neo4j Module

The neo4j module provides the main Neo4j client functionality and will be the starting point for most applications.

Connecting to a Graph

A default installation of Neo4j will use the URI below for the root of the graph database service:

neo4j.DEFAULT_URI = 'http://localhost:7474/db/data/'
class py2neo.neo4j.GraphDatabaseService(uri=None, metadata=None)[source]

Bases: py2neo.rest.Resource

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.

Parameters:
  • uri – the base URI of the database (defaults to the value of DEFAULT_URI)
  • metadata – optional resource metadata

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

from py2neo import rest, neo4j
uri = "http://localhost:7474/db/data/"
try:
    graph_db = neo4j.GraphDatabaseService(uri)
    print graph_db.neo4j_version
except rest.NoResponse:
    print "Cannot connect to host"
except rest.ResourceNotFound:
    print "Database service not found"
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, returning a list of Node and Relationship instances. 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)
)
delete(*entities)[source]

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

delete_index(type, name)[source]

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

get_index(type, 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.

See also

Index

get_indexed_node(index, key, value)[source]

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

get_indexed_relationship(index, key, value)[source]

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

get_indexes(type)[source]

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

get_node(id)[source]

Fetch a node by its ID.

get_node_count()[source]

Fetch the number of nodes in this graph as an integer.

get_or_create_index(type, 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")

See also

get_index()

See also

Index

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

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

get_or_create_relationships(*abstracts)[source]

Fetch or create relationships with the specified criteria depending on whether or not such relationships exist. Each relationship descriptor should be a tuple of (start, type, end) or (start, type, end, data) where start and end are either existing Node instances or None (both nodes cannot be None):

# set up three nodes
alice, bob, carol = graph_db.create(
    {"name": "Alice"}, {"name": "Bob"}, {"name": "Carol"}
)

# ensure Alice and Bob and related
ab, = graph_db.get_or_create_relationships(
    (alice, "LOVES", bob, {"since": 2006})
)

# ensure relationships exist between Alice, Bob and Carol
# creating new relationships only where necessary
rels = graph_db.get_or_create_relationships(
    (alice, "LOVES", bob), (bob, "LIKES", alice),
    (carol, "LOVES", bob), (alice, "HATES", carol),
)

# ensure Alice has an outgoing LIKES relationship
# (a new node will be created if required)
friendship, = graph_db.get_or_create_relationships(
    (alice, "LIKES", None)
)

# ensure Alice has an incoming LIKES relationship
# (a new node will be created if required)
friendship, = graph_db.get_or_create_relationships(
    (None, "LIKES", alice)
)

Uses Cypher CREATE UNIQUE clause, raising NotImplementedError if server support not available.

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.

get_reference_node()[source]

Fetch the reference node for the current graph.

Deprecated since version 1.3.1: use indexed nodes instead.

get_relationship(id)[source]

Fetch a relationship by its ID.

get_relationship_count()[source]

Fetch the number of relationships in this graph as an integer.

get_relationship_types()[source]

Fetch a list of relationship type names currently defined within this database instance.

neo4j_version[source]

Return the database software version as a tuple.

Authentication

py2neo.neo4j.authenticate(netloc, user_name, password)[source]

Set HTTP basic authentication values for specified netloc. The code below shows a simple example:

    # set up authentication parameters
    neo4j.authenticate("camelot:7474", "arthur", "excalibur")

    # connect to authenticated graph database
    graph_db = neo4j.GraphDatabaseService("http://camelot:7474/db/data/")

Note: a `netloc` can be either a server name or a server name and port
number but must match exactly that used within the GraphDatabaseService
URI.
Parameters:
  • netloc – the host and port requiring authentication (e.g. “camelot:7474”)
  • user_name – the user name to authenticate as
  • password – the password

Nodes and Relationships

class py2neo.neo4j.PropertyContainer(uri, reference_marker, graph_db=None, metadata=None)[source]

Bases: py2neo.rest.Resource

Base class from which Node and Relationship classes inherit. Provides property management functionality by defining standard Python container handler methods:

# 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]
delete_properties()[source]

Delete all properties for this resource.

get_properties()[source]

Fetch all properties for this resource.

set_properties(properties=None)[source]

Replace all properties for this resource with the supplied dictionary of values.

class py2neo.neo4j.Node(uri, graph_db=None, metadata=None)[source]

Bases: py2neo.neo4j.PropertyContainer

A node within a graph, identified by a URI. This class is _Indexable and, as such, may also contain URIs identifying how this relationship is represented within an index.

Parameters:
  • uri – URI identifying this node
  • graph_db – GraphDatabaseService in which this Node resides
  • metadata – index of resource metadata
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:

  • 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})
  • an existing Relationship instance

Nodes can be any of the following:

  • None, representing an unspecified node that will be created as required
  • an integer containing a node ID
  • a 3-tuple holding an index name, key and value for identifying indexed nodes, e.g. (“People”, “email”, “bob@example.com”)
  • a dict holding a set of properties for a new node
  • an existing Node instance

