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[source]

The GraphService class is the top-level accessor for an entire Neo4j graph database management system (DBMS). Within the py2neo object hierarchy, a GraphService contains one or more Graph 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 and store_id, along with the query_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'
connector

The Connector providing communication for this graph service.

New in version 2020.0.

default_graph

The default Graph exposed by this graph service.

classmethod forget_all()[source]

Forget all cached GraphService details.

kernel_version

The Version of Neo4j running.

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 for connector.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[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()[source]

Create a new auto-commit Transaction.

New in version 2020.0.

begin(autocommit=False)[source]

Begin a new Transaction.

Parameters:autocommit – (deprecated) if True, the transaction will automatically commit after the first operation

Changed in version 2020.0: the ‘autocommit’ argument is now deprecated. Use the ‘auto’ method instead.

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() or iter() 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 a Transaction.

Parameters:subgraph – a Node, Relationship or other Subgraph
delete(subgraph)[source]

Run a delete() operation within an autocommit Transaction. To delete only the relationships, use the separate() method.

Note that only entities which are bound to corresponding remote entities though the graph and identity attributes will trigger a deletion.

Parameters:subgraph – a Node, Relationship or other Subgraph 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 autocommit Transaction.

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 autocommit Transaction.

Parameters:subgraph – a Node, Relationship or other Subgraph 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 direction
  • r_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 direction
  • r_type – type of relationships to match (None means any type)
merge(subgraph, label=None, *property_keys)[source]

Run a merge() operation within an autocommit Transaction.

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 other Subgraph object
  • label – label on which to match any existing nodes
  • property_keys – property keys on which to match any existing nodes
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)[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.

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

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
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 run() operation within an autocommit Transaction.

Parameters:
  • cypher – Cypher statement
  • parameters – dictionary of parameters
  • kwparameters – extra keyword parameters
Returns:

schema = None

The Schema resource for this Graph.

separate(subgraph)[source]

Run a separate() operation within an autocommit Transaction.

Note that only relationships which are bound to corresponding remote relationships though the graph and identity attributes will trigger a deletion.

Parameters:subgraph – a Node, Relationship or other Subgraph
service = None

The GraphService to which this Graph belongs.

SystemGraph objects

class py2neo.database.SystemGraph[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.

node_labels

The set of node labels currently defined within the graph.

relationship_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.