Modules documentation

Database

class neomodel.util.Database

A singleton object via which all operations from neomodel to the Neo4j backend are handled with.

begin(*args, **kwargs)
commit(*args, **kwargs)
cypher_query(*args, **kwargs)
read_transaction
rollback(*args, **kwargs)
set_connection(url)

Sets the connection URL to the address a Neo4j server is set up at

transaction

Returns the current transaction object

write_transaction

Core

class neomodel.core.NodeBase(**kwargs)
DoesNotExist

alias of NodeBaseDoesNotExist

class neomodel.core.StructuredNode(*args, **kwargs)

Base class for all node definitions to inherit from.

If you want to create your own abstract classes set:
__abstract_node__ = True
DoesNotExist

alias of StructuredNodeDoesNotExist

classmethod create(*props, **kwargs)

Call to CREATE with parameters map. A new instance will be created and saved.

Parameters:
  • props (tuple) – dict of properties to create the nodes.
  • lazy – False by default, specify True to get nodes with id only without the parameters.
Type:

bool

Return type:

list

classmethod create_or_update(*props, **kwargs)

Call to MERGE with parameters map. A new instance will be created and saved if does not already exists, this is an atomic operation. If an instance already exists all optional properties specified will be updated.

Note that the post_create hook isn’t called after create_or_update

Parameters:
  • props (tuple) – List of dict arguments to get or create the entities with.
  • relationship – Optional, relationship to get/create on when new entity is created.
  • lazy – False by default, specify True to get nodes with id only without the parameters.
Return type:

list

cypher(query, params=None)

Execute a cypher query with the param ‘self’ pre-populated with the nodes neo4j id.

Parameters:
  • query – cypher query string
  • params – query parameters
Type:

string

Type:

dict

Returns:

list containing query results

Return type:

list

delete()

Delete a node and it’s relationships

Returns:True
classmethod get_or_create(*props, **kwargs)

Call to MERGE with parameters map. A new instance will be created and saved if does not already exists, this is an atomic operation. Parameters must contain all required properties, any non required properties with defaults will be generated.

Note that the post_create hook isn’t called after get_or_create

Parameters:
  • props (tuple) – dict of properties to get or create the entities with.
  • relationship – Optional, relationship to get/create on when new entity is created.
  • lazy – False by default, specify True to get nodes with id only without the parameters.
Return type:

list

classmethod inflate(node)

Inflate a raw neo4j_driver node to a neomodel node :param node: :return: node object

classmethod inherited_labels()

Return list of labels from nodes class hierarchy.

Returns:list
labels()

Returns list of labels tied to the node from neo4j.

Returns:list of labels
Return type:list
refresh()

Reload the node from neo4j

save()

Save the node to neo4j or raise an exception

Returns:the node instance
neomodel.core.drop_constraints(quiet=True, stdout=None)

Discover and drop all constraints.

Type:bool
Returns:None
neomodel.core.drop_indexes(quiet=True, stdout=None)

Discover and drop all indexes.

Type:bool
Returns:None
neomodel.core.install_all_labels(stdout=None)

Discover all subclasses of StructuredNode in your application and execute install_labels on each. Note: code most be loaded (imported) in order for a class to be discovered.

Parameters:stdout – output stream
Returns:None
neomodel.core.install_labels(cls, quiet=True, stdout=None)

Setup labels with indexes and constraints for a given class

Parameters:
  • cls – StructuredNode class
  • quiet – (default true) enable standard output
  • stdout – stdout stream
Type:

class

Type:

bool

Returns:

None

neomodel.core.remove_all_labels(stdout=None)

Calls functions for dropping constraints and indexes.

Parameters:stdout – output stream
Returns:None

Properties

class neomodel.properties.AliasProperty(to=None)

Bases: property, neomodel.properties.Property

Alias another existing property

class neomodel.properties.ArrayProperty(base_property=None, **kwargs)

Bases: neomodel.properties.Property

Stores a list of items

default_value()

Generate a default value

Returns:the value
class neomodel.properties.BooleanProperty(unique_index=False, index=False, required=False, default=None, db_property=None, label=None, help_text=None, **kwargs)