Note there MUST be an even number of items supplied

Parameters:items – alternating relationships and nodes
Returns:Path object representing the newly-created path
create_relationship_from(other_node, type, properties=None)[source]

Create and return a new relationship of type type from the node represented by other_node to the node represented by the current instance.

create_relationship_to(other_node, type, properties=None)[source]

Create and return a new relationship of type type from the node represented by the current instance to the node represented by other_node.

delete()[source]

Delete this node from the database.

Delete this node, plus all related nodes and relationships.

exists()[source]

Determine whether this node still exists in the database.

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)

Fetch all nodes related to the current node by a relationship in a given direction of a specific type (if supplied).

get_relationships(direction=0, *types)[source]

Fetch all relationships from the current node in a given direction of a specific type (if supplied).

get_relationships_with(other, direction=0, *types)[source]

Return all relationships between this node and another node using the relationship criteria supplied.

Return only one node related to the current node by a relationship in the given direction of the specified type, if any such relationships exist.

get_single_relationship(direction=0, *types)[source]

Fetch only one relationship from the current node in the given direction of the specified type, if any such relationships exist.

has_relationship(direction=0, *types)[source]

Return True if this node has any relationships with the specified criteria, False otherwise.

has_relationship_with(other, direction=0, *types)[source]

Return True if this node has any relationships with the specified criteria, False otherwise.

id[source]

Return the unique id for this node.

Return True if the current node is related to the other node using the relationship criteria supplied, False otherwise.

update_properties(properties=None)[source]

Update the properties for this node with the values supplied.

class py2neo.neo4j.Relationship(uri, graph_db=None, metadata=None)[source]

Bases: py2neo.neo4j.PropertyContainer

A relationship within a graph, identified by a URI. This class is _Indexable and, as such, may also contain URIs identifying how this relationship is represented within an index.

Parameters:
  • uri – URI identifying this relationship
  • metadata – index of resource metadata
delete()[source]

Delete this relationship from the database.

end_node[source]

Return the end node of this relationship.

exists()[source]

Determine whether this relationship still exists in the database.

get_other_node(node)[source]

Return a node object representing the node within this relationship which is not the one supplied.

id[source]

Return the unique id for this relationship.

is_type(type)[source]

Return True if this relationship is of the given type.

nodes[source]

Return a tuple of the two nodes attached to this relationship.

start_node[source]

Return the start node of this relationship.

type[source]

Return the type of this relationship.

update_properties(properties=None)[source]

Update the properties for this relationship with the values supplied.

Indexes

class py2neo.neo4j.Index(content_type, template_uri, graph_db=None, metadata=None)[source]

Bases: py2neo.rest.Resource

Searchable database index which can contain either nodes or relationships.

add(key, value, entity)[source]

Add an entity to this index under the key:value pair supplied:

# create a node and obtain
# a reference to the "People" node index
alice, = graph_db.create({"name": "Alice Smith"})
people = graph_db.get_or_create_index(neo4j.Node, "People")

# add the node to the index
people.add("family_name", "Smith", alice)

Note that while Neo4j indexes allow multiple entities to be added under a particular key:value, the same entity may only be represented once; this method is therefore idempotent.

add_if_none(key, value, entity)[source]

Add an entity to this index under the key:value pair supplied if no entry already exists at that point:

# obtain a reference to the "Rooms" node index and
# add node `alice` to room 100 if empty
rooms = graph_db.get_or_create_index(neo4j.Node, "Rooms")
rooms.add_if_none("room", 100, alice)

If added, this method returns the entity, otherwise None is returned.

content_type[source]

Return the type of entity contained within this index. Will return either Node or Relationship.

create(key, value, abstract)[source]

Create and index a new node or relationship using the abstract provided.

create_if_none(key, value, abstract)[source]

Create a new entity with the specified details within the current index, under the key:value pair supplied, if no such entity already exists. If creation occurs, the new entity will be returned, otherwise None will be returned:

# obtain a reference to the "Contacts" node index and
# create a node for Alice if one does not already exist
contacts = graph_db.get_or_create_index(neo4j.Node, "Contacts")
alice = contacts.create_if_none("name", "SMITH, Alice", {
    "given_name": "Alice Jane", "family_name": "Smith",
    "phone": "01234 567 890", "mobile": "07890 123 456"
})
get(key, value)[source]

Fetch a list of all entities from the index which are associated with the key:value pair supplied:

# obtain a reference to the "People" node index and
# get all nodes where `family_name` equals "Smith"
people = graph_db.get_or_create_index(neo4j.Node, "People")
smiths = people.get("family_name", "Smith")
get_or_create(key, value, abstract)[source]

Fetch a single entity from the index which is associated with the key:value pair supplied, creating a new entity with the supplied details if none exists:

