Object-Graph Mapping (OGM)

The ogm module provides Object to Graph Mapping features similar to ORM facilities available for relational databases. All functionality is available through the Store class which is bound to a specific neo4j.GraphDatabaseService instance on creation.

Conceptually, a mapped object “owns” a single node within the graph along with all of that node’s outgoing relationships. These features are managed via a pair of attributes called __node__ and __rel__ which store details of the mapped node and the outgoing relationships respectively. The only specific requirement for a mapped object is that it has a nullary constructor which can be used to create new instances.

The __node__ attribute holds a neo4j.Node object which is the node to which this object is mapped. If the attribute does not exist, or is None, the object is considered “unsaved”.

The __rel__ attribute holds a dictionary of outgoing relationship details. Each key corresponds to a relationship type and each value to a list of 2-tuples representing the outgoing relationships of that type. Within each 2-tuple, the first value holds a dictionary of relationship properties (which may be empty) and the second value holds the endpoint. The endpoint may be either a neo4j.Node instance or another mapped object. Any such objects which are unsaved will be lazily saved as required by creation of the relationship itself. The following data structure outline shows an example of a __rel__ attribute (where alice and bob represent other mapped objects:

{
    "LIKES": [
        ({}, alice),
        ({"since": 1999}, bob)
    ]
}

To manage relationships, use the Store.relate() and Store.separate() methods. Neither method makes any calls to the database and operates only on the local __rel__ attribute. Changes must be explicitly saved via one of the available save methods. The Store.load_related() method loads all objects marked as related by the __rel__ attribute.

The code below shows an example of usage:

from py2neo import neo4j, ogm

class Person(object):

    def __init__(self, email=None, name=None, age=None):
        self.email = email
        self.name = name
        self.age = age

    def __str__(self):
        return self.name

graph_db = neo4j.GraphDatabaseService()
store = ogm.Store(graph_db)

alice = Person("alice@example.com", "Alice", 34)
store.save_unique("People", "email", alice.email, alice)

bob = Person("bob@example.org", "Bob", 66)
carol = Person("carol@example.net", "Carol", 42)
store.relate(alice, "LIKES", bob)     # these relationships are not saved
store.relate(alice, "LIKES", carol)   # until `alice` is saved
store.save(alice)

friends = store.load_related(alice, "LIKES", Person)
print("Alice likes {0}".format(" and ".join(str(f) for f in friends)))
exception py2neo.ogm.NotSaved[source]

Bases: exceptions.ValueError

Raised when an object has not been saved but a bound node is required.

class py2neo.ogm.Store(graph_db)[source]

Bases: object

delete(subj)[source]

Delete a saved object node from the database as well as all incoming and outgoing relationships.

Parameters:subj – the object to delete from the database
Raises NotSaved:
 if subj is not linked to a database node
is_saved(subj)[source]

Return True if the object subj has been saved to the database, False otherwise.

Parameters:subj – the object to test
load(cls, node)[source]

Load and return an object of type cls from database node node.

Parameters:
  • cls – the class of the object to be returned
  • node – the node from which to load object data
Returns:

a cls instance

load_indexed(index_name, key, value, cls)[source]

Load zero or more indexed nodes from the database into a list of objects.

Parameters:
  • index_name – the node index name
  • key – the index key
  • value – the index value
  • cls – the class of the object to be returned
Returns:

a list of cls instances

Load all nodes related to subj by a relationship of type rel_type into objects of type cls.

Parameters:
  • subj – the object bound to the start of the relationship
  • rel_type – the relationship type
  • cls – the class to load all related objects into
Returns:

list of cls instances

load_unique(index_name, key, value, cls)[source]

Load a uniquely indexed node from the database into an object.

Parameters:
  • index_name – the node index name
  • key – the index key
  • value – the index value
  • cls – the class of the object to be returned
Returns:

as instance of cls containing the loaded data

relate(subj, rel_type, obj, properties=None)[source]

Define a relationship between subj and obj of type rel_type. This is a local operation only: nothing is saved to the database until a save method is called. Relationship properties may optionally be specified.

Parameters:
  • subj – the object bound to the start of the relationship
  • rel_type – the relationship type
  • obj – the object bound to the end of the relationship
  • properties – properties attached to the relationship (optional)
reload(subj)[source]

Reload properties and relationships from a database node into subj.

Parameters:subj – the object to reload
Raises NotSaved:
 if subj is not linked to a database node
save(subj, node=None)[source]

Save an object to a database node.

Parameters:
  • subj – the object to save
  • node – the database node to save to (if omitted, will re-save to same node as previous save)
save_indexed(index_name, key, value, *subj)[source]

Save one or more objects to the database, indexed under the supplied criteria.

Parameters:
  • index_name – the node index name
  • key – the index key
  • value – the index value
  • subj – one or more objects to save
save_unique(index_name, key, value, subj)[source]

Save an object to the database, uniquely indexed under the supplied criteria.

Parameters:
  • index_name – the node index name
  • key – the index key
  • value – the index value
  • subj – the object to save
separate(subj, rel_type, obj=None)[source]

Remove any relationship definitions which match the criteria specified. This is a local operation only: nothing is saved to the database until a save method is called. If no object is specified, all relationships of type rel_type are removed.

Parameters:
  • subj – the object bound to the start of the relationship
  • rel_type – the relationship type
  • obj – the object bound to the end of the relationship (optional)

Previous topic

Cypher

Next topic

Geoff

This Page