Sync API Documentation¶
Core¶
- class neomodel.sync_.core.Database¶
A singleton object via which all operations from neomodel to the Neo4j backend are handled with.
- close_connection() None ¶
Closes the currently open driver. The driver should always be closed at the end of the application’s lifecyle.
- drop_constraints(quiet: bool = True, stdout: TextIO | None = None) None ¶
Discover and drop all constraints.
- Type:
- Returns:
None
- drop_indexes(quiet: bool = True, stdout: TextIO | None = None) None ¶
Discover and drop all indexes, except the automatically created token lookup indexes.
- Type:
- Returns:
None
- 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
- install_all_labels(stdout: TextIO | None = None) 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
- install_labels(cls: Any, quiet: bool = True, stdout: TextIO | None = None) 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
- list_constraints() list[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: bool = False) list[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
- remove_all_labels(stdout: TextIO | None = None) None ¶
Calls functions for dropping constraints and indexes.
- Parameters:
stdout – output stream
- Returns:
None
- set_connection(url: str | None = None, driver: Driver | None = None) 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: TransactionProxy¶
Returns the current transaction object
- class neomodel.sync_.core.NodeBase(**kwargs: dict[str, Any])¶
- DoesNotExist¶
alias of
NodeBaseDoesNotExist
- class neomodel.sync_.core.StructuredNode(*args: Any, **kwargs: Any)¶
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: tuple, **kwargs: dict[str, Any]) list ¶
Call to CREATE with parameters map. A new instance will be created and saved.
- classmethod create_or_update(*props: tuple, **kwargs: dict[str, Any]) list ¶
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: str, params: dict[str, Any] | None = None) tuple[list | None, tuple[str, ...] | None] ¶
Execute a cypher query with the param ‘self’ pre-populated with the nodes neo4j id.
- classmethod get_or_create(*props: tuple, **kwargs: dict[str, Any]) list ¶
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: Any) Any ¶
Inflate a raw neo4j_driver node to a neomodel node :param node: :return: node object
- classmethod inherited_labels() list[str] ¶
Return list of labels from nodes class hierarchy.
- Returns:
list
- classmethod inherited_optional_labels() list[str] ¶
Return list of optional labels from nodes class hierarchy.
- Returns:
list
- Return type:
- labels() list[str] ¶
Returns list of labels tied to the node from neo4j.
- Returns:
list of labels
- Return type:
- save() StructuredNode ¶
Save the node to neo4j or raise an exception
- Returns:
the node instance
- neomodel.sync_.core.ensure_connection(func: Callable) Callable ¶
Decorator that ensures a connection is established before executing the decorated function.
- Args:
func (callable): The function to be decorated.
- Returns:
callable: The decorated function.
SemiStructuredNode
¶
- class neomodel.contrib.SemiStructuredNode(*args: Any, **kwargs: Any)¶
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
Relationships¶
- class neomodel.sync_.relationship.StructuredRel(*args: Any, **kwargs: dict)¶
Bases:
StructuredRelBase
Base class for relationship objects
- classmethod inflate(rel: Relationship) StructuredRel ¶
Inflate a neo4j_driver relationship object to a neomodel object :param rel: :return: StructuredRel
- save() StructuredRel ¶
Save the relationship
- Returns:
self
- class neomodel.sync_.relationship.StructuredRelBase(**kwargs: dict[str, Any])¶
Bases:
PropertyManager
- class neomodel.sync_.relationship_manager.RelationshipManager(source: Any, key: str, definition: dict)¶
Bases:
object
Base class for all relationships managed through neomodel.
I.e the ‘friends’ object in user.friends.all()
- all_relationships(node: StructuredNode) list[StructuredRel] ¶
Retrieve all relationship objects between self and node.
- Parameters:
node
- Returns:
[StructuredRel]
- connect(node: StructuredNode, properties: dict[str, Any] | None = None) StructuredRel | None ¶
Connect a node
- Parameters:
node
properties – for the new relationship
- Type:
- Returns:
- disconnect(node: StructuredNode) None ¶
Disconnect a node
- Parameters:
node
- Returns:
- exclude(*args: Any, **kwargs: dict) BaseSet ¶
Exclude nodes that match the provided properties.
- Parameters:
args – a Q object
kwargs – same syntax as NodeSet.filter()
- Returns:
NodeSet
- filter(*args: Any, **kwargs: dict) BaseSet ¶
Retrieve related nodes matching the provided properties.
- Parameters:
args – a Q object
kwargs – same syntax as NodeSet.filter()
- Returns:
NodeSet
- get(**kwargs: Any) NodeSet ¶
Retrieve a related node with the matching node properties.
- Parameters:
kwargs – same syntax as NodeSet.filter()
- Returns:
node
- get_or_none(**kwargs: dict) NodeSet ¶
Retrieve a related node with the matching node properties or return None.
- Parameters:
kwargs – same syntax as NodeSet.filter()
- Returns:
node
- is_connected(node: StructuredNode) bool ¶
Check if a node is connected with this relationship type :param node: :return: bool
- match(**kwargs: dict) NodeSet ¶
Return set of nodes who’s relationship properties match supplied args
- Parameters:
kwargs – same syntax as NodeSet.filter()
- Returns:
NodeSet
- order_by(*props: Any) BaseSet ¶
Order related nodes by specified properties
- Parameters:
props
- Returns:
NodeSet
- reconnect(old_node: StructuredNode, new_node: StructuredNode) None ¶
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: StructuredNode) StructuredRel | None ¶
Retrieve the relationship object for this first relationship between self and node.
- Parameters:
node
- Returns:
StructuredRel
- replace(node: StructuredNode, properties: dict[str, Any] | None = None) None ¶
Disconnect all existing nodes and connect the supplied node
- Parameters:
node
properties – for the new relationship
- Type:
- Returns:
- single() StructuredNode | None ¶
Get a single related node or none.
- Returns:
StructuredNode
- class neomodel.sync_.relationship_manager.ZeroOrMore(source: Any, key: str, definition: dict)¶
Bases:
RelationshipManager
A relationship of zero or more nodes (the default)
- class neomodel.sync_.cardinality.One(source: Any, key: str, definition: dict)¶
Bases:
RelationshipManager
A relationship to a single node
- all() list[StructuredNode] ¶
Return single node in an array
- Returns:
[node]
- connect(node: StructuredNode, properties: dict[str, Any] | None = None) StructuredRel ¶
Connect a node
- Parameters:
node
properties – relationship properties
- Returns:
True / rel instance
- disconnect(node: StructuredNode) None ¶
Disconnect a node
- Parameters:
node
- Returns:
- single() StructuredNode ¶
Return the associated node.
- Returns:
node
- class neomodel.sync_.cardinality.OneOrMore(source: Any, key: str, definition: dict)¶
Bases:
RelationshipManager
A relationship to zero or more nodes.
- all() list[StructuredNode] ¶
Returns all related nodes.
- Returns:
[node1, node2…]
- disconnect(node: StructuredNode) None ¶
Disconnect node :param node: :return:
- single() StructuredNode ¶
Fetch one of the related nodes
- Returns:
Node
- class neomodel.sync_.cardinality.ZeroOrOne(source: Any, key: str, definition: dict)¶
Bases:
RelationshipManager
A relationship to zero or one node.
- all() list[StructuredNode] ¶
Return all related nodes.
- Returns:
list
- connect(node: StructuredNode, properties: dict[str, Any] | None = None) StructuredRel ¶
Connect to a node.
- Parameters:
node
properties – relationship properties
- Type:
- Type:
- Returns:
True / rel instance
- single() StructuredNode | None ¶
Return the associated node.
- Returns:
node
Property Manager¶
- class neomodel.sync_.property_manager.PropertyManager(**kwargs: dict[str, Any])¶
Bases:
object
Common methods for handling properties on node and relationship objects.
- classmethod deflate(properties: Any, obj: Any = None, skip_empty: bool = False) dict[str, Any] ¶
Deflate the properties of a PropertyManager subclass (a user-defined StructuredNode or StructuredRel) so that it can be put into a neo4j.graph.Entity (a neo4j.graph.Node or neo4j.graph.Relationship) for storage. properties can be constructed manually, or fetched from a PropertyManager subclass using __properties__.
Includes mapping from python class attribute name -> database property name (see Property.db_property).
Ignores any properties that are not defined as python attributes in the class definition.
- classmethod inflate(graph_entity: Entity) Any ¶
Inflate the properties of a neo4j.graph.Entity (a neo4j.graph.Node or neo4j.graph.Relationship) into an instance of cls. Includes mapping from database property name (see Property.db_property) -> python class attribute name. Ignores any properties that are not defined as python attributes in the class definition.
Paths¶
- class neomodel.sync_.path.NeomodelPath(a_neopath: Path)¶
Bases:
object
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 end_node: StructuredNode¶
The last
StructuredNode
in this path.
- property start_node: StructuredNode¶
The first
StructuredNode
in this path.
Match¶
- class neomodel.sync_.match.BaseSet¶
Base class for all node sets.
Contains common python magic methods, __len__, __contains__ etc
- all(lazy: bool = False) list ¶
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
- source_class: type[StructuredNode]¶
- class neomodel.sync_.match.NodeSet(source: Any)¶
A class representing as set of nodes matching common query parameters
- annotate(*vars: tuple, **aliased_vars: tuple) NodeSet ¶
Annotate node set results with extra variables.
- exclude(*args: Any, **kwargs: Any) BaseSet ¶
Exclude nodes from the NodeSet via filters.
- Parameters:
kwargs – filter parameters see syntax for the filter method
- Returns:
self
- fetch_relations(*relation_names: tuple[str, ...]) NodeSet ¶
Specify a set of relations to traverse and return.
- filter(*args: Any, **kwargs: Any) BaseSet ¶
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: Any) Any ¶
Retrieve the first node from the set matching supplied parameters
- Parameters:
kwargs – same syntax as filter()
- Returns:
node
- first_or_none(**kwargs: Any) Any ¶
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: bool = False, **kwargs: Any) Any ¶
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: Any) Any ¶
Retrieve a node from the set matching supplied parameters or return none
- Parameters:
kwargs – same syntax as filter()
- Returns:
node or none
- intermediate_transform(vars: dict[str, Transformation], distinct: bool = False, ordering: list | None = None) NodeSet ¶
- order_by(*props: Any) BaseSet ¶
Order by properties. Prepend with minus to do descending. Pass None to remove ordering.
- resolve_subgraph() list ¶
Convert every result contained in this node set to a subgraph.
By default, we receive results from neomodel as a list of nodes without the hierarchy. This method tries to rebuild this hierarchy without overriding anything in the node, that’s why we use a dedicated property to store node’s relations.
- subquery(nodeset: NodeSet, return_set: list[str], initial_context: list[str] | None = None) NodeSet ¶
Add a subquery to this node set.
A subquery is a regular cypher query but executed within the context of a CALL statement. Such query will generally fetch additional variables which must be declared inside return_set variable in order to be included in the final RETURN statement.
- class neomodel.sync_.match.Traversal(source: Any, name: str, definition: dict)¶
Models a traversal from a node to another.
- Parameters: