Graphs, Nodes & Relationships

GraphDatabaseService

class py2neo.neo4j.GraphDatabaseService(uri=None)[source]

An instance of a Neo4j database identified by its base URI. Generally speaking, this is the only URI which a system attaching to this service should need to be directly aware of; all further entity URIs will be discovered automatically from within response content when possible (see Hypermedia) or will be derived from existing URIs.

The following code illustrates how to connect to a database server and display its version number:

from py2neo import neo4j

graph_db = neo4j.GraphDatabaseService()
print(graph_db.neo4j_version)
Parameters:uri – the base URI of the database (defaults to <http://localhost:7474/db/data/>)
clear()[source]

Clear all nodes and relationships from the graph.

Warning

This method will permanently remove all nodes and relationships from the graph and cannot be undone.

create(*abstracts)[source]

Create multiple nodes and/or relationships as part of a single batch.

The abstracts provided may use any accepted notation, as described in the section on py2neo fundamentals. For a node, simply pass a dictionary of properties; for a relationship, pass a tuple of (start, type, end) or (start, type, end, data) where start and end may be Node instances or zero-based integral references to other node entities within this batch:

# create a single node
alice, = graph_db.create({"name": "Alice"})

# create multiple nodes
people = graph_db.create(
    {"name": "Alice", "age": 33}, {"name": "Bob", "age": 44},
    {"name": "Carol", "age": 55}, {"name": "Dave", "age": 66},
)

# create two nodes with a connecting relationship
alice, bob, rel = graph_db.create(
    {"name": "Alice"}, {"name": "Bob"},
    (0, "KNOWS", 1, {"since": 2006})
)

# create a node plus a relationship to pre-existing node
ref_node = graph_db.get_reference_node()
alice, rel = graph_db.create(
    {"name": "Alice"}, (ref_node, "PERSON", 0)
)
Returns:list of Node and/or Relationship instances

Warning

This method will always return a list, even when only creating a single node or relationship. To automatically unpack a list containing a single item, append a trailing comma to the variable name on the left of the assignment operation.

delete(*entities)[source]

Delete multiple nodes and/or relationships as part of a single batch.

delete_index(content_type, index_name)[source]

Delete the entire index identified by the type and name supplied.

Parameters:
  • content_type – either neo4j.Node or neo4j.Relationship
  • index_name – the name of the index to delete
Raises LookupError:
 

if the specified index does not exist

find(label, property_key=None, property_value=None)[source]

Iterate through a set of labelled nodes, optionally filtering by property key and value

get_index(content_type, index_name)[source]

Fetch a specific index from the current database, returning an Index instance. If an index with the supplied name and content type does not exist, None is returned.

Parameters:
  • content_type – either neo4j.Node or neo4j.Relationship
  • index_name – the name of the required index
Returns:

an Index instance or None

See also

get_or_create_index()

See also

Index

get_indexed_node(index_name, key, value)[source]

Fetch the first node indexed with the specified details, returning None if none found.

Parameters:
  • index_name – the name of the required index
  • key – the index key
  • value – the index value
Returns:

a Node instance

get_indexed_relationship(index_name, key, value)[source]

Fetch the first relationship indexed with the specified details, returning None if none found.

Parameters:
  • index_name – the name of the required index
  • key – the index key
  • value – the index value
Returns:

a Relationship instance

get_indexes(content_type)[source]

Fetch a dictionary of all available indexes of a given type.

Parameters:content_type – either neo4j.Node or neo4j.Relationship
Returns:a list of Index instances of the specified type
classmethod get_instance(uri)

Fetch a cached instance if one is available, otherwise create, cache and return a new instance.

Parameters:uri – URI of the cached resource
Returns:a resource instance
get_or_create_index(content_type, index_name, config=None)[source]

Fetch a specific index from the current database, returning an Index instance. If an index with the supplied name and content type does not exist, one is created with either the default configuration or that supplied in config:

# get or create a node index called "People"
people = graph_db.get_or_create_index(neo4j.Node, "People")

# get or create a relationship index called "Friends"
friends = graph_db.get_or_create_index(neo4j.Relationship, "Friends")
Parameters:
  • content_type – either neo4j.Node or neo4j.Relationship
  • index_name – the name of the required index
Returns:

an Index instance

See also

get_index()

See also

Index

get_or_create_indexed_node(index_name, key, value, properties=None)[source]

Fetch the first node indexed with the specified details, creating and returning a new indexed node if none found.

Parameters:
  • index_name – the name of the required index
  • key – the index key
  • value – the index value
  • properties – properties for the new node, if one is created (optional)
Returns:

a Node instance

get_properties(*entities)[source]

Fetch properties for multiple nodes and/or relationships as part of a single batch; returns a list of dictionaries in the same order as the supplied entities.

load2neo_version[source]

The load2neo extension version, if available.

load_geoff(geoff)[source]

Load Geoff data via the load2neo extension.

>>> from py2neo import neo4j
>>> graph_db = neo4j.GraphDatabaseService()
>>> graph_db.load_geoff("(alice)<-[:KNOWS]->(bob)")
[{u'alice': Node('http://localhost:7474/db/data/node/1'),
  u'bob': Node('http://localhost:7474/db/data/node/2')}]
Parameters:geoff – geoff data to load
Returns:list of node mappings
match(start_node=None, rel_type=None, end_node=None, bidirectional=False, limit=None)[source]

Iterate through all relationships matching specified criteria.

Examples are as follows:

# all relationships from the graph database
# ()-[r]-()
rels = list(graph_db.match())

# all relationships outgoing from `alice`
# (alice)-[r]->()
rels = list(graph_db.match(start_node=alice))

# all relationships incoming to `alice`
# ()-[r]->(alice)
rels = list(graph_db.match(end_node=alice))

# all relationships attached to `alice`, regardless of direction
# (alice)-[r]-()
rels = list(graph_db.match(start_node=alice, bidirectional=True))

# all relationships from `alice` to `bob`
# (alice)-[r]->(bob)
rels = list(graph_db.match(start_node=alice, end_node=bob))

# all relationships outgoing from `alice` of type "FRIEND"
# (alice)-[r:FRIEND]->()
rels = list(graph_db.match(start_node=alice, rel_type="FRIEND"))

# up to three relationships outgoing from `alice` of type "FRIEND"
# (alice)-[r:FRIEND]->()
rels = list(graph_db.match(start_node=alice, rel_type="FRIEND", limit=3))
Parameters:
  • start_node – concrete start Node to match or None if any
  • rel_type – type of relationships to match or None if any
  • end_node – concrete end Node to match or None if any
  • bidirectionalTrue if reversed relationships should also be included
  • limit – maximum number of relationships to match or None if no limit
Returns:

matching relationships

Return type:

generator

match_one(start_node=None, rel_type=None, end_node=None, bidirectional=False)[source]

Fetch a single relationship matching specified criteria.

Parameters:
  • start_node – concrete start Node to match or None if any
  • rel_type – type of relationships to match or None if any
  • end_node – concrete end Node to match or None if any
  • bidirectionalTrue if reversed relationships should also be included
Returns:

a matching Relationship or None

neo4j_version[source]

The database software version as a 4-tuple of (int, int, int, str).

node(id_)[source]

Fetch a node by ID.

node_labels[source]

The set of node labels currently defined within the graph.

order[source]

The number of nodes in this graph.

relationship(id_)[source]

Fetch a relationship by ID.

relationship_types[source]

The set of relationship types currently defined within the graph.

schema[source]

The Schema resource for this graph.

See also

Schema

size[source]

The number of relationships in this graph.

supports_index_uniqueness_modes[source]

Indicates whether the server supports get_or_create and create_or_fail uniqueness modes on batched index methods.

supports_node_labels[source]

Indicates whether the server supports node labels.

supports_schema_indexes[source]

Indicates whether the server supports schema indexes.

Nodes & Relationships

class py2neo.neo4j.Node(uri)[source]

A node within a graph, identified by a URI. For example:

>>> from py2neo import neo4j
>>> alice = neo4j.Node("http://localhost:7474/db/data/node/1")

Typically, concrete nodes will not be constructed directly in this way by client applications. Instead, methods such as GraphDatabaseService.create() build node objects indirectly as required. Once created, nodes can be treated like any other container type so as to manage properties:

# get the `name` property of `node`
name = node["name"]

# set the `name` property of `node` to `Alice`
node["name"] = "Alice"

# delete the `name` property from `node`
del node["name"]

# determine the number of properties within `node`
count = len(node)

# determine existence of the `name` property within `node`
if "name" in node:
    pass

# iterate through property keys in `node`
for key in node:
    value = node[key]
Parameters:uri – URI identifying this node
__str__()[source]

Return Cypher/Geoff style representation of this node.

_id

Return the internal ID for this entity.

Returns:integer ID of this entity within the database or None if abstract
classmethod abstract(**properties)[source]

Create and return a new abstract node containing properties drawn from the keyword arguments supplied. An abstract node is not bound to a concrete node within a database but properties can be managed similarly to those within bound nodes:

>>> alice = Node.abstract(name="Alice")
>>> alice["name"]
'Alice'
>>> alice["age"] = 34
alice.get_properties()
{'age': 34, 'name': 'Alice'}

If more complex property keys are required, abstract nodes may be instantiated with the ** syntax:

>>> alice = Node.abstract(**{"first name": "Alice"})
>>> alice["first name"]
'Alice'
Parameters:properties – node properties
add_labels(*labels)[source]

Add one or more labels to this node.

For example:

>>> from py2neo import neo4j, node
>>> graph_db = neo4j.GraphDatabaseService()
>>> alice, = graph_db.create(node(name="Alice"))
>>> alice.add_labels("female", "human")
Parameters:labels – one or more text labels
create_path(*items)[source]

Create a new path, starting at this node and chaining together the alternating relationships and nodes provided:

(self)-[rel_0]->(node_0)-[rel_1]->(node_1) ...
       |-----|  |------| |-----|  |------|
 item:    0        1        2        3

Each relationship may be specified as one of the following:

  • an existing Relationship instance
  • a string holding the relationship type, e.g. “KNOWS”
  • a (str, dict) tuple holding both the relationship type and its properties, e.g. (“KNOWS”, {“since”: 1999})

Nodes can be any of the following:

  • an existing Node instance
  • an integer containing the ID of an existing node
  • a dict holding a set of properties for a new node
  • a 3-tuple holding an index name, key and value for identifying indexed nodes, e.g. (“People”, “email”, “bob@example.com”)
  • None, representing an unspecified node that will be created as required
Parameters:items – alternating relationships and nodes
Returns:Path object representing the newly-created path
delete()

Delete this entity from the database.

delete_properties()

Delete all properties.

Delete this node along with all related nodes and relationships.

exists

Detects whether this entity still exists in the database.

get_cached_properties()

Fetch last known properties without calling the server.

Returns:dictionary of properties
get_labels()[source]

Fetch all labels associated with this node.

Returns:set of text labels
get_or_create_path(*items)[source]

Identical to create_path except will reuse parts of the path which already exist.

Some examples:

# add dates to calendar, starting at calendar_root
christmas_day = calendar_root.get_or_create_path(
    "YEAR",  {"number": 2000},
    "MONTH", {"number": 12},
    "DAY",   {"number": 25},
)
# `christmas_day` will now contain a `Path` object
# containing the nodes and relationships used:
# (CAL)-[:YEAR]->(2000)-[:MONTH]->(12)-[:DAY]->(25)

# adding a second, overlapping path will reuse
# nodes and relationships wherever possible
christmas_eve = calendar_root.get_or_create_path(
    "YEAR",  {"number": 2000},
    "MONTH", {"number": 12},
    "DAY",   {"number": 24},
)
# `christmas_eve` will contain the same year and month nodes
# as `christmas_day` but a different (new) day node:
# (CAL)-[:YEAR]->(2000)-[:MONTH]->(12)-[:DAY]->(25)
#                                  |
#                                [:DAY]
#                                  |
#                                  v
#                                 (24)
get_properties()

Fetch all properties.

Returns:dictionary of properties
is_abstract

Indicates whether this entity is abstract (i.e. not bound to a concrete entity within the database)

isolate()[source]

Delete all relationships connected to this node, both incoming and outgoing.

match(rel_type=None, other_node=None, limit=None)[source]

Iterate through matching relationships attached to this node, regardless of direction.

Parameters:
  • rel_type – type of relationships to match or None if any
  • other_node – concrete Node to match for other end of relationship or None if any
  • limit – maximum number of relationships to match or None if no limit
Returns:

matching relationships

Return type:

generator

match_incoming(rel_type=None, start_node=None, limit=None)[source]

Iterate through matching relationships where this node is the end node.

Parameters:
  • rel_type – type of relationships to match or None if any
  • start_node – concrete start Node to match or None if any
  • limit – maximum number of relationships to match or None if no limit
Returns:

matching relationships

Return type:

generator

match_outgoing(rel_type=None, end_node=None, limit=None)[source]

Iterate through matching relationships where this node is the start node.

Parameters:
  • rel_type – type of relationships to match or None if any
  • end_node – concrete end Node to match or None if any
  • limit – maximum number of relationships to match or None if no limit
Returns:

matching relationships

Return type:

generator

remove_labels(*labels)[source]

Remove one or more labels from this node.

Parameters:labels – one or more text labels
set_labels(*labels)[source]

Replace all labels on this node.

Parameters:labels – one or more text labels
set_properties(properties)

Replace all properties with those supplied.

Parameters:properties – dictionary of new properties
update_properties(properties)[source]

Update properties with the values supplied.

Parameters:properties – dictionary of properties to integrate with existing properties
class py2neo.neo4j.Relationship(uri)[source]

A relationship within a graph, identified by a URI.

Parameters:uri – URI identifying this relationship
_id

Return the internal ID for this entity.

Returns:integer ID of this entity within the database or None if abstract
classmethod abstract(start_node, type_, end_node, **properties)[source]

Create and return a new abstract relationship.

delete()

Delete this entity from the database.

delete_properties()

Delete all properties.

end_node[source]

Return the end node of this relationship.

exists

Detects whether this entity still exists in the database.

get_cached_properties()

Fetch last known properties without calling the server.

Returns:dictionary of properties
get_properties()

Fetch all properties.

Returns:dictionary of properties
is_abstract

Indicates whether this entity is abstract (i.e. not bound to a concrete entity within the database)

set_properties(properties)

Replace all properties with those supplied.

Parameters:properties – dictionary of new properties
start_node[source]

Return the start node of this relationship.

type[source]

Return the type of this relationship as a string.

update_properties(properties)[source]

Update the properties for this relationship with the values supplied.

Table Of Contents

Previous topic

Fundamentals

Next topic

Paths

This Page