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()
andGraph.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()
orrollback()
. In the case of an error, the server can also prematurely end transactions. Thefinished()
method can be used to determine whether or not any of these cases have occurred.The
run()
andevaluate()
methods are used to execute Cypher queries within the transactional context. The remaining methods operate onSubgraph
objects, including derivatives such asNode
andRelationship
.-
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 otherSubgraph
-
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 otherSubgraph
Returns: True
if all entities exist remotely,False
otherwise
-
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 otherSubgraph
object - primary_label – label on which to match any existing nodes
- primary_key – property key(s) on which to match any existing nodes
- subgraph – a
-
pull
(subgraph)[source]¶ Update local entities from their remote counterparts.
For any nodes and relationships that exist in both the local
Subgraph
and the remoteGraph
, pull properties and node labels into the local copies. This operation does not create or delete any entities.Parameters: subgraph – a Node
,Relationship
or otherSubgraph
-
push
(subgraph)[source]¶ Update remote entities from their local counterparts.
For any nodes and relationships that exist in both the local
Subgraph
and the remoteGraph
, push properties and node labels into the remote copies. This operation does not create or delete any entities.Parameters: subgraph – a Node
,Relationship
or otherSubgraph
-
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 otherSubgraph
-
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 thecurrent
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 orNone
if neither the field nor the record are present:print(cursor.evaluate())
-
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
-
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
-
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.
-
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 anamedtuple
but allows field access only through bracketed syntax, and provides more functionality.Record
extends bothtuple
andMapping
.-
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 anIndexError
.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
-
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
-
Table
objects¶
-
class
py2neo.database.work.
Table
(records, keys=None)[source]¶ Immutable list of records.
A
Table
holds a list ofRecord
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
extendslist
.-
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 anio.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 areNone
,False
otherwise.
-
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¶
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.
-
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.
-