Bases: neomodel.properties.Property

Stores a boolean value

default_value()

Generate a default value

Returns:the value
class neomodel.properties.DateProperty(unique_index=False, index=False, required=False, default=None, db_property=None, label=None, help_text=None, **kwargs)

Bases: neomodel.properties.Property

Stores a date

class neomodel.properties.DateTimeProperty(default_now=False, **kwargs)

Bases: neomodel.properties.Property

A property representing a datetime.datetime object as unix epoch.

Parameters:default_now (bool) – If True, the creation time (UTC) will be used as default. Defaults to False.
class neomodel.properties.EmailProperty(expression=None, **kwargs)

Bases: neomodel.properties.RegexProperty

Store email addresses

class neomodel.properties.FloatProperty(unique_index=False, index=False, required=False, default=None, db_property=None, label=None, help_text=None, **kwargs)

Bases: neomodel.properties.Property

Store a floating point value

default_value()

Generate a default value

Returns:the value
class neomodel.properties.IntegerProperty(unique_index=False, index=False, required=False, default=None, db_property=None, label=None, help_text=None, **kwargs)

Bases: neomodel.properties.Property

Stores an Integer value

default_value()

Generate a default value

Returns:the value
class neomodel.properties.JSONProperty(*args, **kwargs)

Bases: neomodel.properties.Property

Store a data structure as a JSON string.

The structure will be inflated when a node is retrieved.

class neomodel.properties.NormalProperty(*args, **kwargs)

Bases: neomodel.properties.NormalizedProperty

class neomodel.properties.NormalizedProperty(unique_index=False, index=False, required=False, default=None, db_property=None, label=None, help_text=None, **kwargs)

Bases: neomodel.properties.Property

Base class for normalized properties. These use the same normalization method to in- or deflating.

default_value()

Generate a default value

Returns:the value
class neomodel.properties.Property(unique_index=False, index=False, required=False, default=None, db_property=None, label=None, help_text=None, **kwargs)

Bases: object

Base class for object properties.

Parameters:
  • unique_index (bool) – Creates a unique index for this property. Defaults to False.
  • index (bool) – Creates an index for this property. Defaults to False.
  • required (bool) – Marks the property as required. Defaults to False.
  • default – A default value or callable that returns one to set when a node is initialized without specifying this property.
  • db_property (str) – A name that this property maps to in the database. Defaults to the model’s property name.
  • label (str) – Optional, used by django_neomodel.
  • help_text (str) – Optional, used by django_neomodel.
default_value()

Generate a default value

Returns:the value
class neomodel.properties.PropertyManager(**kwargs)

Bases: object

Common methods for handling properties on node and relationship objects.

class neomodel.properties.RegexProperty(expression=None, **kwargs)

Bases: neomodel.properties.NormalizedProperty

Validates a property against a regular expression.

If sub-classing set:

expression = r’[^@]+@[^@]+.[^@]+’
class neomodel.properties.StringProperty(choices=None, **kwargs)

Bases: neomodel.properties.NormalizedProperty

Stores a unicode string

Parameters:choices (Any type that can be used to initiate a dict.) – A mapping of valid strings to label strings that are used to display information in an application. If the default value None is used, any string is valid.
default_value()

Generate a default value

Returns:the value
class neomodel.properties.UniqueIdProperty(**kwargs)

Bases: neomodel.properties.Property

A unique identifier, a randomly generated uid (uuid4) with a unique index

Relationships

class neomodel.relationship.StructuredRel(*args, **kwargs)

Bases: neomodel.relationship.RelationshipBase

Base class for relationship objects

end_node()

Get end node

Returns:StructuredNode
classmethod inflate(rel)

Inflate a neo4j_driver relationship object to a neomodel object :param rel: :return: StructuredRel

save()

Save the relationship

Returns:self
start_node()

Get start node

Returns:StructuredNode
neomodel.relationship.StructuredRelBase

alias of neomodel.relationship.RelationshipBase

class neomodel.relationship_manager.RelationshipManager(source, key, definition)

Bases: object

Base class for all relationships managed through neomodel.

