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)¶
- close_connection()¶
Closes the currently open driver. The driver should always be closed at the end of the application’s lifecyle.
- commit(*args, **kwargs)¶
- cypher_query(*args, **kwargs)¶
- property database_edition¶
- property database_version¶
- edition_is_enterprise() bool ¶
Returns true if the database edition is enterprise
- Returns:
bool: True if the database edition is enterprise
- impersonate(user: str) ImpersonationHandler ¶
All queries executed within this context manager will be executed as impersonated user
- Args:
user (str): User to impersonate
- Returns:
ImpersonationHandler: Context manager to set/unset the user to impersonate
- list_constraints() Sequence[dict] ¶
Returns all constraints existing in the database
- Returns:
Sequence[dict]: List of dictionaries, each entry being a constraint definition
- list_indexes(exclude_token_lookup=False) Sequence[dict] ¶
Returns all indexes existing in the database
- Arguments:
exclude_token_lookup[bool]: Exclude automatically create token lookup indexes
- Returns:
Sequence[dict]: List of dictionaries, each entry being an index definition
- property read_transaction¶
- rollback(*args, **kwargs)¶
- set_connection(url: str = None, driver: Driver = None)¶
Sets the connection up and relevant internal. This can be done using a Neo4j URL or a driver instance.
- Args:
url (str): Optionally, Neo4j URL in the form protocol://username:password@hostname:port/dbname. When provided, a Neo4j driver instance will be created by neomodel.
driver (neo4j.Driver): Optionally, a pre-created driver instance. When provided, neomodel will not create a driver instance but use this one instead.
- property transaction¶
Returns the current transaction object
- version_is_higher_than(version_tag: str) bool ¶
Returns true if the database version is higher or equal to a given tag
- Args:
version_tag (str): The version to compare against
- Returns:
bool: True if the database version is higher or equal to the given version
- property write_transaction¶
Core¶
- 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.
- 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
- cypher(query, params=None)¶
Execute a cypher query with the param ‘self’ pre-populated with the nodes neo4j id.
- delete()¶
Delete a node and its 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 exist, 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) – Arguments to get_or_create as tuple of dict with property names and values 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:
- 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
- classmethod inherited_optional_labels()¶
Return list of optional labels from nodes class hierarchy.
- Returns:
list
- Return type:
- labels()¶
Returns list of labels tied to the node from neo4j.
- Returns:
list of labels
- Return type:
- 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:
- Returns:
None
- neomodel.core.drop_indexes(quiet=True, stdout=None)¶
Discover and drop all indexes, except the automatically created token lookup indexes.
- Type:
- 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 must 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:
- Returns:
None
- neomodel.core.remove_all_labels(stdout=None)¶
Calls functions for dropping constraints and indexes.
- Parameters:
stdout – output stream
- Returns:
None
SemiStructuredNode
¶
- class neomodel.contrib.SemiStructuredNode(*args, **kwargs)¶
A base class allowing properties to be stored on a node that aren’t specified in its definition. Conflicting properties are signaled with the
DeflateConflict
exception:class Person(SemiStructuredNode): name = StringProperty() age = IntegerProperty() def hello(self): print("Hi my names " + self.name) tim = Person(name='Tim', age=8, weight=11).save() tim.hello = "Hi" tim.save() # DeflateConflict
Properties¶
- class neomodel.properties.AliasProperty(to=None)¶
-
Alias another existing property
- class neomodel.properties.ArrayProperty(base_property=None, **kwargs)¶
Bases:
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:
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:
Property
Stores a date
- class neomodel.properties.DateTimeFormatProperty(default_now=False, format='%Y-%m-%d', **kwargs)¶
Bases:
Property
Store a datetime by custome format :param default_now: If
True
, the creation time (Local) will be used as default.Defaults to
False
.- Parameters:
format (
str
) – Date format string, default is %Y-%m-%d
- class neomodel.properties.DateTimeProperty(default_now=False, **kwargs)¶
Bases:
Property
A property representing a
datetime.datetime
object as unix epoch.- Parameters:
default_now (
bool
) – IfTrue
, the creation time (UTC) will be used as default. Defaults toFalse
.
- class neomodel.properties.EmailProperty(expression=None, **kwargs)¶
Bases:
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:
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:
Property
Stores an Integer value
- default_value()¶
Generate a default value
- Returns:
the value
- class neomodel.properties.JSONProperty(*args, **kwargs)¶
Bases:
Property
Store a data structure as a JSON string.
The structure will be inflated when a node is retrieved.
- class neomodel.properties.NormalizedProperty(unique_index=False, index=False, required=False, default=None, db_property=None, label=None, help_text=None, **kwargs)¶
Bases:
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 toFalse
.index (
bool
) – Creates an index for this property. Defaults toFalse
.required (
bool
) – Marks the property as required. Defaults toFalse
.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 bydjango_neomodel
.help_text (
str
) – Optional, used bydjango_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:
NormalizedProperty
Validates a property against a regular expression.
If sub-classing set:
expression = r’[^@]+@[^@]+.[^@]+’
- class neomodel.properties.StringProperty(choices=None, max_length=None, **kwargs)¶
Bases:
NormalizedProperty
Stores a unicode string
- Parameters:
- default_value()¶
Generate a default value
- Returns:
the value
- class neomodel.properties.UniqueIdProperty(**kwargs)¶
Bases:
Property
A unique identifier, a randomly generated uid (uuid4) with a unique index
Spatial Properties & Datatypes¶
Relationships¶
- class neomodel.relationship.StructuredRel(*args, **kwargs)¶
Bases:
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
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(node)¶
Retrieve all relationship objects between self and node.
- Parameters:
node –
- Returns:
[StructuredRel]
- connect(node, properties=None)¶
Connect a node
- Parameters:
node –
properties – for the new relationship
- Type:
- Returns:
- disconnect(node)¶
Disconnect a node
- Parameters:
node –
- Returns:
- disconnect_all()¶
Disconnect all nodes
- Returns:
- exclude(*args, **kwargs)¶
Exclude nodes that match the provided properties.
- Parameters:
args – a Q object
kwargs – same syntax as NodeSet.filter()
- Returns:
NodeSet
- filter(*args, **kwargs)¶
Retrieve related nodes matching the provided properties.
- Parameters:
args – a Q object
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(old_node, new_node)¶
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(node)¶
Retrieve the relationship object for this first relationship between self and node.
- Parameters:
node –
- Returns:
StructuredRel
- replace(node, properties=None)¶
Disconnect all existing nodes and connect the supplied node
- Parameters:
node –
properties – for the new relationship
- Type:
- Returns:
- single()¶
Get a single related node or none.
- Returns:
StructuredNode
- class neomodel.relationship_manager.ZeroOrMore(source, key, definition)¶
Bases:
RelationshipManager
A relationship of zero or more nodes (the default)
- class neomodel.cardinality.One(source, key, definition)¶
Bases:
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:
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:
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:
- Type:
- Returns:
True / rel instance
- single()¶
Return the associated node.
- Returns:
node
Paths¶
- class neomodel.path.NeomodelPath(a_neopath)¶
Bases:
Path
Represents paths within neomodel.
This object is instantiated when you include whole paths in your
cypher_query()
result sets and turnresolve_objects
to True.That is, any query of the form:
MATCH p=(:SOME_NODE_LABELS)-[:SOME_REL_LABELS]-(:SOME_OTHER_NODE_LABELS) return p
NeomodelPath
are simple objects that reference their nodes and relationships, each of which is already resolved to their neomodel objects if such mapping is possible.- Parameters:
nodes (List[StructuredNode]) – Neomodel nodes appearing in the path in order of appearance.
relationships (List[StructuredRel]) – Neomodel relationships appearing in the path in order of appearance.
- property nodes¶
The sequence of
Node
objects in this path.
- property relationships¶
The sequence of
Relationship
objects in this path.
Match¶
- class neomodel.match.BaseSet¶
Base class for all node sets.
Contains common python magic methods, __len__, __contains__ etc
- all(lazy=False)¶
Return all nodes belonging to the set :param lazy: False by default, specify True to get nodes with id only without the parameters. :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
- fetch_relations(*relation_names)¶
Specify a set of relations to return.
- filter(*args, **kwargs)¶
Apply filters to the existing nodes in the set.
- Parameters:
args –
a Q object
e.g .filter(Q(salary__lt=10000) | Q(salary__gt=20000)).
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(lazy=False, **kwargs)¶
Retrieve one node from the set matching supplied parameters :param lazy: False by default, specify True to get nodes with id only without the parameters. :param kwargs: same syntax as filter() :return: 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, aNodeSet
instance or aTraversal
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:
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:
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:
ValueError
,NeomodelException
- exception neomodel.exceptions.DeflateConflict(cls, key, value, nid)¶
Bases:
InflateConflict
- exception neomodel.exceptions.DeflateError(key, cls, msg, obj)¶
Bases:
ValueError
,NeomodelException
- exception neomodel.exceptions.DoesNotExist(msg)¶
Bases:
NeomodelException
- exception neomodel.exceptions.FeatureNotSupported(msg)¶
Bases:
NeomodelException
- exception neomodel.exceptions.InflateConflict(cls, key, value, nid)¶
Bases:
NeomodelException
- exception neomodel.exceptions.InflateError(key, cls, msg, obj=None)¶
Bases:
ValueError
,NeomodelException
- exception neomodel.exceptions.MultipleNodesReturned(msg)¶
Bases:
ValueError
,NeomodelException
- exception neomodel.exceptions.NeomodelException¶
Bases:
Exception
A base class that identifies all exceptions raised by
neomodel
.
- exception neomodel.exceptions.NodeClassAlreadyDefined(db_node_rel_class, current_node_class_registry)¶
Bases:
ModelDefinitionException
Raised when an attempt is made to re-map a set of labels to a class that already has a mapping within the node-to-class registry.
- exception neomodel.exceptions.NodeClassNotDefined(db_node_rel_class, current_node_class_registry)¶
Bases:
ModelDefinitionException
Raised when it is impossible to resolve a Neo4j driver Node to a data model object. This can happen as a result of a query returning nodes for which class definitions do exist but have not been imported or because the retrieved nodes contain more labels for a known class.
In either of these cases the mismatch must be reported
- exception neomodel.exceptions.NotConnected(action, node1, node2)¶
Bases:
NeomodelException
- exception neomodel.exceptions.RelationshipClassNotDefined(db_node_rel_class, current_node_class_registry)¶
Bases:
ModelDefinitionException
Raised when it is impossible to resolve a Neo4j driver Relationship to a data model object.
- exception neomodel.exceptions.RelationshipClassRedefined(db_rel_class_type, current_node_class_registry, remapping_to_class)¶
Bases:
ModelDefinitionException
Raised when an attempt is made to re-map a relationship label to a relationship model of an entirely different type
- exception neomodel.exceptions.RequiredProperty(key, cls)¶
Bases:
NeomodelException
- exception neomodel.exceptions.UniqueProperty(msg)¶
Bases:
ConstraintValidationFailed
Scripts¶
neomodel_install_labels
¶
usage: neomodel_install_labels [-h] [--db bolt://neo4j:neo4j@localhost:7687] <someapp.models/app.py> [<someapp.models/app.py> ...]
Setup indexes and constraints on labels in Neo4j for your neomodel schema.
If a connection URL is not specified, the tool will look up the environment
variable NEO4J_BOLT_URL. If that environment variable is not set, the tool
will attempt to connect to the default URL bolt://neo4j:neo4j@localhost:7687
positional arguments:
<someapp.models/app.py>
python modules or files with neomodel schema declarations.
options:
-h, --help show this help message and exit
--db bolt://neo4j:neo4j@localhost:7687
Neo4j Server URL
- neomodel.scripts.neomodel_install_labels.load_python_module_or_file(name)¶
Imports an existing python module or file into the current workspace.
In both cases, the resource must exist.
- Parameters:
name (str) – A string that refers either to a Python module or a source coe file to load in the current workspace.
- neomodel.scripts.neomodel_install_labels.main()¶
neomodel_remove_labels
¶
usage: neomodel_remove_labels [-h] [--db bolt://neo4j:neo4j@localhost:7687]
Drop all indexes and constraints on labels from schema in Neo4j database.
If a connection URL is not specified, the tool will look up the environment
variable NEO4J_BOLT_URL. If that environment variable is not set, the tool
will attempt to connect to the default URL bolt://neo4j:neo4j@localhost:7687
options:
-h, --help show this help message and exit
--db bolt://neo4j:neo4j@localhost:7687
Neo4j Server URL
- neomodel.scripts.neomodel_remove_labels.main()¶