Workflow¶
GraphService
objects¶
- class py2neo.GraphService(profile=None, **settings)[source]¶
The
GraphService
class is the top-level accessor for an entire Neo4j graph database management system (DBMS). Within the py2neo object hierarchy, aGraphService
contains one or moreGraph
objects in which data storage and retrieval activity chiefly occurs.An explicit URI can be passed to the constructor:
>>> from py2neo import GraphService >>> gs = GraphService("bolt://camelot.example.com:7687")
Alternatively, the default value of
bolt://localhost:7687
is used:>>> default_gs = GraphService() >>> default_gs <GraphService uri='bolt://localhost:7687'>
Note
Some attributes of this class available in earlier versions of py2neo are no longer available, specifically
kernel_start_time
,primitive_counts
,store_creation_time
,store_file_sizes
andstore_id
, along with thequery_jmx
method. This is due to a change in Neo4j 4.0 relating to how certain system metadata is exposed. Replacement functionality may be reintroduced in a future py2neo release.Changed in 2020.0: this class was formerly known as ‘Database’, but was renamed to avoid confusion with the concept of the same name introduced with the multi-database feature of Neo4j 4.0.
- iter(graph_service)
Yield all named graphs.
For Neo4j 4.0 and above, this yields the names returned by a
SHOW DATABASES
query. For earlier versions, this yields no entries, since the one and only graph in these versions is not named.New in version 2020.0.
- graph_service[name]
Access a
Graph
by name.New in version 2020.0.
- property config¶
A dictionary of the configuration parameters used to configure Neo4j.
>>> gs.config['dbms.connectors.default_advertised_address'] 'localhost'
- property connector¶
The
Connector
providing communication for this graph service.New in version 2020.0.
- keys()[source]¶
Return a list of all
Graph
names exposed by this graph service.New in version 2020.0.
- property product¶
The product name.
- property profile¶
The
ConnectionProfile
for which this graph service is configured. This attribute is simply a shortcut forconnector.profile
.New in version 2020.0.
- property system_graph¶
The
SystemGraph
exposed by this graph service.New in version 2020.0.
- property uri¶
The URI to which this graph service is connected. This attribute is simply a shortcut for
connector.profile.uri
.
Graph
objects¶
- class py2neo.Graph(profile=None, name=None, **settings)[source]¶
The Graph class provides a handle to an individual named graph database exposed by a Neo4j graph database service.
Connection details are provided using either a URI or a
ConnectionProfile
, plus individual settings, if required.The name argument allows selection of a graph database by name. When working with Neo4j 4.0 and above, this can be any name defined in the system catalogue, a full list of which can be obtained through the Cypher
SHOW DATABASES
command. Passing None here will select the default database, as defined on the server. For earlier versions of Neo4j, the name must be set to None.>>> from py2neo import Graph >>> sales = Graph("bolt+s://g.example.com:7687", name="sales") >>> sales.run("MATCH (c:Customer) RETURN c.name") c.name --------------- John Smith Amy Pond Rory Williams
The system graph, which is available in all 4.x+ product editions, can also be accessed via the
SystemGraph
class.>>> from py2neo import SystemGraph >>> sg = SystemGraph("bolt+s://g.example.com:7687") >>> sg.call("dbms.security.listUsers") username | roles | flags ----------|-------|------- neo4j | null | []
In addition to the core connection details that can be passed to the constructor, the
Graph
class can accept several other settings:Keyword
Description
Type
Default
user_agent
User agent to send for all connections
str
(depends on URI scheme)
max_connections
The maximum number of simultaneous connections permitted
int
40
Once obtained, the Graph instance provides direct or indirect access to most of the functionality available within py2neo.
- auto(readonly=False)[source]¶
Create a new auto-commit
Transaction
.- Parameters:
readonly – if
True
, will begin a readonly transaction, otherwise will begin as read-write
New in version 2020.0.
- begin(readonly=False)[source]¶
Begin a new
Transaction
.- Parameters:
readonly – if
True
, will begin a readonly transaction, otherwise will begin as read-write
Changed in version 2021.1: the ‘autocommit’ argument has been removed. Use the ‘auto’ method instead.
- property call¶
Accessor for listing and calling procedures.
This property contains a
ProcedureLibrary
object tied to this graph, which provides links to Cypher procedures in the underlying implementation.Calling a procedure requires only the regular Python function call syntax:
>>> g = Graph() >>> g.call.dbms.components() name | versions | edition --------------|------------|----------- Neo4j Kernel | ['3.5.12'] | community
The object returned from the call is a
Cursor
object, identical to that obtained from running a normal Cypher query, and can therefore be consumed in a similar way.Procedure names can alternatively be supplied as a string:
>>> g.call["dbms.components"]() name | versions | edition --------------|------------|----------- Neo4j Kernel | ['3.5.12'] | community
Using
dir()
oriter()
on the call attribute will yield a list of available procedure names.New in version 2020.0.
- create(subgraph)[source]¶
Run a
create()
operation within aTransaction
.- Parameters:
subgraph – a
Node
,Relationship
or otherSubgraph
- delete(subgraph)[source]¶
Run a
delete()
operation within an auto-commitTransaction
. To delete only the relationships, use theseparate()
method.Note that only entities which are bound to corresponding remote entities though the
graph
andidentity
attributes will trigger a deletion.- Parameters:
subgraph – a
Node
,Relationship
or otherSubgraph
object
- delete_all()[source]¶
Delete all nodes and relationships from this
Graph
.Warning
This method will permanently remove all nodes and relationships from the graph and cannot be undone.
- evaluate(cypher, parameters=None, **kwparameters)[source]¶
Run a
evaluate()
operation within an auto-commitTransaction
.- Parameters:
cypher – Cypher statement
parameters – dictionary of parameters
- Returns:
first value from the first record returned or
None
.
- exists(subgraph)[source]¶
Run a
exists()
operation within an auto-commitTransaction
.- Parameters:
subgraph – a
Node
,Relationship
or otherSubgraph
object- Returns:
- match(nodes=None, r_type=None, limit=None)[source]¶
Match and return all relationships with specific criteria.
For example, to find all of Alice’s friends:
for rel in graph.match((alice, ), r_type="FRIEND"): print(rel.end_node["name"])
- Parameters:
nodes – Sequence or Set of start and end nodes (
None
means any node); a Set implies a match in any directionr_type – type of relationships to match (
None
means any type)limit – maximum number of relationships to match (
None
means unlimited)
- match_one(nodes=None, r_type=None)[source]¶
Match and return one relationship with specific criteria.
- Parameters:
nodes – Sequence or Set of start and end nodes (
None
means any node); a Set implies a match in any directionr_type – type of relationships to match (
None
means any type)
- merge(subgraph, label=None, *property_keys)[source]¶
Run a
merge()
operation within an auto-commitTransaction
.The example code below shows a simple merge for a new relationship between two new nodes:
>>> from py2neo import Graph, Node, Relationship >>> g = Graph() >>> a = Node("Person", name="Alice", age=33) >>> b = Node("Person", name="Bob", age=44) >>> KNOWS = Relationship.type("KNOWS") >>> g.merge(KNOWS(a, b), "Person", "name")
Following on, we then create a third node (of a different type) to which both the original nodes connect:
>>> c = Node("Company", name="ACME") >>> c.__primarylabel__ = "Company" >>> c.__primarykey__ = "name" >>> WORKS_FOR = Relationship.type("WORKS_FOR") >>> g.merge(WORKS_FOR(a, c) | WORKS_FOR(b, c))
For details of how the merge algorithm works, see the
merge()
method. Note that this is different to a Cypher MERGE.- Parameters:
subgraph – a
Node
,Relationship
or otherSubgraph
objectlabel – label on which to match any existing nodes
property_keys – property keys on which to match any existing nodes
- property name¶
The name of this graph.
New in version 2020.0.
- property nodes¶
A
NodeMatcher
for this graph.This can be used to find nodes that match given criteria:
>>> graph = Graph() >>> graph.nodes[1234] (_1234:Person {name: 'Alice'}) >>> graph.nodes.get(1234) (_1234:Person {name: 'Alice'}) >>> graph.nodes.match("Person", name="Alice").first() (_1234:Person {name: 'Alice'})
Nodes can also be efficiently counted using this attribute:
>>> len(graph.nodes) 55691 >>> len(graph.nodes.match("Person", age=33)) 12
- pull(subgraph)[source]¶
Pull data to one or more entities from their remote counterparts.
- Parameters:
subgraph – the collection of nodes and relationships to pull
- push(subgraph)[source]¶
Push data from one or more entities to their remote counterparts.
- Parameters:
subgraph – the collection of nodes and relationships to push
- query(cypher, parameters=None, timeout=None)[source]¶
Run a single query within a readonly auto-commit
Transaction
.Should query execution fail due to connection failure or other transient error, retries will be attempted. There will be a minimum of three attempts, and retries will continue until the timeout passes.
- Parameters:
cypher – Cypher statement
parameters – dictionary of parameters
timeout –
- Returns:
result
Cursor
object- Raises:
TypeError – if the underlying connection profile does not support readonly transactions
ServiceUnavailable – if the query does not successfully complete
Refactored from read to query in version 2021.1
- property relationships¶
A
RelationshipMatcher
for this graph.This can be used to find relationships that match given criteria as well as efficiently count relationships.
- run(cypher, parameters=None, **kwparameters)[source]¶
Run a single read/write query within an auto-commit
Transaction
.- Parameters:
cypher – Cypher statement
parameters – dictionary of parameters
kwparameters – extra parameters supplied as keyword arguments
- Returns:
- separate(subgraph)[source]¶
Run a
separate()
operation within an auto-commitTransaction
.Note that only relationships which are bound to corresponding remote relationships though the
graph
andidentity
attributes will trigger a deletion.- Parameters:
subgraph – a
Node
,Relationship
or otherSubgraph
- service = None¶
The
GraphService
to which thisGraph
belongs.
- update(cypher, parameters=None, timeout=None)[source]¶
Execute a transactional unit of work that carries out write operations but does not return a result.
The cypher argument can be either a single string statement or a callable that accepts a
Transaction
object as its first argument. Additional arguments can be passed though the args and kwargs arguments of this method.The unit of work may be called multiple times if earlier attempts fail due to connectivity or other transient errors. As such, the function should have no non-idempotent side effects.
Note that hybrid read-write queries (i.e. those which carry out updates and return a result should use the non-retrying
run
method instead.- Parameters:
cypher – cypher string or transaction function containing a unit of work
parameters – cypher parameter map or function arguments
timeout –
- Raises:
WriteServiceUnavailable – if the update does not successfully complete
SystemGraph
objects¶
Schema
objects¶
- class py2neo.Schema(graph)[source]¶
The schema resource attached to a Graph instance.
- create_index(label, *property_keys)[source]¶
Create a schema index for a label and property key combination.
- create_uniqueness_constraint(label, property_key)[source]¶
Create a node uniqueness constraint for a given label and property key.
While indexes support the use of composite keys, unique constraints may only be tied to a single property key.
- drop_uniqueness_constraint(label, property_key)[source]¶
Remove the node uniqueness constraint for a given label and property key.
- get_uniqueness_constraints(label)[source]¶
Fetch a list of unique constraints for a label. Each constraint is the name of a single property key.
- property node_labels¶
The set of node labels currently defined within the graph.
- property relationship_types¶
The set of relationship types currently defined within the graph.
Transaction
objects¶
- class py2neo.Transaction(manager, autocommit=False, readonly=False)[source]¶
Logical context for one or more graph operations.
Transaction objects are typically constructed by the
Graph.auto()
andGraph.begin()
methods. Likewise, theGraph.commit()
andGraph.rollback()
methods can be used to finish a transaction.- graph¶
Graph to which this transaction belongs.
- readonly¶
True
if this is a readonly transaction,False
otherwise.
Cypher execution
The
run()
,evaluate()
andupdate()
methods are used to execute Cypher queries within the transactional context. Each is intended for use with a particular kind of query:run()
for general-purpose query execution,evaluate()
for retrieving single aggregation values andupdate()
for executing Cypher that has no return value.- evaluate(cypher, parameters=None, **kwparameters)[source]¶
Execute a single Cypher query and return the value from the first column of the first record.
- Parameters:
cypher – Cypher statement
parameters – dictionary of parameters
- Returns:
single return value or
None
- run(cypher, parameters=None, **kwparameters)[source]¶
Send a Cypher query to the server for execution and return a
Cursor
for navigating its result.- Parameters:
cypher – Cypher query
parameters – dictionary of parameters
- Returns:
Cursor
object
- update(cypher, parameters=None, **kwparameters)[source]¶
Execute a single Cypher statement and discard any result returned.
- Parameters:
cypher – Cypher statement
parameters – dictionary of parameters
Subgraph operations
The methods below all operate on
Subgraph
objects, such as nodes and relationships.- create(subgraph)[source]¶
Create remote nodes and relationships that correspond to those in a local subgraph. Any entities in subgraph that are already bound to remote entities will remain unchanged, those which are not will become bound to their newly-created counterparts.
For example:
>>> from py2neo import Graph, Node, Relationship >>> g = Graph() >>> tx = g.begin() >>> a = Node("Person", name="Alice") >>> tx.create(a) >>> b = Node("Person", name="Bob") >>> ab = Relationship(a, "KNOWS", b) >>> tx.create(ab) >>> tx.commit() >>> g.exists(ab) True
- Parameters:
subgraph – a
Node
,Relationship
or other creatable object
- delete(subgraph)[source]¶
Delete the remote nodes and relationships that correspond to those in a local subgraph. To delete only the relationships, use the
separate()
method.- Parameters:
subgraph – a
Node
,Relationship
or otherSubgraph
- exists(subgraph)[source]¶
Determine whether one or more entities all exist within the graph. Note that if any nodes or relationships in subgraph are not bound to remote counterparts, this method will return
False
.- Parameters:
subgraph – a
Node
,Relationship
or otherSubgraph
- Returns:
True
if all entities exist remotely,False
otherwise
- merge(subgraph, primary_label=None, primary_key=None)[source]¶
Create or update the nodes and relationships of a local subgraph in the remote database. Note that the functionality of this operation is not strictly identical to the Cypher MERGE clause, although there is some overlap.
Each node and relationship in the local subgraph is merged independently, with nodes merged first and relationships merged second.
For each node, the merge is carried out by comparing that node with a potential remote equivalent on the basis of a single label and property value. If no remote match is found, a new node is created; if a match is found, the labels and properties of the remote node are updated. The label and property used for comparison are determined by the primary_label and primary_key arguments but may be overridden for individual nodes by the of __primarylabel__ and __primarykey__ attributes on the node itself.
For each relationship, the merge is carried out by comparing that relationship with a potential remote equivalent on the basis of matching start and end nodes plus relationship type. If no remote match is found, a new relationship is created; if a match is found, the properties of the remote relationship are updated.
- Parameters:
subgraph – a
Node
,Relationship
or otherSubgraph
objectprimary_label – label on which to match any existing nodes
primary_key – property key(s) on which to match any existing nodes
- pull(subgraph)[source]¶
Update local entities from their remote counterparts.
For any nodes and relationships that exist in both the local
Subgraph
and the remoteGraph
, pull properties and node labels into the local copies. This operation does not create or delete any entities.- Parameters:
subgraph – a
Node
,Relationship
or otherSubgraph
- push(subgraph)[source]¶
Update remote entities from their local counterparts.
For any nodes and relationships that exist in both the local
Subgraph
and the remoteGraph
, push properties and node labels into the remote copies. This operation does not create or delete any entities.- Parameters:
subgraph – a
Node
,Relationship
or otherSubgraph
- separate(subgraph)[source]¶
Delete the remote relationships that correspond to those in a local subgraph. This leaves any nodes untouched.
- Parameters:
subgraph – a
Node
,Relationship
or otherSubgraph
Deprecated methods
The
commit()
androllback()
methods are deprecated. Instead, the similarly-named methods on the parentGraph
should be used, with this transaction as an argument.- commit(**kwargs)¶
Commit the transaction.
- rollback(**kwargs)¶
Roll back the current transaction, undoing all actions previously taken.