I.e the ‘friends’ object in user.friends.all()

all()

Return all related nodes.

Returns:list
all_relationships(*args, **kwargs)

Retrieve all relationship objects between self and node.

Parameters:node
Returns:[StructuredRel]
connect(*args, **kwargs)

Connect a node

Parameters:
  • node
  • properties – for the new relationship
Type:

dict

Returns:

disconnect(*args, **kwargs)

Disconnect a node

Parameters:node
Returns:
disconnect_all(*args, **kwargs)

Disconnect all nodes

Returns:
exclude(**kwargs)

Exclude nodes that match the provided properties.

Parameters:kwargs – same syntax as NodeSet.filter()
Returns:NodeSet
filter(**kwargs)

Retrieve related nodes matching the provided properties.

Parameters:kwargs – same syntax as NodeSet.filter()
Returns:NodeSet
get(**kwargs)

Retrieve a related node with the matching node properties.

Parameters:kwargs – same syntax as NodeSet.filter()
Returns:node
get_or_none(**kwargs)

Retrieve a related node with the matching node properties or return None.

Parameters:kwargs – same syntax as NodeSet.filter()
Returns:node
is_connected(node)

Check if a node is connected with this relationship type :param node: :return: bool

match(**kwargs)

Return set of nodes who’s relationship properties match supplied args

Parameters:kwargs – same syntax as NodeSet.filter()
Returns:NodeSet
order_by(*props)

Order related nodes by specified properties

Parameters:props
Returns:NodeSet
reconnect(*args, **kwargs)

Disconnect old_node and connect new_node copying over any properties on the original relationship.

Useful for preventing cardinality violations

Parameters:
  • old_node
  • new_node
Returns:

None

relationship(*args, **kwargs)

Retrieve the relationship object for this first relationship between self and node.

Parameters:node
Returns:StructuredRel
replace(*args, **kwargs)

Disconnect all existing nodes and connect the supplied node

Parameters:
  • node
  • properties – for the new relationship
Type:

dict

Returns:

search(**kwargs)

Retrieve related nodes matching the provided properties.

Parameters:kwargs – same syntax as NodeSet.filter()
Returns:NodeSet
single()

Get a single related node or none.

Returns:StructuredNode
class neomodel.relationship_manager.ZeroOrMore(source, key, definition)

Bases: neomodel.relationship_manager.RelationshipManager

A relationship of zero or more nodes (the default)

class neomodel.cardinality.One(source, key, definition)

Bases: neomodel.relationship_manager.RelationshipManager

A relationship to a single node

all()

Return single node in an array

Returns:[node]
connect(node, properties=None)

Connect a node

Parameters:
  • node
  • properties – relationship properties
Returns:

True / rel instance

disconnect(node)

Disconnect a node

Parameters:node
Returns:
disconnect_all()

Disconnect all nodes

Returns:
single()

Return the associated node.

Returns:node
class neomodel.cardinality.OneOrMore(source, key, definition)

Bases: neomodel.relationship_manager.RelationshipManager

A relationship to zero or more nodes.

all()

Returns all related nodes.

Returns:[node1, node2…]
disconnect(node)

Disconnect node :param node: :return:

single()

Fetch one of the related nodes

Returns:Node
class neomodel.cardinality.ZeroOrOne(source, key, definition)

Bases: neomodel.relationship_manager.RelationshipManager

A relationship to zero or one node.

all()

Return all related nodes.

Returns:list
connect(node, properties=None)

Connect to a node.

Parameters:
  • node
  • properties – relationship properties
Type:

StructuredNode

Type:

dict

Returns:

True / rel instance

single()

Return the associated node.

Returns:node

Match

class neomodel.match.BaseSet

Base class for all node sets.

Contains common python magic methods, __len__, __contains__ etc

all()

Return all nodes belonging to the set :return: list of nodes :rtype: list

query_cls

alias of QueryBuilder

class neomodel.match.NodeSet(source)

A class representing as set of nodes matching common query parameters

exclude(*args, **kwargs)

Exclude nodes from the NodeSet via filters.

Parameters:kwargs – filter parameters see syntax for the filter method
Returns:self
filter(*args, **kwargs)

Apply filters to the existing nodes in the set.

Parameters:kwargs

filter parameters

Filters mimic Django’s syntax with the double ‘__’ to separate field and operators.

e.g .filter(salary__gt=20000) results in salary > 20000.

The following operators are available:

  • ’lt’: less than
  • ’gt’: greater than
  • ’lte’: less than or equal to
  • ’gte’: greater than or equal to
  • ’ne’: not equal to
  • ’in’: matches one of list (or tuple)
  • ’isnull’: is null
  • ’regex’: matches supplied regex (neo4j regex format)
  • ’exact’: exactly match string (just ‘=’)
  • ’iexact’: case insensitive match string
  • ’contains’: contains string
  • ’icontains’: case insensitive contains
  • ’startswith’: string starts with
  • ’istartswith’: case insensitive string starts with
  • ’endswith’: string ends with
  • ’iendswith’: case insensitive string ends with
Returns:self
first(**kwargs)

Retrieve the first node from the set matching supplied parameters

Parameters:kwargs – same syntax as filter()
Returns:node
first_or_none(**kwargs)

Retrieve the first node from the set matching supplied parameters or return none

Parameters:kwargs – same syntax as filter()
Returns:node or none
get(**kwargs)

Retrieve one node from the set matching supplied parameters

Parameters:kwargs – same syntax as filter()
Returns:node
get_or_none(**kwargs)

Retrieve a node from the set matching supplied parameters or return none

Parameters:kwargs – same syntax as filter()
Returns:node or none
has(**kwargs)
order_by(*props)

Order by properties. Prepend with minus to do descending. Pass None to remove ordering.

class neomodel.match.Traversal(source, name, definition)

Models a traversal from a node to another.

Parameters:
  • source (A StructuredNode subclass, an instance of such, a NodeSet instance or a Traversal instance.) – Starting of the traversal.
  • name (str) – A name for the traversal.
  • definition – A relationship definition that most certainly deserves a documentation here.
match(**kwargs)

Traverse relationships with properties matching the given parameters.

e.g: .match(price__lt=10)
Parameters:kwargs – see NodeSet.filter() for syntax
Returns:self

Exceptions

exception neomodel.exceptions.AttemptedCardinalityViolation

Bases: neomodel.exceptions.NeomodelException

Attempted to alter the database state against the cardinality definitions.

Example: a relationship of type One trying to connect a second node.

exception neomodel.exceptions.CardinalityViolation(rel_manager, actual)

Bases: neomodel.exceptions.NeomodelException

The state of database doesn’t match the nodes cardinality definition.

For example a relationship type OneOrMore returns no nodes.

exception neomodel.exceptions.ConstraintValidationFailed(msg)

Bases: exceptions.ValueError, neomodel.exceptions.NeomodelException

exception neomodel.exceptions.DeflateConflict(cls, key, value, nid)

Bases: neomodel.exceptions.InflateConflict

exception neomodel.exceptions.DeflateError(key, cls, msg, obj)

Bases: exceptions.ValueError, neomodel.exceptions.NeomodelException

exception neomodel.exceptions.DoesNotExist(msg)

Bases: neomodel.exceptions.NeomodelException

exception neomodel.exceptions.InflateConflict(cls, key, value, nid)

Bases: neomodel.exceptions.NeomodelException

exception neomodel.exceptions.InflateError(key, cls, msg, obj=None)

Bases: exceptions.ValueError, neomodel.exceptions.NeomodelException

exception neomodel.exceptions.MultipleNodesReturned(msg)

Bases: exceptions.ValueError, neomodel.exceptions.NeomodelException

exception neomodel.exceptions.NeomodelException

Bases: exceptions.Exception

A base class that identifies all exceptions raised by neomodel.

exception neomodel.exceptions.NotConnected(action, node1, node2)

Bases: neomodel.exceptions.NeomodelException

exception neomodel.exceptions.RequiredProperty(key, cls)

Bases: neomodel.exceptions.NeomodelException

exception neomodel.exceptions.UniqueProperty(msg)

Bases: neomodel.exceptions.ConstraintValidationFailed