2. py2neo.database – Graph Databases

The py2neo.database package contains classes and functions required to interact with a Neo4j server. The most important of these 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

2.1. The Database

class py2neo.database.Database[source]

Accessor for an entire Neo4j graph database installation over Bolt or HTTP. Within the py2neo object hierarchy, a Database contains a Graph in which most activity occurs. Currently, Neo4j only supports one Graph per Database.

An explicit URI can be passed to the constructor:

>>> from py2neo import Database
>>> db = Database("bolt://camelot.example.com:7687")

Alternatively, the default value of bolt://localhost:7687 is used:

>>> default_db = Database()
>>> default_db
<Database uri='bolt://localhost:7687'>
config

Return a dictionary of the configuration parameters used to configure Neo4j.

default_graph

The default graph exposed by this database.

Return type:Graph
classmethod forget_all()[source]

Forget all cached Database details.

kernel_start_time

Return the time from which this Neo4j instance was in operational mode.

kernel_version

Return the version of Neo4j.

name

Return the name of the active Neo4j database.

primitive_counts

Return a dictionary of estimates of the numbers of different kinds of Neo4j primitives.

product

Return the product name.

query_jmx(namespace, instance=None, name=None, type=None)[source]

Query the JMX service attached to this database.

store_creation_time

Return the time when this Neo4j graph store was created.

store_file_sizes

Return a dictionary of file sizes for each file in the Neo4j graph store.

store_id

Return an identifier that, together with store creation time, uniquely identifies this Neo4j graph store.

uri

The URI to which this Database is connected.

2.2. The Graph

class py2neo.database.Graph(uri, **settings)[source]

The Graph class represents the graph data storage space within a Neo4j graph database. Connection details are provided using URIs and/or individual settings.

Supported URI schemes are:

  • http
  • https
  • bolt
  • bolt+routing

The full set of supported settings are:

Keyword Description Type Default
auth A 2-tuple of (user, password) tuple ('neo4j', 'password')
host Database server host name str 'localhost'
password Password to use for authentication str 'password'
port Database server port int 7687
scheme Use a specific URI scheme str 'bolt'
secure Use a secure connection (TLS) bool False
user User to authenticate as str 'neo4j'
user_agent User agent to send for all connections str (depends on URI scheme)

Each setting can be provided as a keyword argument or as part of an http:, https:, bolt: or bolt+routing: URI. Therefore, the examples below are equivalent:

>>> from py2neo import Graph
>>> graph_1 = Graph()
>>> graph_2 = Graph(host="localhost")
>>> graph_3 = Graph("bolt://localhost:7687")

Once obtained, the Graph instance provides direct or indirect access to most of the functionality available within py2neo.

begin(autocommit=False)[source]

Begin a new Transaction.

Parameters:autocommit – if True, the transaction will automatically commit after the first operation
create(subgraph)[source]

Run a Transaction.create() operation within a Transaction.

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

The Database to which this Graph belongs.

delete(subgraph)[source]

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

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

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
nodes

Obtain 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
relationships

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

Parameters:subgraph – a Node, Relationship or other Subgraph
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_keys)[source]

Create a uniqueness constraint for a label.

drop_index(label, *property_keys)[source]

Remove label index for a given property key.

drop_uniqueness_constraint(label, *property_keys)[source]

Remove the uniqueness constraint for a given 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.

node_labels

The set of node labels currently defined within the graph.

relationship_types

The set of relationship types currently defined within the graph.

2.3. Transaction objects

class py2neo.database.Transaction(autocommit=False)[source]

A transaction is a logical container for multiple Cypher statements.

commit()[source]

Commit the transaction.

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 other Subgraph
evaluate(cypher, parameters=None, **kwparameters)[source]

Execute a single Cypher statement 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

exists(subgraph)[source]

Determine whether one or more graph entities all exist within the database. 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 other Subgraph
Returns:True if all entities exist remotely, False otherwise
finished()[source]

Indicates whether or not this transaction has been completed or is still open.

merge(subgraph, primary_label=None, primary_key=None)[source]

Merge nodes and relationships from a local subgraph into the database. Each node and relationship 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 label and property value. If no remote match is found, a new node is created. The label and property to use for comparison are determined by primary_label and primary_key but may be overridden for individual nodes by the presence of __primarylabel__ and __primarykey__ attributes on the node itself. Note that multiple property keys may be specified by using a tuple.

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.

Parameters:
  • subgraph – a Node, Relationship or other Subgraph object
  • primary_label – label on which to match any existing nodes
  • primary_key – property key(s) on which to match any existing nodes
process()[source]

Send all pending statements to the server for processing.

pull(subgraph)[source]

Update local entities from their remote counterparts.

For any nodes and relationships that exist in both the local Subgraph and the remote Graph, pull properties and node labels into the local copies. This operation does not create or delete any entities.

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

Update remote entities from their local counterparts.

For any nodes and relationships that exist in both the local Subgraph and the remote Graph, push properties and node labels into the remote copies. This operation does not create or delete any entities.

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

Roll back the current transaction, undoing all actions previously taken.

run(cypher, parameters=None, **kwparameters)[source]

Send a Cypher statement to the server for execution and return a Cursor for navigating its result.

Parameters:
  • cypher – Cypher statement
  • parameters – dictionary of parameters
Returns:

Cursor object

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 other Subgraph

2.4. Cursor objects

class py2neo.database.Cursor(result)[source]

A Cursor is a navigator for a stream of records.

A cursor can be thought of as a window onto an underlying data stream. All cursors in py2neo are “forward-only”, meaning that navigation starts before the first record and may proceed only in a forward direction.

It is not generally necessary for application code to instantiate a cursor directly as one will be returned by any Cypher execution method. However, cursor creation requires only a DataSource object which contains the logic for how to access the source data that the cursor navigates.

Many simple cursor use cases require only the forward() method and the current attribute. To navigate through all available records, a while loop can be used:

while cursor.forward():
    print(cursor.current["name"])

If only the first record is of interest, a similar if structure will do the job:

if cursor.forward():
    print(cursor.current["name"])

To combine forward and current into a single step, use the built-in py:func:next function:

print(next(cursor)["name"])

Cursors are also iterable, so can be used in a loop:

for record in cursor:
    print(record["name"])

For queries that are expected to return only a single value within a single record, use the evaluate() method. This will return the first value from the next record or None if neither the field nor the record are present:

print(cursor.evaluate())
close()[source]

Close this cursor and free up all associated resources.

current

Returns the current record or None if no record has yet been selected.

data()[source]

Consume and extract the entire result as a list of dictionaries.

>>> from py2neo import Graph
>>> graph = Graph()
>>> graph.run("MATCH (a:Person) RETURN a.name, a.born LIMIT 4").data()
[{'a.born': 1964, 'a.name': 'Keanu Reeves'},
 {'a.born': 1967, 'a.name': 'Carrie-Anne Moss'},
 {'a.born': 1961, 'a.name': 'Laurence Fishburne'},
 {'a.born': 1960, 'a.name': 'Hugo Weaving'}]
Returns:the full query result
Return type:list of dict
evaluate(field=0)[source]

Return the value of the first field from the next record (or the value of another field if explicitly specified).

This method attempts to move the cursor one step forward and, if successful, selects and returns an individual value from the new current record. By default, this value will be taken from the first value in that record but this can be overridden with the field argument, which can represent either a positional index or a textual key.

If the cursor cannot be moved forward or if the record contains no values, None will be returned instead.

This method is particularly useful when it is known that a Cypher query returns only a single value.

Parameters:field – field to select value from (optional)
Returns:value of the field or None

Example

>>> from py2neo import Graph
>>> g = Graph()
>>> g.run("MATCH (a) WHERE a.email={x} RETURN a.name", x="bob@acme.com").evaluate()
'Bob Robertson'
forward(amount=1)[source]

Attempt to move the cursor one position forward (or by another amount if explicitly specified). The cursor will move position by up to, but never more than, the amount specified. If not enough scope for movement remains, only that remainder will be consumed. The total amount moved is returned.

Parameters:amount – the amount to move the cursor
Returns:the amount that the cursor was able to move
keys()[source]

Return the field names for the records in the stream.

plan()[source]

Return the plan returned with this result, if any.

stats()[source]

Return the query statistics.

summary()[source]

Return the result summary.

to_data_frame(index=None, columns=None, dtype=None)[source]

Consume and extract the entire result as a pandas.DataFrame.

>>> from py2neo import Graph
>>> graph = Graph()
>>> graph.run("MATCH (a:Person) RETURN a.name, a.born LIMIT 4").to_data_frame()
   a.born              a.name
0    1964        Keanu Reeves
1    1967    Carrie-Anne Moss
2    1961  Laurence Fishburne
3    1960        Hugo Weaving

Note

This method requires pandas to be installed.

Parameters:
  • index – Index to use for resulting frame.
  • columns – Column labels to use for resulting frame.
  • dtype – Data type to force.
Warns:

If pandas is not installed

Returns:

DataFrame object.

to_matrix(mutable=False)[source]

Consume and extract the entire result as a sympy.Matrix.

Note

This method requires sympy to be installed.

Parameters:mutable
Returns:Matrix object.
to_ndarray(dtype=None, order='K')[source]

Consume and extract the entire result as a numpy.ndarray.

Note

This method requires numpy to be installed.

Parameters:
  • dtype
  • order
Warns:

If numpy is not installed

Returns:

ndarray object.

to_series(field=0, index=None, dtype=None)[source]

Consume and extract one field of the entire result as a pandas.Series.

Note

This method requires pandas to be installed.

Parameters:
  • field
  • index
  • dtype
Warns:

If pandas is not installed

Returns:

Series object.

to_subgraph()[source]

Consume and extract the entire result as a Subgraph containing the union of all the graph structures within.

Returns:Subgraph object
to_table()[source]

Consume and extract the entire result as a Table object.

Returns:the full query result

2.5. Errors & Warnings

class py2neo.database.GraphError(*args, **kwargs)[source]
class py2neo.database.ClientError(*args, **kwargs)[source]

The Client sent a bad request - changing the request might yield a successful outcome.

class py2neo.database.DatabaseError(*args, **kwargs)[source]

The database failed to service the request.

class py2neo.database.TransientError(*args, **kwargs)[source]

The database cannot service the request right now, retrying later might yield a successful outcome.

class py2neo.database.TransactionFinished(*args, **kwargs)[source]

Raised when actions are attempted against a Transaction that is no longer available for use.