py2neo.database
– Graph Databases
The py2neo.database
package contains classes and functions required to interact with a Neo4j server. For convenience, many of these classes are also exposed through the top-level package, py2neo
.
The most useful of the classes provided here is the Graph
class which represents a Neo4j graph database instance and provides access to a large portion of the most commonly used py2neo API.
To run a query against a local database is straightforward:
>>> from py2neo import Graph >>> graph = Graph(password="password") >>> graph.run("UNWIND range(1, 3) AS n RETURN n, n * n as n_sq").to_table() n | n_sq -----|------ 1 | 1 2 | 4 3 | 9
Getting connected
The GraphService
, Graph
, and SystemGraph
classes all accept an argument called profile plus individual keyword settings. Internally, these arguments are used to construct a ConnectionProfile
object which holds these details.
The profile can either be a URI or a base ConnectionProfile
object. The settings are individual overrides for the values within that, such as host
or password
. This override mechanism allows several ways of specifying the same information. For example, the three variants below are all equivalent:
>>> from py2neo import Graph >>> graph_1 = Graph() >>> graph_2 = Graph(host="localhost") >>> graph_3 = Graph("bolt://localhost:7687")
Omitting the profile argument completely falls back to using the default ConnectionProfile
. More on this, and other useful information, can be found in the documentation for that class.
URIs
The general format of a URI is <scheme>://[<user>[:<password>]@]<host>[:<port>]
. Supported URI schemes are:
-
bolt
- Bolt (unsecured) -
bolt+s
- Bolt (secured with full certificate checks) -
bolt+ssc
- Bolt (secured with no certificate checks) -
http
- HTTP (unsecured) -
https
- HTTP (secured with full certificate checks) -
http+s
- HTTP (secured with full certificate checks) -
http+ssc
- HTTP (secured with no certificate checks)
Note that py2neo does not support routing with a Neo4j causal cluster, so neo4j://...
URIs are not available. For this functionality, please use the official Neo4j Driver for Python.
Individual settings
The full set of supported settings are:
Keyword | Description | Type | Default |
---|---|---|---|
scheme | Use a specific URI scheme | str | 'bolt' |
secure | Use a secure connection (TLS) | bool | False |
verify | Verify the server certificate (if secure) | bool | True |
host | Database server host name | str | 'localhost' |
port | Database server port | int | 7687 |
address | Colon-separated host and port string | str | 'localhost:7687' |
user | User to authenticate as | str | 'neo4j' |
password | Password to use for authentication | str | 'password' |
auth | A 2-tuple of (user, password) | tuple | ('neo4j', 'password') |
GraphService
objects
-
class
py2neo.database.``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 ofbolt://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, specificallykernel_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 aSHOW 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 aGraph
by name.New in version 2020.0.**propertyconfig
A dictionary of the configuration parameters used to configure Neo4j.>>> gs.config['dbms.connectors.default_advertised_address'] 'localhost'
propertyconnector
TheConnector
providing communication for this graph service.New in version 2020.0.**propertydefault_graph
The defaultGraph
exposed by this graph service.classmethodforget_all
()[source]Forget all cachedGraphService
details.propertykernel_version
TheVersion
of Neo4j running.keys
()[source]Return a list of allGraph
names exposed by this graph service.New in version 2020.0.**propertyproduct
The product name.propertyprofile
TheConnectionProfile
for which this graph service is configured. This attribute is simply a shortcut forconnector.profile
.New in version 2020.0.**propertysystem_graph
TheSystemGraph
exposed by this graph service.New in version 2020.0.**propertyuri
The URI to which this graph service is connected. This attribute is simply a shortcut forconnector.profile.uri
.
Graph
objects
-
class
py2neo.database.``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 CypherSHOW 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 theSystemGraph
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, theGraph
class can accept several other settings:KeywordDescriptionTypeDefaultuser_agent
User agent to send for all connectionsstr(depends on URI scheme)max_connections
The maximum number of simultaneous connections permittedint40Once obtained, the Graph instance provides direct or indirect access to most of the functionality available within py2neo.auto
()[source]Create a new auto-commitTransaction
.New in version 2020.0.begin
(autocommit=False)[source]Begin a newTransaction
.Parametersautocommit – (deprecated) ifTrue
, the transaction will automatically commit after the first operationChanged in version 2020.0: the ‘autocommit’ argument is now deprecated. Use the ‘auto’ method instead.**propertycall
Accessor for listing and calling procedures.This property contains aProcedureLibrary
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 aCursor
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
Usingdir()
oriter()
on the call attribute will yield a list of available procedure names.New in version 2020.0.create
(subgraph)[source]Run acreate()
operation within aTransaction
.Parameterssubgraph – aNode
,Relationship
or otherSubgraph
delete
(subgraph)[source]Run adelete()
operation within an autocommitTransaction
. To delete only the relationships, use theseparate()
method.Note that only entities which are bound to corresponding remote entities though thegraph
andidentity
attributes will trigger a deletion.Parameterssubgraph – aNode
,Relationship
or otherSubgraph
objectdelete_all
()[source]Delete all nodes and relationships from thisGraph
.Warning This method will permanently remove all nodes and relationships from the graph and cannot be undone.evaluate
(cypher, parameters=None, kwparameters)[source]Run aevaluate()
operation within an autocommitTransaction
.Parameterscypher* – Cypher statementparameters – dictionary of parametersReturnsfirst value from the first record returned orNone
.exists
(subgraph)[source]Run aexists()
operation within an autocommitTransaction
.Parameterssubgraph – aNode
,Relationship
or otherSubgraph
objectReturnsmatch
(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"])
Parametersnodes – 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.Parametersnodes – 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 amerge()
operation within an autocommitTransaction
.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 themerge()
method. Note that this is different to a Cypher MERGE.Parameterssubgraph* – aNode
,Relationship
or otherSubgraph
objectlabel – label on which to match any existing nodesproperty_keys – property keys on which to match any existing nodesproperty*name
The name of this graph.New in version 2020.0.**propertynodes
ANodeMatcher
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 ``play
(work, args=None, kwargs=None)[source]Call a function representing a transactional unit of work.The function must always accept aTransaction
object as its first argument. Additional arguments can be passed though the args and kwargs arguments of this method.Parameterswork – function containing the unit of workargs – sequence of additional positional arguments to pass into the functionkwargs – mapping of additional keyword arguments to pass into the functionNew in version 2020.0.pull
(subgraph)[source]Pull data to one or more entities from their remote counterparts.Parameterssubgraph – the collection of nodes and relationships to pullpush
(subgraph)[source]Push data from one or more entities to their remote counterparts.Parameterssubgraph – the collection of nodes and relationships to pushpropertyrelationships
ARelationshipMatcher
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 arun()
operation within an autocommitTransaction
.Parameterscypher** – Cypher statement**parameters** – dictionary of parameters**kwparameters** – extra keyword parametersReturns`schema` = NoneTheSchema
resource for thisGraph
.separate
(subgraph)[source]Run aseparate()
operation within an autocommitTransaction
.Note that only relationships which are bound to corresponding remote relationships though thegraph
andidentity
attributes will trigger a deletion.Parameterssubgraph – aNode
,Relationship
or otherSubgraph
service
= NoneTheGraphService
to which thisGraph
belongs.
SystemGraph
objects
-
class
py2neo.database.``SystemGraph
(profile=None, **settings)[source]A subclass of
Graph
that provides access to the system database for the remote DBMS. This is only available in Neo4j 4.0 and above.New in version 2020.0.
Schema
objects
-
class
py2neo.database.``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_index
(label, property_keys)[source]Remove label index for a given property key.drop_uniqueness_constraint
(label*, property_key)[source]Remove the node uniqueness constraint for a given label and property key.get_indexes
(label)[source]Fetch a list of indexed property keys for a label.get_uniqueness_constraints
(label)[source]Fetch a list of unique constraints for a label. Each constraint is the name of a single property key.propertynode_labels
The set of node labels currently defined within the graph.propertyrelationship_types
The set of relationship types currently defined within the graph.
ProcedureLibrary
objects
-
class
py2neo.database.``ProcedureLibrary
(graph)[source]Accessor for listing and calling procedures.This object is typically constructed and accessed via the
Graph.call()
attribute. See the documentation for that attribute for usage information.New in version 2020.0.
Procedure
objects¶
-
class
py2neo.database.``Procedure
(graph, name)[source]Represents an individual procedure.New in version 2020.0.