py2neo.ogm – Object-Graph Mapping

The py2neo.ogm package contains a set of facilities for binding Python objects to an underlying set of graph data. Class definitions extend Model and include Property and Label definitions as well as details of Related objects.

A simple example, based on the movie graph data set:

class Movie(Model):
    __primarykey__ = "title"

    title = Property()
    tag_line = Property("tagline")
    released = Property()

    actors = RelatedFrom("Person", "ACTED_IN")
    directors = RelatedFrom("Person", "DIRECTED")
    producers = RelatedFrom("Person", "PRODUCED")


class Person(Model):
    __primarykey__ = "name"

    name = Property()
    born = Property()

    acted_in = RelatedTo(Movie)
    directed = RelatedTo(Movie)
    produced = RelatedTo(Movie)

Repositories

class py2neo.ogm.Repository(profile=None, name=None, **settings)[source]

Storage container for Model instances.

The constructor for this class has an identical signature to that for the Graph class. For example:

>>> from py2neo.ogm import Repository
>>> from py2neo.ogm.models.movies import Movie
>>> repo = Repository("bolt://neo4j@localhost:7687", password="password")
>>> repo.match(Movie, "The Matrix").first()
<Movie title='The Matrix'>

New in version 2020.0. In earlier versions, a :class:`.Graph` was required to co-ordinate all reads and writes to the remote database. This class completely replaces that, removing the need to import from any other packages when using OGM.

delete(obj)[source]

Delete the object in the remote graph.

exists(obj)[source]

Check whether the object exists in the remote graph.

get(model, primary_value=None)[source]

Match and return a single object from the remote graph.

Parameters:
  • model – the Model subclass to match

  • primary_value – value of the primary property (optional)

Return type:

Model

match(model, primary_value=None)[source]

Select one or more objects from the remote graph.

Parameters:
  • model – the Model subclass to match

  • primary_value – value of the primary property (optional)

Return type:

ModelMatch

reload(obj)[source]

Reload data from the remote graph into the local object.

save(*objects)[source]

Save data from the local object into the remote graph.

Each object in objects can be a Model object or an iterable of such objects.

Parameters:

objectsModel objects to save.

classmethod wrap(graph)[source]

Wrap an existing Graph object as a Repository.

Models

At the heart of the py2neo OGM framework is the Model. This is a base class for all classes that are to be mapped onto the graph database. Each Model wraps a node as well as a set of pointers to RelatedObjects and the relationship details that connect them.

A Model instance may be constructed just like any other Python object but can also be matched from the database. Each instance may contain attributes that represent labels, nodes or related objects.

class py2neo.ogm.Model(*values, **properties)[source]

Base class for all OGM object classes.

This class provides a default constructor, allowing initial property values to be provided. Positional arguments are mapped, in order, to primary key fields; keywords arguments are mapped directly by name.

Changed in 2020.0: this used to be called GraphObject, but was renamed to avoid ambiguity. The old name is still available as an alias.

Changed in 2021.2: added default constructor.

__primarylabel__

The primary node label used for Cypher MATCH and MERGE operations. By default the name of the class is used.

This value can also be a tuple, in which case a composite primary label is implied.

__primarykey__

The primary property key used for Cypher MATCH and MERGE operations. If undefined, the special value of "__id__" is used to hinge uniqueness on the internal node ID instead of a property. Note that this alters the behaviour of operations such as Graph.create() and Graph.merge() on Model instances.

This value can also be a tuple, in which case a composite primary key is implied.

__primaryvalue__

The value of the property identified by __primarykey__. If the key is "__id__" then this value returns the internal node ID. If the primary key is a tuple, then a corresponding tuple of property values is returned.

__node__

The Node wrapped by this Model.

classmethod wrap(node)[source]

Convert a Node into a Model.

Parameters:

node

Returns:

classmethod match(repository, primary_value=None)[source]

Select one or more nodes from the database, wrapped as instances of this class.

Parameters:
  • repository – the Repository in which to match

  • primary_value – value of the primary property (optional)

Return type:

ModelMatch

Properties

A Property defined on a Model provides an accessor to a property of the underlying node.

class py2neo.ogm.Property(key=None, default=None)[source]

Property definition for a Model.

key

The name of the node property within the database.

default

The default value for the property, if it would otherwise be None.

>>> class Person(Model):
...     name = Property()
...
>>> alice = Person()
>>> alice.name = "Alice Smith"
>>> alice.name
"Alice Smith"

Labels

A Label defined on a Model provides an accessor to a label of the underlying central node. It is exposed as a boolean value, the setting of which allows the label to be toggled on or off.

Labels are exposed in the API in an identical way to boolean properties. The difference between these is in how the value translates into the graph database. A label should generally be used if matches are regularly carried out on that value. Secondary or supporting information could be stored in a boolean property.

class py2neo.ogm.Label(name=None)[source]

Label definition for a Model.

Labels are toggleable tags applied to an object that can be used as type information or other forms of classification.

>>> class Food(Model):
...     hot = Label()
...
>>> pizza = Food()
>>> pizza.hot
False
>>> pizza.hot = True
>>> pizza.hot
True

Object Matching

One or more Model instances can be selected from the database by using the match method of the relevant subclass.

To select a single instance using the primary label and primary key:

>>> Person.match(graph, "Keanu Reeves").first()
<Person name='Keanu Reeves'>

To select all instances that match certain criteria, you can simply iterate through the Match object. Note the use of the underscore in the Cypher WHERE clause to refer to the underlying node:

>>> list(Person.match(graph).where("_.name =~ 'K.*'"))
[<Person name='Keanu Reeves'>,
 <Person name='Kevin Bacon'>,
 <Person name='Kiefer Sutherland'>,
 <Person name='Kevin Pollak'>,
 <Person name='Kelly McGillis'>,
 <Person name='Kelly Preston'>]
class py2neo.ogm.ModelMatch(graph, labels=frozenset({}), predicates=(), order_by=(), skip=None, limit=None)[source]

A selection of Model instances that match a given set of criteria.

__iter__()[source]

Iterate through items drawn from the underlying repository that match the given criteria.

first()[source]

Return the first item that matches the given criteria.