py2neo.database.work – Database workflow

The py2neo.database.work package contains classes pertaining to the execution of Cypher queries and transactions.

Transaction objects

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

Logical context for one or more graph operations.

Transaction objects are typically constructed by the Graph.auto() and Graph.begin() methods. User applications should not generally need to create these objects directly.

Each transaction has a lifetime which ends by a call to either commit() or rollback(). In the case of an error, the server can also prematurely end transactions. The finished() method can be used to determine whether or not any of these cases have occurred.

The run() and evaluate() methods are used to execute Cypher queries within the transactional context. The remaining methods operate on Subgraph objects, including derivatives such as Node and Relationship.

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

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

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

Query result data

Cursor objects

class py2neo.database.work.Cursor(result, hydrant=None, entities=None)[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(*keys)[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'}]
Parameters:keys – indexes or keys of the items to include; if none are provided, all values will be included
Returns:list of dictionary of values, keyed by field name
Raises:IndexError – if an out-of-bounds index is specified
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.

preview(limit=1)[source]

Construct a Table containing a preview of upcoming records, including no more than the given limit.

Parameters:limit – maximum number of records to include in the preview
Returns:Table containing the previewed records
stats()[source]

Return the query statistics.

This contains details of the activity undertaken by the database kernel for the query, such as the number of entities created or deleted. Specifically, this returns a CypherStats object.

>>> from py2neo import Graph
>>> g = Graph()
>>> g.run("CREATE (a:Person) SET a.name = 'Alice'").stats()
constraints_added: 0
constraints_removed: 0
contained_updates: True
indexes_added: 0
indexes_removed: 0
labels_added: 1
labels_removed: 0
nodes_created: 1
nodes_deleted: 0
properties_set: 1
relationships_created: 0
relationships_deleted: 0
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

Record objects

class py2neo.database.work.Record[source]

A Record object holds an ordered, keyed collection of values. It is in many ways similar to a namedtuple but allows field access only through bracketed syntax, and provides more functionality. Record extends both tuple and Mapping.

record[index]
record[key]

Return the value of record with the specified key or index.

len(record)

Return the number of fields in record.

dict(record)

Return a dict representation of record.

data(*keys)[source]

Return the keys and values of this record as a dictionary, optionally including only certain values by index or key. Keys provided that do not exist within the record will be included but with a value of None; indexes provided that are out of bounds will trigger an IndexError.

Parameters:keys – indexes or keys of the items to include; if none are provided, all values will be included
Returns:dictionary of values, keyed by field name
Raises:IndexError if an out-of-bounds index is specified
get(key, default=None)[source]

Obtain a single value from the record by index or key. If the specified item does not exist, the default value is returned.

Parameters:
  • key – index or key
  • default – default value to be returned if key does not exist
Returns:

selected value

index(key)[source]

Return the index of the given item.

items(*keys)[source]

Return the fields of the record as a list of key and value tuples

Parameters:keys – indexes or keys of the items to include; if none are provided, all values will be included
Returns:list of (key, value) tuples
keys()[source]

Return the keys of the record.

Returns:list of key names
to_subgraph()[source]

Return a Subgraph containing the union of all the graph structures within this Record.

Returns:Subgraph object
values(*keys)[source]

Return the values of the record, optionally filtering to include only certain values by index or key.

Parameters:keys – indexes or keys of the items to include; if none are provided, all values will be included
Returns:list of values

Table objects

class py2neo.database.work.Table(records, keys=None)[source]

Immutable list of records.

A Table holds a list of Record objects, typically received as the result of a Cypher query. It provides a convenient container for working with a result in its entirety and provides methods for conversion into various output formats. Table extends list.

repr(table)

Return a string containing an ASCII art representation of this table. Internally, this method calls write() with header=True, writing the output into an io.StringIO instance.

field(key)[source]

Return a dictionary of metadata for a given field. The metadata includes the following values:

type
Single class or tuple of classes representing the field values.
numeric
True if all field values are of a numeric type, False otherwise.
optional
True if any field values are None, False otherwise.
keys()[source]

Return a list of field names for this table.

write(file=None, header=None, skip=None, limit=None, auto_align=True, padding=1, separator='|', newline='\r\n')[source]

Write data to a human-readable ASCII art table.

Parameters:
  • file – file-like object capable of receiving output
  • header – boolean flag for addition of column headers
  • skip – number of records to skip before beginning output
  • limit – maximum number of records to include in output
  • auto_align – if True, right-justify numeric values
  • padding – number of spaces to include between column separator and value
  • separator – column separator character
  • newline – newline character sequence
Returns:

the number of records included in output

write_csv(file=None, header=None, skip=None, limit=None)[source]

Write the data as RFC4180-compatible comma-separated values. This is a customised call to write_separated_values().

write_html(file=None, header=None, skip=None, limit=None, auto_align=True)[source]

Write data to an HTML table.

Parameters:
  • file – file-like object capable of receiving output
  • header – boolean flag for addition of column headers
  • skip – number of records to skip before beginning output
  • limit – maximum number of records to include in output
  • auto_align – if True, right-justify numeric values
Returns:

the number of records included in output

write_separated_values(separator, file=None, header=None, skip=None, limit=None, newline='\r\n', quote='"')[source]

Write data to a delimiter-separated file.

Parameters:
  • separator – field separator character
  • file – file-like object capable of receiving output
  • header – boolean flag or string style tag, such as ‘i’ or ‘cyan’, for addition of column headers
  • skip – number of records to skip before beginning output
  • limit – maximum number of records to include in output
  • newline – newline character sequence
  • quote – quote character
Returns:

the number of records included in output

write_tsv(file=None, header=None, skip=None, limit=None)[source]

Write the data as tab-separated values. This is a customised call to write_separated_values().

Query result summaries

CypherSummary objects

class py2neo.database.work.CypherSummary(**data)[source]

CypherStats objects

class py2neo.database.work.CypherStats(**stats)[source]

Container for a set of statistics drawn from Cypher query execution.

Each value can be accessed as either an attribute or via a string index. This class implements Mapping to allow it to be used as a dictionary.

constraints_added = 0

Number of constraints added.

constraints_removed = 0

Number of constraints removed.

contained_updates = False

Boolean flag to indicate whether or not the query contained an update.

indexes_added = 0

Number of indexes added.

indexes_removed = 0

Number of indexes removed.

keys()[source]

Full list of the key or attribute names of the statistics available.

labels_added = 0

Number of node labels added.

labels_removed = 0

Number of node labels removed.

nodes_created = 0

Number of nodes created.

nodes_deleted = 0

Number of nodes deleted.

properties_set = 0

Number of property values set.

relationships_created = 0

Number of relationships created.

relationships_deleted = 0

Number of relationships deleted.

CypherPlan objects

class py2neo.database.work.CypherPlan(**kwargs)[source]
keys() → a set-like object providing a view on D's keys[source]

Errors

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

Base exception for all errors signalled by Neo4j.

ClientError exceptions

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

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

DatabaseError exceptions

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

The database failed to service the request.

TransientError exceptions

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

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