Async API Documentation

Core

class neomodel.async_.core.AsyncDatabase

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

async close_connection() None

Closes the currently open driver. The driver should always be closed at the end of the application’s lifecyle.

async drop_constraints(quiet: bool = True, stdout: TextIO | None = None) None

Discover and drop all constraints.

Type:

bool

Returns:

None

async drop_indexes(quiet: bool = True, stdout: TextIO | None = None) None

Discover and drop all indexes, except the automatically created token lookup indexes.

Type:

bool

Returns:

None

async 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

async 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

async 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:

bool

Returns:

None

async list_constraints() list[dict]

Returns all constraints existing in the database

Returns:

Sequence[dict]: List of dictionaries, each entry being a constraint definition

async 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

async remove_all_labels(stdout: TextIO | None = None) None

Calls functions for dropping constraints and indexes.

Parameters:

stdout – output stream

Returns:

None

async set_connection(url: str | None = None, driver: AsyncDriver | 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: AsyncTransactionProxy

Returns the current transaction object

class neomodel.async_.core.AsyncStructuredNode(*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 AsyncStructuredNodeDoesNotExist

async classmethod create(*props: tuple, **kwargs: dict[str, Any]) list

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

async 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

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

async 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.

Parameters:
  • query – cypher query string

  • params – query parameters

Type:

string

Type:

dict

Returns:

tuple containing a list of query results, and the meta information as a tuple

Return type:

tuple

delete() bool

Delete a node and its relationships

Returns:

True

async 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:

list

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:

list

async labels() list[str]

Returns list of labels tied to the node from neo4j.

Returns:

list of labels

Return type:

list

async refresh() None

Reload the node from neo4j

save() AsyncStructuredNode

Save the node to neo4j or raise an exception

Returns:

the node instance

property was_saved: bool

Shows status of node in the database. False, if node hasn’t been saved yet, True otherwise.

class neomodel.async_.core.NodeBase(**kwargs: dict[str, Any])
DoesNotExist

alias of NodeBaseDoesNotExist

neomodel.async_.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.

AsyncSemiStructuredNode

class neomodel.contrib.AsyncSemiStructuredNode(*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(AsyncSemiStructuredNode):
    name = StringProperty()
    age = IntegerProperty()

    def hello(self):
        print("Hi my names " + self.name)

tim = await Person(name='Tim', age=8, weight=11).save()
tim.hello = "Hi"
await tim.save() # DeflateConflict

Relationships

class neomodel.async_.relationship.AsyncStructuredRel(*args: Any, **kwargs: dict)

Bases: StructuredRelBase

Base class for relationship objects

async end_node() Any

Get end node

Returns:

StructuredNode

classmethod inflate(rel: Relationship) AsyncStructuredRel

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

save() AsyncStructuredRel

Save the relationship

Returns:

self

async start_node() Any

Get start node

Returns:

StructuredNode

class neomodel.async_.relationship.StructuredRelBase(**kwargs: dict[str, Any])

Bases: AsyncPropertyManager

class neomodel.async_.relationship_manager.AsyncRelationshipManager(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()

async all() list

Return all related nodes.

Returns:

list

all_relationships(node: AsyncStructuredNode) list[AsyncStructuredRel]

Retrieve all relationship objects between self and node.

Parameters:

node

Returns:

[StructuredRel]

connect(node: AsyncStructuredNode, properties: dict[str, Any] | None = None) AsyncStructuredRel | None

Connect a node

Parameters:
  • node

  • properties – for the new relationship

Type:

dict

Returns:

disconnect(node: AsyncStructuredNode) None

Disconnect a node

Parameters:

node

Returns:

disconnect_all() None

Disconnect all nodes

Returns:

exclude(*args: Any, **kwargs: dict) AsyncBaseSet

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) AsyncBaseSet

Retrieve related nodes matching the provided properties.

Parameters:
  • args – a Q object

  • kwargs – same syntax as NodeSet.filter()

Returns:

NodeSet

async get(**kwargs: Any) AsyncNodeSet

Retrieve a related node with the matching node properties.

Parameters:

kwargs – same syntax as NodeSet.filter()

Returns:

node

async get_or_none(**kwargs: dict) AsyncNodeSet

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

Parameters:

kwargs – same syntax as NodeSet.filter()

Returns:

node

async is_connected(node: AsyncStructuredNode) bool

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

match(**kwargs: dict) AsyncNodeSet

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

Parameters:

kwargs – same syntax as NodeSet.filter()

Returns:

NodeSet

order_by(*props: Any) AsyncBaseSet

Order related nodes by specified properties

Parameters:

props

Returns:

NodeSet

reconnect(old_node: AsyncStructuredNode, new_node: AsyncStructuredNode) 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: AsyncStructuredNode) AsyncStructuredRel | None

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

Parameters:

node

Returns:

StructuredRel

replace(node: AsyncStructuredNode, 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:

async single() AsyncStructuredNode | None

Get a single related node or none.

Returns:

StructuredNode

class neomodel.async_.relationship_manager.AsyncZeroOrMore(source: Any, key: str, definition: dict)

Bases: AsyncRelationshipManager

A relationship of zero or more nodes (the default)

class neomodel.async_.cardinality.AsyncOne(source: Any, key: str, definition: dict)

Bases: AsyncRelationshipManager

A relationship to a single node

async all() list[AsyncStructuredNode]

Return single node in an array

Returns:

[node]

async connect(node: AsyncStructuredNode, properties: dict[str, Any] | None = None) AsyncStructuredRel

Connect a node

Parameters:
  • node

  • properties – relationship properties

Returns:

True / rel instance

async disconnect(node: AsyncStructuredNode) None

Disconnect a node

Parameters:

node

Returns:

async disconnect_all() None

Disconnect all nodes

Returns:

async single() AsyncStructuredNode

Return the associated node.

Returns:

node

class neomodel.async_.cardinality.AsyncOneOrMore(source: Any, key: str, definition: dict)

Bases: AsyncRelationshipManager

A relationship to zero or more nodes.

async all() list[AsyncStructuredNode]

Returns all related nodes.

Returns:

[node1, node2…]

async disconnect(node: AsyncStructuredNode) None

Disconnect node :param node: :return:

async single() AsyncStructuredNode

Fetch one of the related nodes

Returns:

Node

class neomodel.async_.cardinality.AsyncZeroOrOne(source: Any, key: str, definition: dict)

Bases: AsyncRelationshipManager

A relationship to zero or one node.

async all() list[AsyncStructuredNode]

Return all related nodes.

Returns:

list

async connect(node: AsyncStructuredNode, properties: dict[str, Any] | None = None) AsyncStructuredRel

Connect to a node.

Parameters:
  • node

  • properties – relationship properties

Type:

StructuredNode

Type:

dict

Returns:

True / rel instance

async single() AsyncStructuredNode | None

Return the associated node.

Returns:

node

Property Manager

class neomodel.async_.property_manager.AsyncPropertyManager(**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.async_.path.AsyncNeomodelPath(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: AsyncStructuredNode

The last StructuredNode in this path.

property start_node: AsyncStructuredNode

The first StructuredNode in this path.

Match

class neomodel.async_.match.AsyncBaseSet

Base class for all node sets.

Contains common python magic methods, __len__, __contains__ etc

async 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

async check_bool() bool

Override for __bool__ dunder method. :return: True if the set contains any nodes, False otherwise :rtype: bool

async check_contains(obj: AsyncStructuredNode | Any) bool
async check_nonzero() bool

Override for __bool__ dunder method. :return: True if the set contains any node, False otherwise :rtype: bool

async get_item(key: int | slice) AsyncBaseSet | None
async get_len() int
query_cls

alias of AsyncQueryBuilder

source_class: type[AsyncStructuredNode]
class neomodel.async_.match.AsyncNodeSet(source: Any)

A class representing as set of nodes matching common query parameters

annotate(*vars: tuple, **aliased_vars: tuple) AsyncNodeSet

Annotate node set results with extra variables.

exclude(*args: Any, **kwargs: Any) AsyncBaseSet

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, ...]) AsyncNodeSet

Specify a set of relations to traverse and return.

filter(*args: Any, **kwargs: Any) AsyncBaseSet

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

async first(**kwargs: Any) Any

Retrieve the first node from the set matching supplied parameters

Parameters:

kwargs – same syntax as filter()

Returns:

node

async 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

async 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

async 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

has(**kwargs: Any) AsyncBaseSet
intermediate_transform(vars: dict[str, Transformation], distinct: bool = False, ordering: list | None = None) AsyncNodeSet
order_by(*props: Any) AsyncBaseSet

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

async 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.

async subquery(nodeset: AsyncNodeSet, return_set: list[str], initial_context: list[str] | None = None) AsyncNodeSet

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_relations(*relation_names: tuple[str, ...], **aliased_relation_names: dict) AsyncNodeSet

Specify a set of relations to traverse only.

unique_variables(*pathes: tuple[str, ...]) AsyncNodeSet

Generate unique variable names for the given pathes.

class neomodel.async_.match.AsyncTraversal(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: Any) AsyncTraversal

Traverse relationships with properties matching the given parameters.

e.g: .match(price__lt=10)

Parameters:

kwargs – see NodeSet.filter() for syntax

Returns:

self

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