Sync API Documentation

Core

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(**kwargs: dict[str, Any])

Bases: StructuredRelBase

Base class for relationship objects

end_node() → Any

Get end node

Returns:

StructuredNode

classmethod inflate(graph_entity: Relationship) → StructuredRel

Inflate a neo4j_driver relationship object to a neomodel object :param graph_entity: Relationship :return: StructuredRel

save() → StructuredRel

Save the relationship

Returns:

self

start_node() → Any

Get start node

Returns:

StructuredNode

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() → list

Return all related nodes.

Returns:

list

all_relationships(node: StructuredNode) → list[StructuredRel]

Retrieve all relationship objects between self and node.

Parameters:

node

Returns:

[StructuredRel]

check_cardinality(node: StructuredNode) → None

Check whether a new connection to a node would violate the cardinality of the relationship.

Parameters:

node – The node that is being connected.

Type:

StructuredNode

Raises:

AttemptedCardinalityViolation

check_mutual_exclusion() → None

Check whether connecting this relationship would violate a mutual exclusion group. Relationships sharing the same exclusion_group on the source node are mutually exclusive: at most one of them may hold any connection at a time (this is orthogonal to each relationship’s own cardinality).

Raises:

MutualExclusionViolation

connect(node: StructuredNode, properties: dict[str, Any] | None = None) → StructuredRel | None

Connect a node

Parameters:
  • node

  • properties – for the new relationship

Type:

dict

Returns:

disconnect(node: StructuredNode) → None

Disconnect a node

Parameters:

node

Returns:

disconnect_all() → None

Disconnect all nodes

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)

Retrieve a related node with the matching node properties.

Parameters:

kwargs – same syntax as NodeSet.filter()

Returns:

node

get_or_none(**kwargs: dict)

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: Any) → NodeSet

Return set of nodes whose 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:

dict

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)

neomodel.sync_.relationship_manager.deflate_relationship_properties(relationship: RelationshipManager, rel_props: dict[str, Any], query_params: dict[str, Any]) → dict[str, str]

Deflate relationship properties and prepare them for Cypher query.

Parameters:
  • relationship – The relationship manager containing the model

  • rel_props – Dictionary of relationship properties to deflate

  • query_params – Query parameters dict to add deflated values to

Returns:

Dictionary mapping property names to parameter placeholders (e.g. {‘since’: ‘$since’})

neomodel.sync_.relationship_manager.validate_relationship(relationship: Any, rel_props: Any) → None

Validate relationship manager.

Parameters:

relationship – The relationship manager to validate

Raises:
  • TypeError – If relationship is not an RelationshipManager

  • ValueError – If relationship source is invalid or relation_type is missing

  • RuntimeError – If relationship source element_id is None

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]

check_cardinality(node: StructuredNode) → None

Check whether a new connection to a node would violate the cardinality of the relationship.

Parameters:

node – The node that is being connected.

Type:

StructuredNode

Raises:

AttemptedCardinalityViolation

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:

disconnect_all() → None

Disconnect all nodes

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:

disconnect_all() → None

Disconnect all nodes

Returns:

single() → StructuredNode

Fetch one of the related nodes

Returns:

Node

class neomodel.sync_.cardinality.ZeroOrMore(source: Any, key: str, definition: dict)

Bases: RelationshipManager

A relationship of zero or more nodes (the default)

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

check_cardinality(node: StructuredNode) → None

Check whether a new connection to a node would violate the cardinality of the relationship.

Parameters:

node – The node that is being connected.

Type:

StructuredNode

Raises:

AttemptedCardinalityViolation

connect(node: StructuredNode, properties: dict[str, Any] | None = None) → StructuredRel

Connect to a node.

Parameters:
  • node

  • properties – relationship properties

Type:

StructuredNode

Type:

dict

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: Node | Relationship) → Any

Inflate the properties of a 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 turn resolve_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[T]

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

relations_to_fetch: list[Path]
source: Any
source_class: type[T]
class neomodel.sync_.match.NodeSet(source: Any)

A class representing as set of nodes matching common query parameters

annotate(*vars: tuple, **aliased_vars: tuple) → Self

Annotate node set results with extra variables.

bulk_create(*props: Any, **kwargs: Any) → list[T]

Create multiple nodes of this set’s class in a single round-trip.

Each positional argument is a dict of properties for one node. This is the batch counterpart to StructuredNode.save() (which creates one node); it replaces the deprecated MyNode.create(...) classmethod.

Parameters:
  • props – one dict of properties per node to create

  • lazy – if True, return nodes with element_id only

Returns:

list of created nodes, in the order supplied

bulk_create_or_update(*props: Any, **kwargs: Any) → list[T]

Create or update multiple nodes in a single MERGE round-trip.

Replaces the deprecated MyNode.create_or_update(...) classmethod. See bulk_create for the props/lazy/merge_by arguments.

Returns:

list of created/updated nodes, in the order supplied

bulk_get_or_create(*props: Any, **kwargs: Any) → list[T]

Get or create multiple nodes in a single MERGE round-trip.

Replaces the deprecated MyNode.get_or_create(...) classmethod. See bulk_create for the props/lazy/merge_by arguments.

Returns:

list of fetched/created nodes, in the order supplied

bulk_save(nodes: list[T]) → list[T]

Persist a list of node instances of this set’s class in bulk.

Convenience mirror of StructuredNode.bulk_save(...) so every batch operation is reachable from MyNode.nodes.

Parameters:

nodes – node instances to save

Returns:

the same instances, in order

dont_match: dict
exclude(*args: Any, **kwargs: Any) → Self

Exclude nodes from the NodeSet via filters.

Parameters:

kwargs – filter parameters see syntax for the filter method

Returns:

self

filter(*args: Any, **kwargs: Any) → Self

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

    • ’includes’: ArrayProperty contains the given element

    • ’includes_all’: ArrayProperty contains all the given elements

    • ’includes_any’: ArrayProperty contains any of the given elements

Returns:

self

filters: list
first(**kwargs: Any) → T

Retrieve the first node from the set matching supplied parameters

Parameters:

kwargs – same syntax as filter()

Returns:

node

first_or_none(**kwargs: Any) → T | None

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

Parameters:

kwargs – same syntax as filter()

Returns:

node or none

fulltext_query: FulltextFilter | None
get(lazy: bool = False, **kwargs: Any) → T

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) → T | None

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) → Self
must_match: dict
order_by(*props: Any) → Self

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

order_by_elements: list
relations_to_fetch: list[Path]
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: Self, return_set: list[str], initial_context: list[str | NodeNameResolver | RelationNameResolver | RawCypher] | None = None) → Self

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.

traverse(*paths: tuple[str, ...], **aliased_paths: dict) → Self

Specify a set of paths to traverse.

unique_variables(*paths: str) → Self

Generate unique variable names for the given paths.

vector_query: VectorFilter | None
class neomodel.sync_.match.Traversal(source: Any, name: str, definition: dict)

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 (dict) – A relationship definition that most certainly deserves a documentation here.

definition: dict
filters: list
match(**kwargs: dict[str, Any]) → NodeSet

Traverse relationships with properties matching the given parameters.

e.g: .match(price__lt=10)

Parameters:

kwargs – see NodeSet.filter() for syntax

Returns:

NodeSet wrapping this traversal

name: str
source: Any
source_class: Any
target_class: Any