Model a graph

An application with many queries repeats the same label, relationship type and property name in each query it builds. The opt-in cypher_dsl.model subpackage declares each graph name once and builds the same core AST nodes as the plain patterns. A plain import of cypher_dsl does not load the subpackage.

Declare the graph names

A node model subclasses NodeType and names its label with label=. A relationship model subclasses RelationshipType and names its type with type=. A name goes through the same identifier rules as the core builders.

label= also takes a label expression, and the class exposes the expression it declared as label, so a second declaration can compose labels that already exist. An optional label is not part of a declaration: a pattern that names a label matches only nodes that carry it, so membership that may be absent is a filter.

field(value_type, property_name=None) declares a property. Its Python name is the property name unless property_name supplies another one. Change the property name by declaring the field under a different Python name, or by passing property_name=.

Movie.named("m") returns a Movie pattern with m as its variable, which is what a field or link is read from. Reading a field on it, such as m.title, returns a Property expression for that property through the variable. It is an expression for a query position, not a row value, and it resolves only on a named instance, because the property read needs a variable.

value_type records the intended Python type of the value as declaration metadata. It is not checked against a value or an expression and does not change the rendered text, so field(list[str]) and field(str) render the same way.

rel(Relationship, Target) declares an outgoing link from one node model to another. Relationship names a RelationshipType declaration and Target names a NodeType declaration, and both must be concrete. rel() raises DslError for RelationshipType itself or NodeType itself, and a link member on a relationship model raises DslError when the class is created.

This version declares outgoing links only. For an incoming or undirected relationship, or a typed pattern map, use relationship_from, relationship_with and the property argument of node() instead.

Build a query from the declarations

The ordinary builders write the acting-credit query without a model:

from datetime import date

from cypher_dsl import Configuration, match, node, param

person = node("Person", name="p")
movie = node("Movie", name="m")
credit = person.relationship_to(movie, "ACTED_IN", name="r")
query = (
    match(credit)
    .where(
        (person["name"] == param("name", "Keanu Reeves"))
        & (movie["released"] >= param("released_after", date(1999, 1, 1)))
    )
    .returning(movie["title"], credit["roles"])
)
rendered = query.build().render(Configuration(server_version="5.26"))
print(rendered.cypher)
print(rendered.parameters)
MATCH (p:Person)-[r:ACTED_IN]->(m:Movie)
  WHERE p.`name` = $name AND m.released >= $released_after
RETURN m.title, r.`roles`
{'name': 'Keanu Reeves', 'released_after': datetime.date(1999, 1, 1)}

The model writes the same statement from declarations that name the graph identifiers once:

from datetime import date

from cypher_dsl import Configuration, match, param
from cypher_dsl.model import NodeType, RelationshipType, field, rel


class ActedIn(RelationshipType, type="ACTED_IN"):
    roles = field(list[str])


class Movie(NodeType, label="Movie"):
    title = field(str)
    released = field(date)


class Person(NodeType, label="Person"):
    name = field(str)
    acted_in = rel(ActedIn, Movie)


p, m = Person.named("p"), Movie.named("m")
credit = p.acted_in.to(m, name="r")
query = (
    match(credit)
    .where(
        (p.name == param("name", "Keanu Reeves"))
        & (m.released >= param("released_after", date(1999, 1, 1)))
    )
    .returning(m.title, credit.roles)
)
rendered = query.build().render(Configuration(server_version="5.26"))
print(rendered.cypher)
print(rendered.parameters)
MATCH (p:Person)-[r:ACTED_IN]->(m:Movie)
  WHERE p.`name` = $name AND m.released >= $released_after
RETURN m.title, r.`roles`
{'name': 'Keanu Reeves', 'released_after': datetime.date(1999, 1, 1)}

Both blocks print the same text and bindings. The model adds no clause, parameter or render rule of its own.

p.acted_in.to(m, name="r") names the relationship r, so credit.roles resolves the property on the returned ActedIn pattern. Leave name out and the relationship is anonymous, so its fields are unavailable. If the target is not an instance of the class declared in rel, to raises DslError.

Movie.label is the expression the declaration created. A second declaration composes declared labels, and a label that may be absent is a filter:

from cypher_dsl import Configuration, has_label, match

configuration = Configuration(server_version="5.26")

class Film(NodeType, label="Film"):
    title = field(str)


class Featured(NodeType, label="Featured"):
    pass


class Title(NodeType, label=Movie.label | Film.label):
    title = field(str)


title = Title.named("m")
titled = match(title).returning(title.title)
print(titled.build().render(configuration).cypher)

movie = Movie.named("m")
featured = has_label(movie, Featured.label)
filtered = match(movie).where(featured).returning(movie.title)
print(filtered.build().render(configuration).cypher)
MATCH (m:Movie|Film) RETURN m.title
MATCH (m:Movie) WHERE m:Featured RETURN m.title

Declarations are still patterns. NodeType subclasses NodePattern and RelationshipType subclasses RelationshipPattern, so match, create and merge take them directly. A core operation returns its core type, so m.with_predicate(...) returns a NodePattern, not a Movie. with_labels is the exception, because the labels it adds belong to that declaration: it returns the same model, so the fields remain available.

A declaration refuses the following, each with DslError when the class is created:

  • a __slots__ that is not empty, because the model fixes the instance layout so an instance cannot gain writable attributes

  • a second base, because mixins and multiple inheritance are not supported

  • the same field declared a second time, under any name, in the same class or in another one. Declare a second field, with property_name= when both read the same property.

  • a field or link named after an inherited pattern member such as properties. Declare it under a different Python name and pass the property name, as in properties_ = field(str, property_name="properties").

The model describes query vocabulary. It does not inspect string-based queries, map rows, validate graph data or install schema. A declaration change alters the text the builders produce, and nothing else: the library opens no connection.

Rename a property in the declaration

A property can have a different name in the graph than in Python. One declaration edit changes every query:

-    title = field(str)
+    title = field(str, property_name="primaryTitle")

Only the projection that reads m.title changes in the rendered text. The query code stays as it is:

MATCH (p:Person)-[r:ACTED_IN]->(m:Movie)
  WHERE p.`name` = $name AND m.released >= $released_after
RETURN m.primaryTitle, r.`roles`