py2neo.cypher – Cypher Execution

Cursor objects

class py2neo.cypher.Cursor(result, hydrant=None, sample_size=3)[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())
property 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 execution plan returned by this query, if any.

preview(limit=None)[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 execution statistics for this query.

This contains details of the activity undertaken by the database kernel for the query, such as the number of entities created or deleted.

>>> from py2neo import Graph
>>> g = Graph()
>>> g.run("CREATE (a:Person) SET a.name = 'Alice'").stats()
{'labels_added': 1, 'nodes_created': 1, 'properties_set': 1}
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.cypher.Record(keys, values)[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

Running procedures

class py2neo.cypher.proc.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.

class py2neo.cypher.proc.Procedure(graph, name)[source]

Represents an individual procedure.

New in version 2020.0.

Utilities

py2neo.cypher.cypher_escape(identifier)[source]

Return a Cypher identifier, with escaping if required.

Simple Cypher identifiers, which just contain alphanumerics and underscores, can be represented as-is in expressions. Any which contain more esoteric characters, such as spaces or punctuation, must be escaped in backticks. Backticks themselves are escaped by doubling.

>>> cypher_escape("simple_identifier")
'simple_identifier'
>>> cypher_escape("identifier with spaces")
'`identifier with spaces`'
>>> cypher_escape("identifier with `backticks`")
'`identifier with ``backticks```'

Identifiers are used in Cypher to denote named values, labels, relationship types and property keys. This function will typically be used to construct dynamic Cypher queries in places where parameters cannot be used.

>>> "MATCH (a:{label}) RETURN id(a)".format(label=cypher_escape("Employee of the Month"))
'MATCH (a:`Employee of the Month`) RETURN id(a)'
Parameters:

identifier – any non-empty string

py2neo.cypher.cypher_join(*clauses, **parameters)[source]

Join multiple Cypher clauses, returning a (query, parameters) tuple. Each clause may either be a simple string query or a (query, parameters) tuple. Additional parameters may also be supplied as keyword arguments.

Parameters:
  • clauses

  • parameters

Returns:

(query, parameters) tuple

py2neo.cypher.cypher_repr(value, **kwargs)[source]

Return the Cypher representation of a value.

This function attempts to convert the supplied value into a Cypher literal form, as used in expressions.

py2neo.cypher.cypher_str(value, **kwargs)[source]

Convert a Cypher value to a Python Unicode string.

This function converts the supplied value into a string form, as used for human-readable output. This is generally identical to cypher_repr() except for with string values, which are returned as-is, instead of being enclosed in quotes with certain characters escaped.