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 URIs like neo4j://...
for use with Neo4j causal clusters. To enable routing, instead pass
a routing=True
keyword argument to the Graph
or
GraphService
constructor.
Routing is only available for Bolt-enabled servers. No equivalent currently exists for HTTP.
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') |
routing |
Route connections across multiple servers | bool | False |
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 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.
-
config
¶ A dictionary of the configuration parameters used to configure Neo4j.
>>> gs.config['dbms.connectors.default_advertised_address'] 'localhost'
-
keys
()[source]¶ Return a list of all
Graph
names exposed by this graph service.New in version 2020.0.
-
product
¶ The product name.
-
profile
¶ The
ConnectionProfile
for which this graph service is configured. This attribute is simply a shortcut forconnector.profile
.New in version 2020.0.
-
system_graph
¶ The
SystemGraph
exposed by this graph service.New in version 2020.0.
-
uri
¶ The URI to which this graph service is connected. This attribute is simply a shortcut for
connector.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 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-writeNew in version 2020.0.
-
begin
(autocommit=False, readonly=False)[source]¶ Begin a new
Transaction
.Parameters: - autocommit – (deprecated) if
True
, the transaction will automatically commit after the first operation - readonly – if
True
, will begin a readonly transaction, otherwise will begin as read-write
Changed in version 2020.0: the ‘autocommit’ argument is now deprecated. Use the ‘auto’ method instead.
- autocommit – (deprecated) if
-
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
objectReturns:
-
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 direction - r_type – type of relationships to match (
None
means any type) - limit – maximum number of relationships to match (
None
means unlimited)
- nodes – Sequence or Set of start and end nodes (
-
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 direction - r_type – type of relationships to match (
None
means any type)
- nodes – Sequence or Set of start and end nodes (
-
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
object - label – label on which to match any existing nodes
- property_keys – property keys on which to match any existing nodes
- subgraph – a
-
name
¶ The name of this graph.
New in version 2020.0.
-
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
-
play
(work, args=None, kwargs=None, readonly=None)[source]¶ Call a function representing a transactional unit of work.
The function must always accept a
Transaction
object as its first argument. Additional arguments can be passed though the args and kwargs arguments of this method.A unit of work can be designated “readonly” if the work function has an attribute called readonly which is set to
True
. This can be overridden by using the readonly argument to this method which, if set to eitherTrue
orFalse
, will take precedence.Parameters: - work – function containing the unit of work
- args – sequence of additional positional arguments to pass into the function
- kwargs – mapping of additional keyword arguments to pass into the function
- readonly – set to
True
orFalse
to override the readonly attribute of the work function
New in version 2020.0.
-
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
-
read
(cypher, parameters=None, **kwparameters)[source]¶ Run a single readonly query within an auto-commit
Transaction
.Parameters: - cypher – Cypher statement
- parameters – dictionary of parameters
- kwparameters – extra parameters supplied as keyword arguments
Returns: Raises: TypeError – if the underlying connection profile does not support readonly transactions
-
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.
-
SystemGraph
objects¶
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_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.
-
node_labels
¶ The set of node labels currently defined within the graph.
-
relationship_types
¶ The set of relationship types currently defined within the graph.
-