# obtain a reference to the "Contacts" node index and
# ensure that Alice exists therein
contacts = graph_db.get_or_create_index(neo4j.Node, "Contacts")
alice = contacts.get_or_create("name", "SMITH, Alice", {
    "given_name": "Alice Jane", "family_name": "Smith",
    "phone": "01234 567 890", "mobile": "07890 123 456"
})

# obtain a reference to the "Friendships" relationship index and
# ensure that Alice and Bob's friendship is registered (`alice`
# and `bob` refer to existing nodes)
friendships = graph_db.get_or_create_index(neo4j.Relationship, "Friendships")
alice_and_bob = friendships.get_or_create(
    "friends", "Alice & Bob", (alice, "KNOWS", bob)
)
name[source]

Return the name of this index.

query(query)[source]

Query the index according to the supplied query criteria, returning a list of matched entities:

# obtain a reference to the "People" node index and
# get all nodes where `family_name` equals "Smith"
people = graph_db.get_or_create_index(neo4j.Node, "People")
s_people = people.query("family_name:S*")

The query syntax used should be appropriate for the configuration of the index being queried. For indexes with default configuration, this should be Apache Lucene query syntax.

remove(key=None, value=None, entity=None)[source]

Remove any entries from the index which pertain to the parameters supplied. The allowed parameter combinations are:

key, value, entity
remove a specific entity indexed under a given key-value pair
key, value
remove all entities indexed under a given key-value pair
key, entity
remove a specific entity indexed against a given key but with any value
entity
remove all occurrences of a specific entity regardless of key and value

Paths

class py2neo.neo4j.Path(node, *rels_and_nodes)[source]

Bases: py2neo.neometry.Path

Batches

class py2neo.neo4j.WriteBatch(graph_db)[source]
add_indexed_node(index, key, value, node)[source]

Add an existing node to the index specified.

add_indexed_node_or_fail(index, key, value, node)[source]

Add an existing node to the index specified if an entry does not already exist for the given key-value pair, fail otherwise.

add_indexed_relationship(index, key, value, relationship)[source]

Add an existing relationship to the index specified.

add_indexed_relationship_or_fail(index, key, value, relationship)[source]

Add an existing relationship to the index specified if an entry does not already exist for the given key-value pair, fail otherwise.

clear()

Clear all requests from this batch.

create_indexed_node_or_fail(index, key, value, properties=None)[source]

Create and index a new node if one does not already exist, fail otherwise.

create_indexed_relationship_or_fail(index, key, value, start_node, type_, end_node, properties=None)[source]

Create and index a new relationship if one does not already exist, fail otherwise.

create_node(properties=None)[source]

Create a new node with the properties supplied.

create_relationship(start_node, type_, end_node, properties=None)[source]

Create a new relationship with the values supplied.

delete_node(node)[source]

Delete the specified node from the graph.

delete_node_properties(node)[source]

Delete all properties from a node.

delete_node_property(node, key)[source]

Delete a single property from a node.

delete_relationship(relationship)[source]

Delete the specified relationship from the graph.

delete_relationship_properties(relationship)[source]

Delete all properties from a relationship.

delete_relationship_property(relationship, key)[source]

Delete a single property from a relationship.

get_or_add_indexed_node(index, key, value, node)[source]

Add an existing node to the index specified if an entry does not already exist for the given key-value pair, returning either the added node or the one already in the index.

get_or_add_indexed_relationship(index, key, value, relationship)[source]

Add an existing relationship to the index specified if an entry does not already exist for the given key-value pair, returning either the added relationship or the one already in the index.

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

Create and index a new node if one does not already exist, returning either the new node or the existing one.

get_or_create_indexed_relationship(index, key, value, start_node, type_, end_node, properties=None)[source]

Create and index a new relationship if one does not already exist, returning either the new relationship or the existing one.

get_or_create_relationship(start_node, type_, end_node, properties=None)[source]

Create a new relationship with the values supplied if one does not already exist.

remove_indexed_node(index, key=None, value=None, node=None)[source]

Remove any entries from the index which pertain to the parameters supplied. The allowed parameter combinations are:

key, value, node
remove a specific node indexed under a given key-value pair
key, node
remove a specific node indexed against a given key but with any value
node
remove all occurrences of a specific node regardless of key and value
remove_indexed_relationship(index, key=None, value=None, relationship=None)[source]

Remove any entries from the index which pertain to the parameters supplied. The allowed parameter combinations are:

key, value, relationship
remove a specific relationship indexed under a given key-value pair
key, relationship
remove a specific relationship indexed against a given key but with any value
relationship
remove all occurrences of a specific relationship regardless of key and value
set_node_properties(node, properties)[source]

Replace all properties on a node.

set_node_property(node, key, value)[source]

Set a single property on a node.

set_relationship_properties(relationship, properties)[source]

Replace all properties on a relationship.

set_relationship_property(relationship, key, value)[source]

Set a single property on a relationship.

submit()

Submit the current batch of requests, returning a list of the objects returned.

Table Of Contents

Previous topic

py2neo

Next topic

cypher Module

This Page