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

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

async drop_constraints(quiet=True, stdout=None)

Discover and drop all constraints.

Type:

bool

Returns:

None

async drop_indexes(quiet=True, stdout=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=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, 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

async list_constraints() Sequence[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=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

async remove_all_labels(stdout=None)

Calls functions for dropping constraints and indexes.

Parameters:

stdout – output stream

Returns:

None

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

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

async 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

async 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

async 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 its relationships

Returns:

True

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

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

classmethod inherited_optional_labels()

Return list of optional labels from nodes class hierarchy.

Returns:

list

Return type:

list

async labels()

Returns list of labels tied to the node from neo4j.

Returns:

list of labels

Return type:

list

async refresh()

Reload the node from neo4j

save()

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

alias of NodeBaseDoesNotExist

neomodel.async_.core.ensure_connection(func)

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, **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(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, **kwargs)

Bases: RelationshipBase

Base class for relationship objects

async 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

async start_node()

Get start node

Returns:

StructuredNode

neomodel.async_.relationship.StructuredRelBase

alias of RelationshipBase

class neomodel.async_.relationship_manager.AsyncRelationshipManager(source, key, definition)

Bases: object

Base class for all relationships managed through neomodel.

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

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

dict

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

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

dict

Returns:

async single()

Get a single related node or none.

Returns:

StructuredNode

class neomodel.async_.relationship_manager.AsyncZeroOrMore(source, key, definition)

Bases: AsyncRelationshipManager

A relationship of zero or more nodes (the default)

class neomodel.async_.cardinality.AsyncOne(source, key, definition)

Bases: AsyncRelationshipManager

A relationship to a single node

async all()

Return single node in an array

Returns:

[node]

async connect(node, properties=None)

Connect a node

Parameters:
  • node

  • properties – relationship properties

Returns:

True / rel instance

async disconnect(node)

Disconnect a node

Parameters:

node

Returns:

async disconnect_all()

Disconnect all nodes

Returns:

async single()

Return the associated node.

Returns:

node

class neomodel.async_.cardinality.AsyncOneOrMore(source, key, definition)

Bases: AsyncRelationshipManager

A relationship to zero or more nodes.

async all()

Returns all related nodes.

Returns:

[node1, node2…]

async disconnect(node)

Disconnect node :param node: :return:

async single()

Fetch one of the related nodes

Returns:

Node

class neomodel.async_.cardinality.AsyncZeroOrOne(source, key, definition)

Bases: AsyncRelationshipManager

A relationship to zero or one node.

async all()

Return all related nodes.

Returns:

list

async connect(node, properties=None)

Connect to a node.

Parameters:
  • node

  • properties – relationship properties

Type:

StructuredNode

Type:

dict

Returns:

True / rel instance

async single()

Return the associated node.

Returns:

node

Property Manager

class neomodel.async_.property_manager.AsyncPropertyManager(**kwargs)

Bases: object

Common methods for handling properties on node and relationship objects.

classmethod deflate(properties, obj=None, skip_empty=False)

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)

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)

Bases: Path

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 nodes

The sequence of Node objects in this path.

property relationships

The sequence of Relationship objects 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=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

async check_bool()

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

async check_contains(obj)
async check_nonzero()

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

async get_item(key)
async get_len()
query_cls

alias of AsyncQueryBuilder

class neomodel.async_.match.AsyncNodeSet(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

async first(**kwargs)

Retrieve the first node from the set matching supplied parameters

Parameters:

kwargs – same syntax as filter()

Returns:

node

async 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

async 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

async 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.async_.match.AsyncTraversal(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