API reference

The public surface is the cypher_dsl package itself. Every name in the section below is importable from cypher_dsl directly. The exception classes are also importable from cypher_dsl.errors.

Names in cypher_dsl

Construct and render Cypher queries from Python syntax objects.

The package is the public facade: every exported name is listed in __all__, so a missing export fails at import time in a test rather than later as a missing attribute.

Common tasks and the builders that serve them:

  • Start a statement: match, optional_match, create, merge, unwind, returning, with_, call_procedure, optional_call_procedure.

  • Describe a pattern: node, relationship_pattern, path_phrase, label, dynamic_label.

  • Filter rows: the where method, condition, raw, exists, path_pattern, has_label, is_labeled, is_not_labeled, is_type, is_not_type, all_, any_, none, single.

  • Project columns: returning, with_, count, collect_subquery, case, case_when, list_comprehension, map_projection, asc, desc.

  • Bind a value: param binds a parameter, lit renders a Python value as a Cypher literal, name references a variable.

  • Choose a target: Configuration, Language.

  • Render: Renderer.get(configuration).render(statement) or statement.render(configuration).

  • Compose queries: with_, union, call, optional_call.

class cypher_dsl.AstNode

Bases: Immutable

Base for a syntax node.

A node that holds other nodes states them in children itself, so the property cannot fall out of step with a field it does not know about.

property children: tuple[AstNode, ...]

Return this node’s syntax children, in the order it writes them.

class cypher_dsl.Builder(clauses: tuple[cypher_dsl.clauses.base.Clause, ...] = ())

Bases: cypher_dsl.ast.Immutable

An immutable sequence of clauses under construction.

The builder is the fluent construction facade, not a syntax node: each method returns a new builder, build() finalises it into a Statement, and as_draft() gives the unbuilt body a CALL or UNION can hold. Building requires a complete query: the last clause must be RETURN, a write clause, or a CALL whose body does not return and which reports no status, and every name a variable reads must be bound at that position.

clauses: tuple[cypher_dsl.clauses.base.Clause, ...]
as_draft() → QueryDraft

Return the unbuilt body a CALL or UNION can hold.

returning(*expressions: cypher_dsl.expressions.base.ProjectionInput) → Builder

Append a RETURN clause.

A bare string becomes a variable name, a named pattern becomes its variable, an existing expression passes through unchanged, and any other supported Python value becomes a literal. Unlike with_, a computed item needs no alias, because nothing after RETURN reads its name.

with_(*expressions: cypher_dsl.expressions.base.ProjectionInput) → Builder

Append a WITH clause.

A bare string becomes a variable name. Any other projection item must be a variable, a raw item, or carry an alias through .alias(), because the next query part needs a name for it.

match(*patterns: cypher_dsl.patterns.nodes.PatternElement) → Builder

Append a MATCH clause.

optional_match(*patterns: cypher_dsl.patterns.nodes.PatternElement) → Builder

Append an OPTIONAL MATCH clause.

unwind(values: cypher_dsl.expressions.base.ExpressionInput, variable: cypher_dsl.expressions.values.Variable) → Builder

Append an UNWIND clause that binds one variable to each element.

call(subquery: Builder | cypher_dsl.statement.Statement | cypher_dsl.statements.composition.UnionSyntax, imports: tuple[str | cypher_dsl.expressions.values.Variable, ...] = (), import_all: bool = False, in_transactions: cypher_dsl.clauses.in_transactions.InTransactions | None = None) → Builder

Append a CALL clause that runs a nested query in its own scope.

A body must stay a builder or a draft when standalone validation cannot resolve a name it reads, which can happen when it reads an import it does not declare and nothing in its own text accounts for that name. Pass named imports or import_all, never both. For inner transactions, pass an InTransactions modifier: the default InTransactions() renders the bare modifier, InTransactions(rows=...) adds OF ... ROWS, InTransactions(concurrency=...) adds the concurrent form, on_error adds the failure policy and report_status binds the batch status after the call.

Example

>>> from cypher_dsl import Configuration, match, name, node
>>> person = node("Person", name="p")
>>> movie = node("Movie", name="m")
>>> body = match(movie).where(movie["title"] == person["favourite"]).returning(name("m"))
>>> statement = match(person).call(body, imports=("p",)).returning(name("m"))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) CALL (p) { MATCH (m:Movie) WHERE m.title = p.favourite RETURN m } RETURN m'
optional_call(subquery: Builder | cypher_dsl.statement.Statement | cypher_dsl.statements.composition.UnionSyntax, imports: tuple[str | cypher_dsl.expressions.values.Variable, ...] = (), import_all: bool = False, in_transactions: cypher_dsl.clauses.in_transactions.InTransactions | None = None) → Builder

Append an OPTIONAL CALL clause that keeps a row without nested output.

The import rules call states apply here too, and so do its transaction forms: InTransactions(rows=...) renders OPTIONAL CALL ... IN TRANSACTIONS OF 5 ROWS. An outer row with no body output survives with null bindings for the exported names.

call_procedure(procedure_name: str, *arguments: cypher_dsl.expressions.base.ExpressionInput) → Builder

Append a CALL clause that invokes a stored procedure.

optional_call_procedure(procedure_name: str, *arguments: cypher_dsl.expressions.base.ExpressionInput) → Builder

Append an OPTIONAL CALL clause that invokes a stored procedure.

yielding(*items: str | cypher_dsl.clauses.call_procedure.YieldItem) → Builder

Attach more YIELD items to the procedure call that immediately precedes them.

create(*patterns: cypher_dsl.patterns.nodes.PatternElement) → Builder

Append a CREATE clause.

merge(pattern: cypher_dsl.patterns.nodes.PatternElement) → Builder

Append a MERGE clause.

on_create(*updates: cypher_dsl.clauses.assignments.Assignment) → Builder

Attach an ON CREATE action to the merge that immediately precedes it.

on_match(*updates: cypher_dsl.clauses.assignments.Assignment) → Builder

Attach an ON MATCH action to the merge that immediately precedes it.

set_(*updates: cypher_dsl.clauses.assignments.Update) → Builder

Append a SET clause.

remove(*targets: cypher_dsl.clauses.remove.RemoveTarget) → Builder

Append a REMOVE clause.

delete(*targets: cypher_dsl.expressions.base.ExpressionInput) → Builder

Append a DELETE clause.

detach_delete(*targets: cypher_dsl.expressions.base.ExpressionInput) → Builder

Append a DETACH DELETE clause.

where(condition: cypher_dsl.expressions.base.ConditionInput) → Builder

Attach a filter to the clause that immediately precedes it.

distinct() → Builder

Mark the current projection as distinct.

group_by(*keys: cypher_dsl.expressions.base.ExpressionInput) → Builder

Add explicit grouping keys to the current projection.

Grouping needs Neo4j 2026.07 and Cypher 25, so a statement that uses it selects the CYPHER 25 prefix under Language.AUTO. A bare string is a variable name. Repeated calls append keys. group_by and group_by_all are mutually exclusive on one projection.

group_by_all() → Builder

Mark every non-aggregating projection item as a grouping key.

GROUP BY ALL has the same Neo4j 2026.07 and Cypher 25 floor as group_by. It takes no keys and cannot be combined with group_by on one projection.

order_by(*items: cypher_dsl.expressions.base.ExpressionInput | cypher_dsl.expressions.values.SortItem) → Builder

Add ordering items to the current projection.

skip(value: int | cypher_dsl.expressions.base.Expression) → Builder

Carry a SKIP value on the current projection.

limit(value: int | cypher_dsl.expressions.base.Expression) → Builder

Carry a LIMIT value on the current projection.

build() → cypher_dsl.statement.Statement

Finalise the builder into a statement and compile its fragment.

Returns:

A Statement that holds the completed fragment, its requirements and a binding snapshot.

Raises:

DslError – If the clauses are empty, the last clause cannot end a statement, a name is read before it is bound, or two bindings for one parameter name conflict.

cypher_dsl.StatementBuilder
cypher_dsl.returning(*expressions: cypher_dsl.expressions.base.ProjectionInput) → Builder

Start a statement builder with a RETURN clause.

A bare string is a variable name, a named pattern becomes its variable, and any other supported Python value becomes a literal. A top-level computed item needs no alias, because Neo4j names it implicitly. A RETURN that ends a CALL subquery must alias a computed item, because the enclosing query reads that name. Use with_ when a later query part reads the projected names.

Example

>>> from cypher_dsl import Configuration, lit, param, returning
>>> statement = returning(lit(1).alias("one"), param("label", "Person"))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'RETURN 1 AS one, $label'
cypher_dsl.with_(*expressions: cypher_dsl.expressions.base.ProjectionInput) → Builder

Start a statement with a WITH projection that ends one query part and starts the next.

Only the local names the projection lists are visible to the query part that follows. A name imported by an enclosing CALL stays visible, because the call fixes it rather than the local query part. A structured item needs an alias, because the next part reads the name rather than the expression. A bare string is already a variable name.

Example

>>> from cypher_dsl import Configuration, lit, name, with_
>>> statement = with_(lit(1).alias("one")).returning(name("one"))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'WITH 1 AS one RETURN one'
class cypher_dsl.Assignment(target: cypher_dsl.expressions.base.Expression, value: cypher_dsl.expressions.base.Expression, kind: UpdateKind = UpdateKind.ASSIGN)

Bases: cypher_dsl.ast.AstNode

A property assignment or a patch of the properties named by a map.

target: cypher_dsl.expressions.base.Expression
value: cypher_dsl.expressions.base.Expression
kind: UpdateKind
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the target, then the value.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write the target, the update operator and the value.

class cypher_dsl.LabelUpdate(target: cypher_dsl.expressions.values.Variable, labels: tuple[cypher_dsl.expressions.values.SymbolicName | cypher_dsl.expressions.labels.DynamicLabel, ...])

Bases: cypher_dsl.ast.AstNode

One or more labels added to or removed from a named element.

target: cypher_dsl.expressions.values.Variable
labels: tuple[cypher_dsl.expressions.values.SymbolicName | cypher_dsl.expressions.labels.DynamicLabel, ...]
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the target, then each dynamic label expression.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write the variable followed by its labels in source order.

cypher_dsl.Update: TypeAlias = Assignment | LabelUpdate
class cypher_dsl.UpdateKind

Bases: enum.Enum

Which property update an assignment performs.

ASSIGN = '='
PATCH = '+='
cypher_dsl.assign(target: cypher_dsl.expressions.base.ExpressionInput, value: cypher_dsl.expressions.base.ExpressionInput) → Assignment

Build an assignment that uses the = update operator.

A property reference or a dynamic subscript sets one property, and a null value removes it. A variable target replaces the element’s property set, taking the new properties from the right-hand side. The DSL accepts the targets and leaves the value rules to Neo4j. Use update_properties to merge entries into the set instead of replacing it.

Example

>>> from cypher_dsl import Configuration, assign, match, node, param
>>> person = node("Person", name="p")
>>> statement = match(person).set_(assign(person["email"], param("email", "ada@example.com")))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) SET p.email = $email'
cypher_dsl.set_labels(target: cypher_dsl.expressions.base.NamedExpression | cypher_dsl.expressions.values.Variable, *labels: str | cypher_dsl.expressions.labels.DynamicLabel) → LabelUpdate

Build a label update for a node, keeping the first occurrence of each label.

The target is a node pattern or the variable that names a node. The DSL does not check that the variable denotes a node, so a relationship variable renders and the server rejects it. A repeated static label is ignored. A $() term is appended in call order and is never de-duplicated. $any() and $all() are refused, because only $() is writable.

Example

>>> from cypher_dsl import Configuration, match, node, set_labels
>>> person = node("Person", name="p")
>>> statement = match(person).set_(set_labels(person, "Employee", "Staff"))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) SET p:Employee:Staff'
cypher_dsl.update_properties(target: cypher_dsl.expressions.base.ExpressionInput, value: cypher_dsl.expressions.base.ExpressionInput) → Assignment

Build a patch that merges the properties of the value into the target.

SET p += $changes adds or overwrites the map’s non-null entries, removes the properties whose entries are null, and retains the properties the map omits. The target is the element variable itself, not a property reference. The signature accepts any expression for symmetry with assign, but any other target raises DslError.

Example

>>> from cypher_dsl import Configuration, match, node, param, update_properties
>>> person = node("Person", name="p")
>>> statement = match(person).set_(update_properties(person, param("changes", {"rating": 5})))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) SET p += $changes'
class cypher_dsl.Clause

Bases: cypher_dsl.ast.AstNode

A syntax node with a fixed position in a statement.

abstractmethod build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this clause under the given scope and return the scope it leaves behind.

localise_reads(scope: cypher_dsl.scope.Scope, reads: frozenset[str]) → cypher_dsl.scope.Scope

Return the scope after the names this clause reads join its query part.

A direct read of a fixed name makes it a column a later wildcard projects. A clause whose projection alone decides membership returns the scope unchanged.

finalises_statement() → bool

Return whether this clause can end a statement.

class cypher_dsl.ProcedureCallClause(name: tuple[str, ...], arguments: tuple[cypher_dsl.expressions.base.Expression, ...], optional: bool, yields: tuple[YieldItem, ...] = (), predicate: cypher_dsl.expressions.operators.Condition | None = None)

Bases: cypher_dsl.clauses.base.Clause

A CALL of a stored procedure that binds the columns it yields.

name: tuple[str, ...]
arguments: tuple[cypher_dsl.expressions.base.Expression, ...]
optional: bool
yields: tuple[YieldItem, ...]
predicate: cypher_dsl.expressions.operators.Condition | None
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the arguments, the yields, then the filter when present.

with_where(predicate: cypher_dsl.expressions.operators.Condition) → ProcedureCallClause

Return a copy whose single filter also requires the predicate.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this clause under the given scope and return the scope it leaves behind.

finalises_statement() → bool

Return True when the call binds nothing, because such a call needs no RETURN.

cypher_dsl.YieldItem
cypher_dsl.call_procedure(procedure_name: str, *arguments: cypher_dsl.expressions.base.ExpressionInput) → cypher_dsl.builder.Builder

Start a builder with a CALL clause that invokes a stored procedure.

The name is one dot-qualified string, split at construction. yielding names the output columns the following clauses read. A standalone call without yield items finalises the statement on its own, and the server returns every column the procedure yields.

Example

>>> from cypher_dsl import Configuration, call_procedure
>>> statement = call_procedure("db.propertyKeys").yielding("propertyKey").returning("propertyKey")
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'CALL db.propertyKeys() YIELD propertyKey RETURN propertyKey'
cypher_dsl.optional_call_procedure(procedure_name: str, *arguments: cypher_dsl.expressions.base.ExpressionInput) → cypher_dsl.builder.Builder

Start a builder with an OPTIONAL CALL clause that invokes a stored procedure.

It renders OPTIONAL CALL. The explicitly yielded names are null on a row that receives no procedure output, the same way OPTIONAL MATCH keeps a row without a match.

Example

>>> from cypher_dsl import Configuration, optional_call_procedure
>>> statement = optional_call_procedure("db.propertyKeys").yielding("propertyKey").returning("propertyKey")
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'OPTIONAL CALL db.propertyKeys() YIELD propertyKey RETURN propertyKey'
class cypher_dsl.SubqueryCallClause(subquery: cypher_dsl.builder.Builder | cypher_dsl.builder.QueryDraft | cypher_dsl.statement.Statement | cypher_dsl.statements.composition.UnionSyntax, imports: tuple[cypher_dsl.expressions.values.Variable, ...] = (), import_all: bool = False, optional: bool = False, in_transactions: cypher_dsl.clauses.in_transactions.InTransactions | None = None)

Bases: cypher_dsl.clauses.base.Clause

A CALL subquery holding a nested body, its imports and its transaction modifier.

The body is a builder, a finalised statement or a union draft. It is written under a seed scope that binds the imports and reserves them, so it reads no enclosing name it did not import. The clause finalises a statement only when the body does not return and the modifier reports no status, because a returning body and a reported status each need a subsequent clause. A reported status name joins the outer scope after the call, so it must be new to the enclosing scope and must not repeat a body export.

subquery: cypher_dsl.builder.QueryDraft | cypher_dsl.statement.Statement | cypher_dsl.statements.composition.UnionSyntax
imports: tuple[cypher_dsl.expressions.values.Variable, ...]
import_all: bool
optional: bool
in_transactions: cypher_dsl.clauses.in_transactions.InTransactions | None
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the imports, the body and the transaction modifier, in render order.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this clause under the given scope and return the scope it leaves behind.

finalises_statement() → bool

Return True when the body does not return and the modifier reports no status.

cypher_dsl.call(subquery: cypher_dsl.builder.Builder | cypher_dsl.statement.Statement | cypher_dsl.statements.composition.UnionSyntax, imports: tuple[str | cypher_dsl.expressions.values.Variable, ...] = (), import_all: bool = False, in_transactions: cypher_dsl.clauses.in_transactions.InTransactions | None = None) → cypher_dsl.builder.Builder

Start a statement whose only clause calls a nested query.

The body is a statement builder, a finalised statement or a union draft. When this factory’s result is built at the root, an explicit import has no earlier clause to bind it, so the build rejects the name. Inside a nested body the enclosing call supplies the import, so the factory can start that body. Use Builder.call after a MATCH or UNWIND for a root-level import.

Example

>>> from cypher_dsl import Configuration, call, create, node
>>> statement = call(create(node("Log", name="l"))).build()
>>> statement.render(Configuration(server_version="5.26")).cypher
'CALL () { CREATE (l:Log) }'
cypher_dsl.optional_call(subquery: cypher_dsl.builder.Builder | cypher_dsl.statement.Statement | cypher_dsl.statements.composition.UnionSyntax, imports: tuple[str | cypher_dsl.expressions.values.Variable, ...] = (), import_all: bool = False, in_transactions: cypher_dsl.clauses.in_transactions.InTransactions | None = None) → cypher_dsl.builder.Builder

Start a builder with an OPTIONAL CALL clause that runs a nested query in its own scope.

An outer row with no body output survives with null bindings for the exported names, the same way OPTIONAL MATCH keeps a row without a match. The import rules of call apply here too.

Example

>>> from cypher_dsl import Configuration, match, name, node, optional_call
>>> body = match(node("Movie", name="m")).returning(name("m"))
>>> statement = optional_call(body).returning(name("m"))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'OPTIONAL CALL () { MATCH (m:Movie) RETURN m } RETURN m'
class cypher_dsl.CreateClause(patterns: tuple[cypher_dsl.patterns.nodes.PatternElement, ...])

Bases: cypher_dsl.clauses.base.Clause

A CREATE clause holding one or more patterns.

Every pattern is a single node or an unquantified chain. A relationship needs exactly one type and a direction, because the clause creates it rather than matching it. A pattern with an inline element predicate is refused. The clause finalises a statement.

patterns: tuple[cypher_dsl.patterns.nodes.PatternElement, ...]
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the patterns in order.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this clause under the given scope and return the scope it leaves behind.

finalises_statement() → bool

Return True, because CREATE needs no RETURN.

cypher_dsl.create(*patterns: cypher_dsl.patterns.nodes.PatternElement) → cypher_dsl.builder.Builder

Start a statement with a CREATE clause that writes each pattern.

A written relationship needs exactly one type and a direction, because the clause creates it rather than matching it. A pattern with an inline element predicate is refused. CREATE finalises a statement, so no RETURN is required.

Example

>>> from cypher_dsl import Configuration, create, node, param
>>> person = node("Person", name="p", properties={"email": param("email", "ada@example.com")})
>>> create(person).build().render(Configuration(server_version="5.26")).cypher
'CREATE (p:Person {email: $email})'
class cypher_dsl.DeleteClause(targets: tuple[cypher_dsl.expressions.values.Variable, ...], detach: bool = False)

Bases: cypher_dsl.clauses.base.Clause

A DELETE or DETACH DELETE clause holding named element references.

targets: tuple[cypher_dsl.expressions.values.Variable, ...]
detach: bool
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the targets in order.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this clause under the given scope and return the scope it leaves behind.

finalises_statement() → bool

Return True, because DELETE needs no RETURN.

class cypher_dsl.DisjointBy

Bases: enum.Enum

The keyword forms of the DISJOINT BY transaction option.

AUTO = 'AUTO'
NONE = 'NONE'
class cypher_dsl.InTransactions(rows: cypher_dsl.expressions.base.ExpressionInput | None = None, concurrency: bool | cypher_dsl.expressions.base.ExpressionInput = False, report_status: str | None = None, on_error: OnError | RetryOnError | None = None, disjoint_by: tuple[cypher_dsl.expressions.base.ExpressionInput, ...] | DisjointBy | None = None)

Bases: cypher_dsl.ast.AstNode

The transaction modifier of a CALL subquery.

rows writes OF ... ROWS and defaults to no row count, so the server default applies. concurrency accepts a boolean or a count. True writes CONCURRENT without a count, False adds no concurrency keyword, and any other value writes its count before CONCURRENT as the maximum number of batches that may run at once. on_error writes the failure policy: one of the OnError modes or a RetryOnError. report_status writes REPORT STATUS AS <name> and binds that name in the scope after the call, so the status cannot be used inside the body and the call no longer finalises a statement on its own.

disjoint_by writes DISJOINT BY (<key>, ...) and accepts a non-empty tuple of key expressions, or DisjointBy.AUTO and DisjointBy.NONE. It requires the concurrent form, so a literal False for concurrency raises DslError. The keys are built against the names the call imports, not the outer scope, the body or the status.

When report_status is set to a name, on_error must be OnError.CONTINUE, OnError.BREAK, or a RetryOnError whose then is one of those modes. Neo4j checks the evaluated counts and duration.

rows: cypher_dsl.expressions.base.Expression | None
concurrency: bool | cypher_dsl.expressions.base.Expression
report_status: str | None
on_error: OnError | RetryOnError | None
disjoint_by: tuple[cypher_dsl.expressions.base.Expression, ...] | DisjointBy | None
property children: tuple[cypher_dsl.ast.AstNode, ...]

count, rows, keys, then retry duration.

Type:

Return the explicit operands in render order

class cypher_dsl.OnError

Bases: enum.Enum

What a failing inner transaction does to the batches that follow it.

CONTINUE skips the failed batch and runs the remaining ones. BREAK stops scheduling new batches and keeps the output rows already produced, with null inner results for the failed and skipped batches. FAIL stops the call and raises.

Whatever the mode, a batch that committed is not rolled back and a failed batch rolls back in full. Under concurrent batches, stopping or rolling back a batch that is already running is not guaranteed, so those batches may still commit. Where REPORT STATUS is eligible, the status, not the row order, identifies the batches that committed.

A retry that reaches its time limit uses its then policy, which is FAIL when it states none.

CONTINUE = 'CONTINUE'
BREAK = 'BREAK'
FAIL = 'FAIL'
class cypher_dsl.RetryOnError(for_seconds: cypher_dsl.expressions.base.ExpressionInput | None = None, then: OnError | None = None)

The retry error policy, with an optional limit and fallback.

Neo4j retries a batch only when it fails with a transient error, waiting longer between attempts. for_seconds writes FOR <expression> SECONDS and sets the time limit for one batch; zero allows a single retry. It is rendered, not evaluated, so Neo4j decides whether the value is a legal time limit. then writes the policy applied when the limit is reached; an omitted fallback is the server’s FAIL.

The value is immutable, is not a syntax node, and compares by identity. Its duration operand appears in InTransactions.children in render order.

for_seconds: cypher_dsl.expressions.base.Expression | None
then: OnError | None
class cypher_dsl.MatchClause(pattern: cypher_dsl.patterns.graph_pattern.GraphPattern, optional: bool = False, where: cypher_dsl.clauses.where.Where | None = None)

Bases: cypher_dsl.clauses.base.Clause

A pattern-matching clause with the filter that belongs to it.

MATCH does not finalise a statement. Its filter is rendered after the pattern, and a second call to with_where joins the predicate with AND instead of adding a second WHERE.

pattern: cypher_dsl.patterns.graph_pattern.GraphPattern
optional: bool
where: cypher_dsl.clauses.where.Where | None
with_where(predicate: cypher_dsl.expressions.operators.Condition) → MatchClause

Return a copy whose single filter also requires the predicate.

property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the pattern elements, then the attached filter when present.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this clause under the given scope and return the scope it leaves behind.

cypher_dsl.match(*patterns: cypher_dsl.patterns.nodes.PatternElement) → cypher_dsl.builder.Builder

Start a statement with a MATCH clause that finds every matching pattern.

MATCH cannot end a statement, so another clause follows. A filter added with where belongs to this clause. A node that repeats a name already bound by the clause or an earlier clause is a reference and takes no label. The DSL rejects a label on it. An explicit property map on that reference is still rendered.

Example

>>> from cypher_dsl import Configuration, match, node, param
>>> movie = node("Movie", name="m")
>>> statement = match(movie).where(movie["released"] < param("year", 2000)).returning(movie["title"])
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (m:Movie) WHERE m.released < $year RETURN m.title'
cypher_dsl.optional_match(*patterns: cypher_dsl.patterns.nodes.PatternElement) → cypher_dsl.builder.Builder

Start a statement with an OPTIONAL MATCH clause that keeps rows without a match.

A row whose pattern finds nothing survives with null bindings for the names the pattern declares. A filter added with where belongs to this clause. Like MATCH, the clause does not finalise a statement.

Example

>>> from cypher_dsl import Configuration, node, optional_match
>>> statement = optional_match(node("Person", name="p")).returning("p")
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'OPTIONAL MATCH (p:Person) RETURN p'
class cypher_dsl.MergeAction(keyword: str, updates: tuple[cypher_dsl.clauses.assignments.Assignment, ...])

Bases: cypher_dsl.ast.AstNode

One ON CREATE or ON MATCH action with the assignments it applies.

keyword: str
updates: tuple[cypher_dsl.clauses.assignments.Assignment, ...]
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the assignments in order.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write the action keyword and its assignment list.

class cypher_dsl.MergeClause(pattern: cypher_dsl.patterns.nodes.PatternElement, actions: tuple[MergeAction, ...] = ())

Bases: cypher_dsl.clauses.base.Clause

A MERGE clause with its identity pattern and the actions it owns.

The identity is the pattern itself, so its properties must be written out. A whole-map parameter is refused, because the server would have to inspect the map to match. A pattern with an inline element predicate is refused. At most one ON CREATE and one ON MATCH action may attach, and the clause finalises a statement.

pattern: cypher_dsl.patterns.nodes.PatternElement
actions: tuple[MergeAction, ...]
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the identity pattern, then the actions.

with_action(action: MergeAction) → MergeClause

Return a copy with one more action attached.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this clause under the given scope and return the scope it leaves behind.

finalises_statement() → bool

Return True, because MERGE needs no RETURN.

cypher_dsl.merge(pattern: cypher_dsl.patterns.nodes.PatternElement) → cypher_dsl.builder.Builder

Start a statement with a MERGE clause that matches or creates one pattern.

The pattern is the identity. Property keys are optional. When supplied, write them explicitly, because a whole-map parameter is refused. A pattern whose names are already visible renders as a reference. A pattern with an inline element predicate is refused. on_create and on_match attach actions to the merge, at most one of each. The clause finalises a statement.

Example

>>> from cypher_dsl import Configuration, assign, merge, node, param
>>> person = node("Person", name="p", properties={"email": param("email", "ada@example.com")})
>>> statement = merge(person).on_create(assign(person["created_at"], param("now", "2026-11-25T09:00:00")))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MERGE (p:Person {email: $email}) ON CREATE SET p.created_at = $now'
class cypher_dsl.RemoveClause(targets: tuple[RemoveTarget, ...])

Bases: cypher_dsl.clauses.base.Clause

A REMOVE clause holding property references and label updates.

targets: tuple[RemoveTarget, ...]
build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this clause under the given scope and return the scope it leaves behind.

finalises_statement() → bool

Return True, because REMOVE needs no RETURN.

cypher_dsl.RemoveTarget: TypeAlias = Property | SubscriptExpression | LabelUpdate
class cypher_dsl.ReturnClause(expressions: tuple[cypher_dsl.expressions.base.Expression, ...], distinct: bool = False, *, group_by: tuple[cypher_dsl.expressions.base.Expression, ...] = (), group_all: bool = False, order_by: tuple[cypher_dsl.expressions.base.Expression | cypher_dsl.expressions.values.SortItem, ...] = (), skip: cypher_dsl.expressions.base.Expression | None = None, limit: cypher_dsl.expressions.base.Expression | None = None)

Bases: cypher_dsl.clauses.projection.ProjectionClause

A projection that ends a statement and makes its columns available.

keyword: ClassVar[str] = 'RETURN'
build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write the projection and leave exactly the columns it projects.

finalises_statement() → bool

Return True, because a statement may end in RETURN.

class cypher_dsl.SetClause(updates: tuple[cypher_dsl.clauses.assignments.Update, ...])

Bases: cypher_dsl.clauses.base.Clause

A SET clause holding property and label updates.

updates: tuple[cypher_dsl.clauses.assignments.Update, ...]
build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this clause under the given scope and return the scope it leaves behind.

finalises_statement() → bool

Return True, because SET needs no RETURN.

class cypher_dsl.UnwindClause(values: cypher_dsl.expressions.base.Expression, variable: cypher_dsl.expressions.values.Variable)

Bases: cypher_dsl.clauses.base.Clause

An UNWIND clause holding the collection expression and the variable each row binds.

The variable is bound for the clauses that follow, and the clause does not finalise a statement. The source must be an expression, and an asterisk is rejected.

values: cypher_dsl.expressions.base.Expression
variable: cypher_dsl.expressions.values.Variable
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the source expression, then the bound variable.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write the source under the incoming scope, then bind the alias in the output.

cypher_dsl.unwind(values: cypher_dsl.expressions.base.ExpressionInput, variable: cypher_dsl.expressions.values.Variable) → cypher_dsl.builder.Builder

Start a statement with an UNWIND clause that turns a collection into rows.

Each element binds the variable for the clauses that follow. The source is an operand expression, so an alias or an asterisk is rejected. A parameter is accepted and its value need not be a list. The clause does not finalise a statement, and WHERE is not part of it: project the row variable through WITH first.

Example

>>> from cypher_dsl import Configuration, name, param, unwind
>>> statement = unwind(param("rows"), name("item")).returning(name("item"))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'UNWIND $rows AS item RETURN item'
class cypher_dsl.Where(predicate: cypher_dsl.expressions.operators.Condition)

Bases: cypher_dsl.ast.AstNode

A predicate rendered immediately after its owning clause.

It is not a clause in its own right: the owning MATCH, WITH or procedure call places it, and the builder rejects a filter with no clause to own it.

predicate: cypher_dsl.expressions.operators.Condition
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the predicate.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope
class cypher_dsl.WithClause(expressions: tuple[cypher_dsl.expressions.base.Expression, ...], distinct: bool = False, where: cypher_dsl.clauses.where.Where | None = None, *, group_by: tuple[cypher_dsl.expressions.base.Expression, ...] = (), group_all: bool = False, order_by: tuple[cypher_dsl.expressions.base.Expression | cypher_dsl.expressions.values.SortItem, ...] = (), skip: cypher_dsl.expressions.base.Expression | None = None, limit: cypher_dsl.expressions.base.Expression | None = None)

Bases: cypher_dsl.clauses.projection.ProjectionClause

A projection that ends one query part and starts the next.

A bare raw() item is kept as trusted text and makes the names this projection supplies unknown to later clauses; an aliased raw item supplies its declared name.

keyword: ClassVar[str] = 'WITH'
where: cypher_dsl.clauses.where.Where | None
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the projected expressions, the modifiers in render order, then the filter.

with_where(predicate: cypher_dsl.expressions.operators.Condition) → WithClause

Return a copy whose single filter also requires the predicate.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this clause under the given scope and return the scope it leaves behind.

localise_reads(scope: cypher_dsl.scope.Scope, reads: frozenset[str]) → cypher_dsl.scope.Scope

Return the scope unchanged: a WITH decides membership by its projection alone.

exception cypher_dsl.ConflictingParameterError

Bases: DslError

Raised when one parameter name carries two different bindings.

exception cypher_dsl.DslError

Bases: Exception

Base class for every construction and rendering failure.

exception cypher_dsl.EmptyPatternError

Bases: DslError

Raised when a grammar position requires at least one pattern or item.

exception cypher_dsl.InvalidClauseOrderError

Bases: DslError

Raised when clauses form a sequence that Cypher does not accept.

exception cypher_dsl.InvalidIdentifierError

Bases: DslError

Raised when a name cannot be rendered as a quoted identifier.

exception cypher_dsl.InvalidLiteralError

Bases: DslError

Raised when a Python value cannot be represented as a frozen literal.

exception cypher_dsl.UnsupportedFeatureError

Bases: DslError

Raised when a requested construct is outside the implemented surface.

cypher_dsl.ConditionInput: TypeAlias = ExpressionInput
class cypher_dsl.Expression

Bases: cypher_dsl.ast.AstNode

Base for every node that can appear in an expression position.

property precedence: Precedence

Return how tightly this expression binds in its parent.

abstractmethod build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

alias(alias: str) → AliasedExpression
cypher_dsl.ExpressionInput: TypeAlias = LiteralInput | Expression | NamedExpression
cypher_dsl.LiteralInput: TypeAlias = bool | int | float | str | bytes | date | datetime | time | timedelta | Sequence['LiteralInput'] | Mapping[str, 'LiteralInput'] | None
class cypher_dsl.NamedExpression

A syntax node with a variable reference for expression positions.

abstractmethod as_expression() → Expression

Return the reference, rejecting a node that binds no name.

class cypher_dsl.Precedence

Bases: enum.IntEnum

Binding strength of an expression, lowest first.

OR = 0
XOR = 1
AND = 2
NOT = 3
COMPARISON = 4
ADDITIVE = 5
MULTIPLICATIVE = 6
UNARY = 7
ATOM = 8
cypher_dsl.ProjectionInput: TypeAlias = ExpressionInput
cypher_dsl.coerce_condition(value: ConditionInput) → cypher_dsl.expressions.operators.Condition

Turn a value into a predicate, rejecting a non-boolean literal or an asterisk.

Example

>>> from cypher_dsl import Configuration, coerce_condition, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).where(coerce_condition(True)).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) WHERE true RETURN p'
cypher_dsl.coerce_expression(value: ExpressionInput) → Expression

Turn a Python value or a named syntax node into an expression node.

Example

>>> from cypher_dsl import Configuration, coerce_expression, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).returning(coerce_expression(person))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) RETURN p'
cypher_dsl.condition(value: ConditionInput) → cypher_dsl.expressions.operators.Condition

Treat an explicitly boolean expression as a predicate.

Example

>>> from cypher_dsl import Configuration, condition, match, node, param
>>> person = node("Person", name="p")
>>> statement = match(person).where(condition(param("active"))).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) WHERE $active RETURN p'
class cypher_dsl.ListExpression(items: tuple[cypher_dsl.expressions.base.Expression, ...])

Bases: cypher_dsl.expressions.base.Expression

A list whose items are expressions in rendered order.

items: tuple[cypher_dsl.expressions.base.Expression, ...]
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the items in order.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

class cypher_dsl.MapExpression(entries: tuple[MapEntry, ...])

Bases: cypher_dsl.expressions.base.Expression

A map whose keys are names and whose values are expressions, in source order.

entries: tuple[MapEntry, ...]
build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

classmethod from_mapping(items: collections.abc.Mapping[str, cypher_dsl.expressions.base.ExpressionInput]) → MapExpression

Snapshot a caller’s string-keyed mapping into typed entries.

cypher_dsl.list_(*items: cypher_dsl.expressions.base.ExpressionInput) → ListExpression

Build a list expression from ordered items, allowing an empty list.

Example

>>> from cypher_dsl import Configuration, list_, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).returning(list_(person["uid"], "active"))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
"MATCH (p:Person) RETURN [p.uid, 'active']"
cypher_dsl.map_(items: collections.abc.Mapping[str, cypher_dsl.expressions.base.ExpressionInput]) → MapExpression

Build a map expression from a string-keyed mapping, allowing an empty map.

Example

>>> from cypher_dsl import Configuration, map_, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).returning(map_({"uid": person["uid"], "verified": True}))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) RETURN {uid: p.uid, verified: true}'
class cypher_dsl.ListComprehension(variable: cypher_dsl.expressions.values.Variable, list: cypher_dsl.expressions.base.Expression, where: cypher_dsl.expressions.operators.Condition | None = None, result: cypher_dsl.expressions.base.Expression | None = None)

Bases: cypher_dsl.expressions.base.Expression

Build a list from the elements of another list that pass an optional filter.

variable: cypher_dsl.expressions.values.Variable
list: cypher_dsl.expressions.base.Expression
where: cypher_dsl.expressions.operators.Condition | None
result: cypher_dsl.expressions.base.Expression | None
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the variable, the source list, the filter and the result, skipping absent parts.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

class cypher_dsl.QuantifiedListPredicate(quantifier: Literal['all', 'any', 'none', 'single'], variable: cypher_dsl.expressions.values.Variable, list: cypher_dsl.expressions.base.Expression, where: cypher_dsl.expressions.operators.Condition)

Bases: cypher_dsl.expressions.operators.Condition

Test how many elements of a list satisfy a condition.

quantifier: Literal['all', 'any', 'none', 'single']
variable: cypher_dsl.expressions.values.Variable
list: cypher_dsl.expressions.base.Expression
where: cypher_dsl.expressions.operators.Condition
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the element variable, the list and the predicate.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

class cypher_dsl.ReduceExpression(accumulator: cypher_dsl.expressions.values.Variable, initial: cypher_dsl.expressions.base.Expression, variable: cypher_dsl.expressions.values.Variable, list: cypher_dsl.expressions.base.Expression, expression: cypher_dsl.expressions.base.Expression)

Bases: cypher_dsl.expressions.base.Expression

Fold a list into one value, binding the accumulator and the element inside the fold.

accumulator: cypher_dsl.expressions.values.Variable
initial: cypher_dsl.expressions.base.Expression
variable: cypher_dsl.expressions.values.Variable
list: cypher_dsl.expressions.base.Expression
expression: cypher_dsl.expressions.base.Expression
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the accumulator, the initial value, the element variable, the list and the expression.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

cypher_dsl.all_(variable: cypher_dsl.expressions.values.Variable, list: cypher_dsl.expressions.base.ExpressionInput, where: cypher_dsl.expressions.base.ConditionInput) → QuantifiedListPredicate

Test whether every element of the list satisfies the condition.

Example

>>> from cypher_dsl import Configuration, all_, match, name, node
>>> person = node("Person", name="p")
>>> statement = match(person).where(all_(name("r"), person["ratings"], name("r") >= 4)).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) WHERE all(r IN p.ratings WHERE r >= 4) RETURN p'
cypher_dsl.any_(variable: cypher_dsl.expressions.values.Variable, list: cypher_dsl.expressions.base.ExpressionInput, where: cypher_dsl.expressions.base.ConditionInput) → QuantifiedListPredicate

Test whether at least one element of the list satisfies the condition.

Example

>>> from cypher_dsl import Configuration, any_, match, name, node
>>> person = node("Person", name="p")
>>> statement = match(person).where(any_(name("r"), person["ratings"], name("r") >= 4)).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) WHERE any(r IN p.ratings WHERE r >= 4) RETURN p'
cypher_dsl.list_comprehension(variable: cypher_dsl.expressions.values.Variable, list: cypher_dsl.expressions.base.ExpressionInput, where: cypher_dsl.expressions.base.ConditionInput | None = None, result: cypher_dsl.expressions.base.ExpressionInput | None = None) → ListComprehension

Build [variable IN list WHERE p | e] with the predicate and mapping optional.

The source list is read in the enclosing scope. The element variable is visible only in where and result, so a name of the same spelling outside the expression refers to the outer binding. Without result the kept element is the value.

Example

>>> from cypher_dsl import Configuration, list_comprehension, match, name, node
>>> person = node("Person", name="p")
>>> statement = match(person).returning(list_comprehension(name("x"), person["xs"], result=name("x")))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) RETURN [x IN p.xs | x]'
cypher_dsl.none(variable: cypher_dsl.expressions.values.Variable, list: cypher_dsl.expressions.base.ExpressionInput, where: cypher_dsl.expressions.base.ConditionInput) → QuantifiedListPredicate

Test whether no element of the list satisfies the condition.

Example

>>> from cypher_dsl import Configuration, match, name, node, none
>>> person = node("Person", name="p")
>>> statement = match(person).where(none(name("r"), person["ratings"], name("r") >= 4)).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) WHERE none(r IN p.ratings WHERE r >= 4) RETURN p'
cypher_dsl.reduce(accumulator: cypher_dsl.expressions.values.Variable, initial: cypher_dsl.expressions.base.ExpressionInput, variable: cypher_dsl.expressions.values.Variable, list: cypher_dsl.expressions.base.ExpressionInput, expression: cypher_dsl.expressions.base.ExpressionInput) → ReduceExpression

Build reduce(accumulator = initial, variable IN list | expression).

initial and list are read in the enclosing scope. The accumulator and the element variable are visible only in expression, and they must differ from each other.

Example

>>> from cypher_dsl import Configuration, match, name, node, reduce
>>> person = node("Person", name="p")
>>> total = reduce(name("total"), 0, name("rating"), person["ratings"], name("total") + name("rating"))
>>> statement = match(person).returning(total.alias("rating_total"))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) RETURN reduce(total = 0, rating IN p.ratings | total + rating) AS rating_total'
cypher_dsl.single(variable: cypher_dsl.expressions.values.Variable, list: cypher_dsl.expressions.base.ExpressionInput, where: cypher_dsl.expressions.base.ConditionInput) → QuantifiedListPredicate

Test whether exactly one element of the list satisfies the condition.

Example

>>> from cypher_dsl import Configuration, match, name, node, single
>>> person = node("Person", name="p")
>>> statement = match(person).where(single(name("r"), person["ratings"], name("r") >= 4)).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) WHERE single(r IN p.ratings WHERE r >= 4) RETURN p'
class cypher_dsl.Case(branches: tuple[CaseWhen, ...], else_: cypher_dsl.expressions.base.Expression | None = None)

Bases: cypher_dsl.expressions.base.Expression

Choose the value of the first branch whose condition holds.

branches: tuple[CaseWhen, ...]
else_: cypher_dsl.expressions.base.Expression | None
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the branches in order, then the fallback when present.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

class cypher_dsl.CaseWhen(condition: cypher_dsl.expressions.operators.Condition, value: cypher_dsl.expressions.base.Expression)

Bases: cypher_dsl.ast.AstNode

One WHEN/THEN branch of a CASE expression.

condition: cypher_dsl.expressions.operators.Condition
value: cypher_dsl.expressions.base.Expression
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the condition, then the value.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope
cypher_dsl.case(*branches: CaseWhen, else_: cypher_dsl.expressions.base.ExpressionInput | None = None) → Case

Build a searched CASE expression from branches in test order.

Only the searched form is built. The form that compares one operand against each WHEN is refused, and raw builds it. The branches and the fallback are expressions read in the enclosing scope.

Example

>>> from cypher_dsl import Configuration, case, case_when, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).returning(case(case_when(person["age"] < 18, "minor"), else_="adult"))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
"MATCH (p:Person) RETURN CASE WHEN p.age < 18 THEN 'minor' ELSE 'adult' END"
cypher_dsl.case_when(condition: cypher_dsl.expressions.base.ConditionInput, value: cypher_dsl.expressions.base.ExpressionInput) → CaseWhen

Build one WHEN/THEN branch, rejecting a non-boolean literal predicate.

Example

>>> from cypher_dsl import Configuration, case, case_when, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).returning(case(case_when(person["age"] < 18, "minor")).alias("band"))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
"MATCH (p:Person) RETURN CASE WHEN p.age < 18 THEN 'minor' END AS band"
class cypher_dsl.Asterisk

Bases: cypher_dsl.expressions.base.Expression

The explicit * projection or argument.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

class cypher_dsl.ElementId(operand: cypher_dsl.expressions.base.Expression)

Bases: FunctionInvocation

A call to elementId with its operand.

class cypher_dsl.FunctionInvocation(function_name: tuple[str, ...], arguments: tuple[cypher_dsl.expressions.base.Expression, ...], distinct: bool = False)

Bases: cypher_dsl.expressions.base.Expression

A call to a function whose name may be dot-qualified and whose arguments are expressions.

function_name: tuple[str, ...]
arguments: tuple[cypher_dsl.expressions.base.Expression, ...]
distinct: bool
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the arguments in order.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

class cypher_dsl.RawExpression(text: str)

Bases: cypher_dsl.expressions.base.Expression

Trusted Cypher expression text rendered exactly as supplied.

text: str
property precedence: cypher_dsl.expressions.base.Precedence

Return the weakest level so a parent groups text whose own operators are unknown.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

cypher_dsl.asterisk() → Asterisk

Return the explicit * expression used by projections and count.

Example

>>> from cypher_dsl import Configuration, asterisk, count, returning
>>> returning(count(asterisk())).build().render(Configuration(server_version="5.26")).cypher
'RETURN count(*)'
cypher_dsl.count(value: cypher_dsl.expressions.base.ExpressionInput, distinct: bool = False) → FunctionInvocation

Build a count invocation, optionally over distinct values.

Example

>>> from cypher_dsl import Configuration, count, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).returning(count(person).alias("people"))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) RETURN count(p) AS people'
cypher_dsl.element_id(value: cypher_dsl.expressions.base.ExpressionInput) → ElementId

Build an elementId invocation without rewriting any other function name.

Example

>>> from cypher_dsl import Configuration, element_id, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).returning(element_id(person).alias("identifier"))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) RETURN elementId(p) AS identifier'
cypher_dsl.fn(function_name: str, *arguments: cypher_dsl.expressions.base.ExpressionInput) → FunctionInvocation

Call a function by name, splitting a dot-qualified name into segments.

A bare string argument stays a literal. The library does not know the function’s signature: it counts arguments only for the unqualified built-ins nodes, relationships and length, and leaves an unknown name alone, because it may be a user-defined function.

Example

>>> from cypher_dsl import Configuration, fn, lit, returning
>>> returning(fn("coalesce", lit(None), "unknown")).build().render(Configuration(server_version="5.26")).cypher
"RETURN coalesce(null, 'unknown')"
cypher_dsl.length(path: cypher_dsl.expressions.base.ExpressionInput) → FunctionInvocation

Build a length invocation over a path.

Only the arity is checked. The library does not prove that the argument holds a path.

Example

>>> from cypher_dsl import Configuration, length, match, name, node, path_phrase
>>> route = name("route")
>>> walked = node("Person", name="p").relationship_to(node("Dog"), "WALKS")
>>> statement = match(path_phrase(walked, variable=route)).returning(length(route))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH route = (p:Person)-[:WALKS]->(:Dog) RETURN length(route)'
cypher_dsl.nodes(path: cypher_dsl.expressions.base.ExpressionInput) → FunctionInvocation

Build a nodes invocation over a path.

Only the arity is checked. The library does not prove that the argument holds a path, so a node variable renders and the server rejects it.

Example

>>> from cypher_dsl import Configuration, match, name, node, nodes, path_phrase
>>> route = name("route")
>>> walked = node("Person", name="p").relationship_to(node("Dog"), "WALKS")
>>> statement = match(path_phrase(walked, variable=route)).returning(nodes(route))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH route = (p:Person)-[:WALKS]->(:Dog) RETURN nodes(route)'
cypher_dsl.raw(text: str) → RawExpression

Wrap trusted Cypher expression text that the library neither escapes nor inspects.

Use it for syntax the library does not model. It is not a parser or a safety boundary: the text is returned unchanged, so supply text you have checked. Never build its text from caller data. Where a predicate is required, wrap the result with condition.

Example

>>> from cypher_dsl import Configuration, raw, returning
>>> returning(raw("CASE 1 WHEN 1 THEN 2 END")).build().render(Configuration(server_version="5.26")).cypher
'RETURN CASE 1 WHEN 1 THEN 2 END'
cypher_dsl.relationships(path: cypher_dsl.expressions.base.ExpressionInput) → FunctionInvocation

Build a relationships invocation over a path.

Only the arity is checked. The library does not prove that the argument holds a path.

Example

>>> from cypher_dsl import Configuration, match, name, node, path_phrase, relationships
>>> route = name("route")
>>> walked = node("Person", name="p").relationship_to(node("Dog"), "WALKS")
>>> statement = match(path_phrase(walked, variable=route)).returning(relationships(route))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH route = (p:Person)-[:WALKS]->(:Dog) RETURN relationships(route)'
class cypher_dsl.HasLabel(operand: cypher_dsl.expressions.base.Expression, labels: cypher_dsl.expressions.labels.LabelExpression)

Bases: cypher_dsl.expressions.operators.Condition

The colon form of a label predicate.

operand: cypher_dsl.expressions.base.Expression
labels: cypher_dsl.expressions.labels.LabelExpression
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the operand, then the label expression.

property precedence: cypher_dsl.expressions.base.Precedence

Return how tightly this expression binds in its parent.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

class cypher_dsl.IsLabeled(operand: cypher_dsl.expressions.base.Expression, labels: cypher_dsl.expressions.labels.LabelExpression, negated: bool = False)

Bases: cypher_dsl.expressions.operators.Condition

The IS [NOT] LABELED form of a label predicate.

operand: cypher_dsl.expressions.base.Expression
labels: cypher_dsl.expressions.labels.LabelExpression
negated: bool
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the operand, then the label expression.

property precedence: cypher_dsl.expressions.base.Precedence

Return how tightly this expression binds in its parent.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

cypher_dsl.has_label(element: cypher_dsl.expressions.base.NamedExpression | cypher_dsl.expressions.base.Expression, labels: str | cypher_dsl.expressions.labels.LabelExpression) → HasLabel

Build the colon form of a label predicate.

The element is a named pattern or an expression. A colon list built by with_labels is rejected here, and a dynamic term needs Cypher 25 and Neo4j 2025.07.

Example

>>> from cypher_dsl import Configuration, has_label, label, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).where(has_label(person, label("Manager") | label("Director")))
>>> statement.returning(person).build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) WHERE p:Manager|Director RETURN p'
cypher_dsl.is_labeled(element: cypher_dsl.expressions.base.NamedExpression | cypher_dsl.expressions.base.Expression, labels: str | cypher_dsl.expressions.labels.LabelExpression) → IsLabeled

Build the IS LABELED form of a label predicate.

The negated form IS NOT LABELED negates the whole expression, which differs from ~ on one term. It needs Neo4j 2026.04 and Cypher 25, so a statement that uses it selects the CYPHER 25 prefix under Language.AUTO.

Example

>>> from cypher_dsl import Configuration, is_labeled, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).where(is_labeled(person, "Employee")).returning(person)
>>> statement.build().render(Configuration(server_version="2026.10")).cypher
'CYPHER 25 MATCH (p:Person) WHERE p IS LABELED Employee RETURN p'
cypher_dsl.is_not_labeled(element: cypher_dsl.expressions.base.NamedExpression | cypher_dsl.expressions.base.Expression, labels: str | cypher_dsl.expressions.labels.LabelExpression) → IsLabeled

Build the IS NOT LABELED form of a label predicate.

It negates the whole label expression, which differs from ~ on one term. A null operand makes the predicate null rather than true. It needs Neo4j 2026.04 and Cypher 25.

Example

>>> from cypher_dsl import Configuration, is_not_labeled, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).where(is_not_labeled(person, "Employee")).returning(person)
>>> statement.build().render(Configuration(server_version="2026.10")).cypher
'CYPHER 25 MATCH (p:Person) WHERE p IS NOT LABELED Employee RETURN p'
cypher_dsl.ANY_LABEL
class cypher_dsl.DynamicLabel(expression: cypher_dsl.expressions.base.Expression, mode: DynamicLabelMode = DynamicLabelMode.PLAIN)

Bases: LabelExpression

A label or relationship type supplied by an expression at run time.

expression: cypher_dsl.expressions.base.Expression
mode: DynamicLabelMode
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the label expression.

property precedence: LabelPrecedence

Return the term’s binding strength.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write the bare term under the given scope.

class cypher_dsl.LabelExpression

Bases: cypher_dsl.ast.AstNode

Base for a label term that a pattern or predicate can carry.

abstract property precedence: LabelPrecedence

Return the term’s binding strength.

abstractmethod build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write the bare term under the given scope.

class cypher_dsl.LabelName(name: cypher_dsl.expressions.values.SymbolicName)

Bases: LabelExpression

One label or relationship type name.

name: cypher_dsl.expressions.values.SymbolicName
property precedence: LabelPrecedence

Return the term’s binding strength.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write the bare term under the given scope.

cypher_dsl.dynamic_label(expression: cypher_dsl.expressions.base.Expression) → DynamicLabel

Build the $() form, which writes a label or type decided at run time.

The argument is an expression, never a bare string. This is the only dynamic form a write clause accepts, and it needs Neo4j 5.26 or later.

Example

>>> from cypher_dsl import Configuration, dynamic_label, match, name, node, param
>>> statement = match(node(dynamic_label(param("label")), name="n")).returning(name("n"))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (n:$($label)) RETURN n'
cypher_dsl.label(name: str) → LabelName

Build one label name term.

Terms combine with &, | and ~ and render in a node pattern, a relationship detail or a label predicate. A colon list of several names comes from with_labels, not from this factory.

Example

>>> from cypher_dsl import Configuration, label, match, node
>>> pattern = node(label("Movie") | label("Series"), name="m")
>>> statement = match(pattern).returning(pattern["title"])
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (m:Movie|Series) RETURN m.title'
cypher_dsl.label_all(expression: cypher_dsl.expressions.base.Expression) → DynamicLabel

Build the $all() form, true when the labels hold every name of a list.

A read form only. A dynamic term in a pattern needs Neo4j 5.26, and in the colon-form predicate it needs Cypher 25 and Neo4j 2025.07.

Example

>>> from cypher_dsl import Configuration, label, label_all, match, node, param
>>> pattern = node(label("Person") & label_all(param("tags")), name="n")
>>> statement = match(pattern).returning(pattern["uid"])
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (n:Person&$all($tags)) RETURN n.uid'
cypher_dsl.label_any(expression: cypher_dsl.expressions.base.Expression) → DynamicLabel

Build the $any() form, true when the labels hold any name of a list.

A read form only: CREATE, MERGE, SET and REMOVE reject it. A dynamic term in the colon-form predicate needs Cypher 25 and Neo4j 2025.07.

Example

>>> from cypher_dsl import Configuration, label, label_any, match, node, param
>>> pattern = node(label("Person") & label_any(param("tags")), name="n")
>>> statement = match(pattern).returning(pattern["uid"])
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (n:Person&$any($tags)) RETURN n.uid'
class cypher_dsl.MapProjection(variable: cypher_dsl.expressions.values.Variable, properties: tuple[cypher_dsl.expressions.values.SymbolicName, ...] = (), entries: tuple[cypher_dsl.expressions.collections.MapEntry, ...] = (), all_properties: bool = False)

Bases: cypher_dsl.expressions.base.Expression

Read selected properties and entries of a variable into a map.

variable: cypher_dsl.expressions.values.Variable
properties: tuple[cypher_dsl.expressions.values.SymbolicName, ...]
entries: tuple[cypher_dsl.expressions.collections.MapEntry, ...]
all_properties: bool
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the projected variable.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

cypher_dsl.map_projection(variable: cypher_dsl.expressions.values.Variable | cypher_dsl.expressions.base.NamedExpression, properties: collections.abc.Sequence[str] = (), entries: collections.abc.Mapping[str, cypher_dsl.expressions.base.ExpressionInput] | None = None, all_properties: bool = False) → MapProjection

Build a map projection from selected property names, entries and the all-properties selector.

The base is a named pattern or a name() variable. At least one selector is required. A bare string entry value stays a literal, so a variable value needs name or a property read. Duplicate keys are rejected, and all_properties=True puts .* before the other selectors.

Example

>>> from cypher_dsl import Configuration, map_projection, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).returning(map_projection(person, properties=("uid",))).build()
>>> statement.render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) RETURN p{.uid}'
class cypher_dsl.BinaryOperation(operator: str, left: cypher_dsl.expressions.base.Expression, right: cypher_dsl.expressions.base.Expression)

Bases: cypher_dsl.expressions.base.Expression

Two operands joined by an arithmetic or concatenation operator.

operator: str
left: cypher_dsl.expressions.base.Expression
right: cypher_dsl.expressions.base.Expression
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the left operand, then the right operand.

property precedence: cypher_dsl.expressions.base.Precedence

Return how tightly this expression binds in its parent.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

class cypher_dsl.BooleanOperation(operator: str, left: Condition, right: Condition)

Bases: Condition

Two predicates joined by AND, OR or XOR.

operator: str
left: Condition
right: Condition
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the left predicate, then the right predicate.

property precedence: cypher_dsl.expressions.base.Precedence

Return how tightly this expression binds in its parent.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

class cypher_dsl.Comparison(operator: str, left: cypher_dsl.expressions.base.Expression, right: cypher_dsl.expressions.base.Expression | None = None)

Bases: Condition

A binary comparison, string predicate, regex match or null test.

operator: str
left: cypher_dsl.expressions.base.Expression
right: cypher_dsl.expressions.base.Expression | None
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the left operand, then the right operand when present.

property precedence: cypher_dsl.expressions.base.Precedence

Return how tightly this expression binds in its parent.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

class cypher_dsl.Condition

Bases: cypher_dsl.expressions.base.Expression

Base for an expression whose value is a predicate.

class cypher_dsl.UnaryOperation(operator: str, operand: cypher_dsl.expressions.base.Expression)

Bases: cypher_dsl.expressions.base.Expression

An operand preceded by unary arithmetic or NOT.

operator: str
operand: cypher_dsl.expressions.base.Expression
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the operand.

property precedence: cypher_dsl.expressions.base.Precedence

Return how tightly this expression binds in its parent.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

cypher_dsl.boolean_operation(operator: str, left: cypher_dsl.expressions.base.ConditionInput, right: cypher_dsl.expressions.base.ConditionInput) → Condition

Join two predicates with a logical operator.

Example

>>> from cypher_dsl import Configuration, boolean_operation, contains, match, node
>>> person = node("Person", name="p")
>>> predicate = boolean_operation("AND", contains(person["title"], "Neo"), contains(person["title"], "Matrix"))
>>> statement = match(person).where(predicate).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
"MATCH (p:Person) WHERE p.title CONTAINS 'Neo' AND p.title CONTAINS 'Matrix' RETURN p"
cypher_dsl.concat(left: cypher_dsl.expressions.base.ExpressionInput, right: cypher_dsl.expressions.base.ExpressionInput) → BinaryOperation

Build a || concatenation. Both operands are strings, or both are lists.

Example

>>> from cypher_dsl import Configuration, concat, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).returning(concat(concat(person["first"], " "), person["last"]))
>>> statement.build().render(Configuration(server_version="5.26")).cypher
"MATCH (p:Person) RETURN p.first || ' ' || p.last"
cypher_dsl.contains(value: cypher_dsl.expressions.base.ExpressionInput, substring: cypher_dsl.expressions.base.ExpressionInput) → Condition

Build a CONTAINS string predicate.

Example

>>> from cypher_dsl import Configuration, contains, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).where(contains(person["title"], "Neo")).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
"MATCH (p:Person) WHERE p.title CONTAINS 'Neo' RETURN p"
cypher_dsl.ends_with(value: cypher_dsl.expressions.base.ExpressionInput, suffix: cypher_dsl.expressions.base.ExpressionInput) → Condition

Build an ENDS WITH string predicate.

Example

>>> from cypher_dsl import Configuration, ends_with, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).where(ends_with(person["title"], "?")).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
"MATCH (p:Person) WHERE p.title ENDS WITH '?' RETURN p"
cypher_dsl.in_(value: cypher_dsl.expressions.base.ExpressionInput, collection: cypher_dsl.expressions.base.ExpressionInput) → Condition

Build a membership test.

Example

>>> from cypher_dsl import Configuration, in_, list_, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).where(in_(person["city"], list_("Berlin", "Paris"))).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
"MATCH (p:Person) WHERE p.city IN ['Berlin', 'Paris'] RETURN p"
cypher_dsl.matches(value: cypher_dsl.expressions.base.ExpressionInput, pattern: cypher_dsl.expressions.base.ExpressionInput) → Condition

Build a =~ regular expression match.

Example

>>> from cypher_dsl import Configuration, match, matches, node
>>> person = node("Person", name="p")
>>> statement = match(person).where(matches(person["title"], ".*Matrix.*")).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
"MATCH (p:Person) WHERE p.title =~ '.*Matrix.*' RETURN p"
cypher_dsl.starts_with(value: cypher_dsl.expressions.base.ExpressionInput, prefix: cypher_dsl.expressions.base.ExpressionInput) → Condition

Build a STARTS WITH string predicate.

Example

>>> from cypher_dsl import Configuration, match, node, starts_with
>>> person = node("Person", name="p")
>>> statement = match(person).where(starts_with(person["title"], "The")).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
"MATCH (p:Person) WHERE p.title STARTS WITH 'The' RETURN p"
class cypher_dsl.PathPatternExpression(pattern: cypher_dsl.patterns.relationships.RelationshipPattern)

Bases: cypher_dsl.expressions.operators.Condition

Test whether a relationship chain matches, reading names an earlier clause binds.

pattern: cypher_dsl.patterns.relationships.RelationshipPattern
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the pattern.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

cypher_dsl.path_pattern(pattern: cypher_dsl.patterns.relationships.RelationshipPattern) → PathPatternExpression

Build a relationship chain as a boolean predicate.

Every named node and relationship must already be bound at the position of the expression. The expression binds none of its own. An inline element predicate is refused; use exists() with a MATCH body for that test.

Example

>>> from cypher_dsl import Configuration, match, node, path_pattern
>>> person = node("Person", name="p")
>>> knows = person.relationship_to(node("Person", name="q"), "KNOWS")
>>> statement = match(person, node("Person", name="q")).where(path_pattern(knows)).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person), (q:Person) WHERE (p:Person)-[:KNOWS]->(q:Person) RETURN p'
class cypher_dsl.Property(expression: cypher_dsl.expressions.base.Expression, key: cypher_dsl.expressions.values.SymbolicName)

Bases: cypher_dsl.expressions.base.Expression

A statically named property of another expression.

expression: cypher_dsl.expressions.base.Expression
key: cypher_dsl.expressions.values.SymbolicName
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the expression.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

class cypher_dsl.SubscriptExpression(expression: cypher_dsl.expressions.base.Expression, key: cypher_dsl.expressions.base.Expression)

Bases: cypher_dsl.expressions.base.Expression

A value selected from another expression by an index or key expression.

expression: cypher_dsl.expressions.base.Expression
key: cypher_dsl.expressions.base.Expression
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the expression, then the key.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

class cypher_dsl.CollectExpression(subquery: cypher_dsl.builder.QueryDraft | cypher_dsl.statement.Statement | cypher_dsl.statements.composition.UnionSyntax)

Bases: SubqueryExpression

Collect the single column a nested query body returns into a list.

keyword: ClassVar[str] = 'COLLECT'
class cypher_dsl.CountExpression(subquery: cypher_dsl.builder.QueryDraft | cypher_dsl.statement.Statement | cypher_dsl.statements.composition.UnionSyntax)

Bases: SubqueryExpression

Count the rows a nested query body produces.

keyword: ClassVar[str] = 'COUNT'
class cypher_dsl.ExistsExpression(subquery: cypher_dsl.builder.QueryDraft | cypher_dsl.statement.Statement | cypher_dsl.statements.composition.UnionSyntax)

Bases: SubqueryExpression, cypher_dsl.expressions.operators.Condition

Test whether a nested query body produces at least one row.

keyword: ClassVar[str] = 'EXISTS'
class cypher_dsl.SubqueryExpression(subquery: cypher_dsl.builder.QueryDraft | cypher_dsl.statement.Statement | cypher_dsl.statements.composition.UnionSyntax)

Bases: cypher_dsl.expressions.base.Expression

Base for an expression whose value comes from a nested query body.

keyword: ClassVar[str] = ''
subquery: cypher_dsl.builder.QueryDraft | cypher_dsl.statement.Statement | cypher_dsl.statements.composition.UnionSyntax
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the subquery body.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

cypher_dsl.collect_subquery(body: cypher_dsl.builder.Builder | cypher_dsl.statement.Statement | cypher_dsl.statements.composition.UnionSyntax | cypher_dsl.patterns.nodes.PatternElement) → CollectExpression

Build COLLECT { ... } from a nested query body.

Every branch must end in a RETURN with exactly one explicit column. RETURN * is one projection item to the DSL, but Neo4j 5.26 rejects it here.

Example

>>> from cypher_dsl import Configuration, collect_subquery, in_, lit, match, node
>>> person = node("Person", name="p")
>>> dog = node("Dog", name="d")
>>> walked = match(node(name="p").relationship_to(dog, "WALKS")).returning(dog["name"])
>>> statement = match(person).where(in_(lit("Ozzy"), collect_subquery(walked))).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
"MATCH (p:Person) WHERE 'Ozzy' IN COLLECT { MATCH (p)-[:WALKS]->(d:Dog) RETURN d.`name` } RETURN p"
cypher_dsl.count_subquery(body: cypher_dsl.builder.Builder | cypher_dsl.statement.Statement | cypher_dsl.statements.composition.UnionSyntax | cypher_dsl.patterns.nodes.PatternElement) → CountExpression

Build COUNT { ... } from a nested query body.

The body counts its rows, so a final RETURN is optional. A plain UNION body needs RETURN in every branch, while a UNION ALL body does not.

Example

>>> from cypher_dsl import Configuration, count_subquery, lit, match, node
>>> person = node("Person", name="p")
>>> walked = match(node(name="p").relationship_to(node("Dog"), "WALKS"))
>>> statement = match(person).where(count_subquery(walked) > lit(1)).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) WHERE COUNT { MATCH (p)-[:WALKS]->(:Dog) } > 1 RETURN p'
cypher_dsl.exists(body: cypher_dsl.builder.Builder | cypher_dsl.statement.Statement | cypher_dsl.statements.composition.UnionSyntax | cypher_dsl.patterns.nodes.PatternElement) → ExistsExpression

Build EXISTS { ... } from a nested query body.

The body is a statement builder, a draft, a finalised statement or a single pattern element. It is written under a correlated scope, so it reads the enclosing names without an import clause, and the names it binds stay inside the expression.

A body that reads an enclosing name is normally passed as a builder, because building it alone would find that name unbound.

Example

>>> from cypher_dsl import Configuration, exists, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).where(
...     exists(node(name="p").relationship_to(node("Dog"), "HAS_DOG"))
... ).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) WHERE EXISTS { MATCH (p)-[:HAS_DOG]->(:Dog) } RETURN p'
class cypher_dsl.TypePredicate(operand: cypher_dsl.expressions.base.Expression, type_name: str, negated: bool = False, not_null: bool = False)

Bases: cypher_dsl.expressions.operators.Condition

Test a value’s runtime type with the IS [NOT] :: form.

operand: cypher_dsl.expressions.base.Expression
type_name: str
negated: bool
not_null: bool
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the operand.

property precedence: cypher_dsl.expressions.base.Precedence

Return the comparison level, where the grammar places a type predicate.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

cypher_dsl.is_not_type(operand: cypher_dsl.expressions.base.Expression, type_name: str, not_null: bool = False) → TypePredicate

Build the IS NOT :: form of a type predicate.

It is the complement of the type, so with not_null it is true for a null value.

Example

>>> from cypher_dsl import Configuration, is_not_type, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).where(is_not_type(person["rating"], "INTEGER")).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) WHERE p.rating IS NOT :: INTEGER RETURN p'
cypher_dsl.is_type(operand: cypher_dsl.expressions.base.Expression, type_name: str, not_null: bool = False) → TypePredicate

Build the IS :: form of a type predicate.

type_name is one of the server’s simple type names or synonyms, rendered as written. A closed union, a parametrised or postfix list type and IS TYPED are refused; build those with raw. not_null appends NOT NULL, which excludes null.

Example

>>> from cypher_dsl import Configuration, is_type, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).where(is_type(person["uid"], "STRING", not_null=True)).returning(person)
>>> statement.build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) WHERE p.uid IS :: STRING NOT NULL RETURN p'
class cypher_dsl.AliasedExpression(expression: Expression, alias_name: SymbolicName)

Bases: Expression

An expression projected under another name.

expression: Expression
alias_name: SymbolicName
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the aliased expression.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

class cypher_dsl.Literal(value: cypher_dsl.parameters.FrozenValue)

Bases: cypher_dsl.expressions.base.Expression

A Cypher literal whose value was frozen when the node was built.

value: cypher_dsl.parameters.FrozenValue
build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

class cypher_dsl.Parameter(symbol: cypher_dsl.expressions.base.SymbolicName, binding: cypher_dsl.parameters.FrozenValue | cypher_dsl.parameters.Unbound)

Bases: cypher_dsl.expressions.base.Expression

One $name query parameter occurrence with an optional frozen binding.

param(“p”, value) binds the value when the parameter is built, so the statement’s parameter dictionary carries it. param(“p”) leaves it unbound and lists the name in unbound_parameters. Either way the text renders as $p; the value never enters it.

symbol: cypher_dsl.expressions.base.SymbolicName
binding: cypher_dsl.parameters.FrozenValue | cypher_dsl.parameters.Unbound
build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

class cypher_dsl.SortItem(expression: cypher_dsl.expressions.base.Expression, direction: SortOrder)

Bases: cypher_dsl.ast.AstNode

An ordering item: an expression and an explicit direction.

expression: cypher_dsl.expressions.base.Expression
direction: SortOrder
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the sort expression.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope
class cypher_dsl.SortOrder

Bases: enum.Enum

Direction attached to an ordering item.

ASCENDING = 'ASC'
DESCENDING = 'DESC'
class cypher_dsl.SymbolicName

A Cypher name used for variables, parameters, aliases and property keys.

value: str
class cypher_dsl.Variable(symbol: cypher_dsl.expressions.base.SymbolicName)

Bases: cypher_dsl.expressions.base.Expression

A reference to a name bound elsewhere in the statement.

symbol: cypher_dsl.expressions.base.SymbolicName
build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this expression under the given scope.

cypher_dsl.asc(expression: cypher_dsl.expressions.base.ExpressionInput) → SortItem

Order an expression ascending.

Example

>>> from cypher_dsl import Configuration, Renderer, asc, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).returning(person["display_name"]).order_by(asc(person["rating"]))
>>> Renderer.get(Configuration(server_version="5.26")).render(statement).cypher
'MATCH (p:Person) RETURN p.display_name ORDER BY p.rating ASC'
cypher_dsl.desc(expression: cypher_dsl.expressions.base.ExpressionInput) → SortItem

Order an expression descending.

Example

>>> from cypher_dsl import Configuration, Renderer, desc, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).returning(person["display_name"]).order_by(desc(person["rating"]))
>>> Renderer.get(Configuration(server_version="5.26")).render(statement).cypher
'MATCH (p:Person) RETURN p.display_name ORDER BY p.rating DESC'
cypher_dsl.lit(value: cypher_dsl.expressions.base.LiteralInput) → Literal

Build a literal expression from a Python value.

The value is snapshotted at construction, so changing the caller’s container later does not change the text. bytes and a value outside LiteralInput are rejected with InvalidLiteralError; bind a value the library cannot render with param.

Example

>>> from cypher_dsl import Configuration, lit, returning
>>> returning(lit("p")).build().render(Configuration(server_version="5.26")).cypher
"RETURN 'p'"
cypher_dsl.name(variable_name: str) → Variable

Build a variable reference from its name.

Where the scope’s names are known, the build checks this reference: name("p") works only where p is visible. An unmasked name resolves in a scope whose names are unknown. A bare string in a projection is already a variable name, so use this where an expression is required.

Example

>>> from cypher_dsl import Configuration, Renderer, match, name, node
>>> person = node("Person", name="p")
>>> statement = match(person).returning(name("p")["display_name"])
>>> Renderer.get(Configuration(server_version="5.26")).render(statement).cypher
'MATCH (p:Person) RETURN p.display_name'
cypher_dsl.param(parameter_name: str, value: object = UNBOUND) → Parameter

Build a parameter occurrence with an optional binding.

param(name) leaves the value to the execution layer and reports the name under unbound_parameters. param(name, value) binds it when the parameter is built: the value goes into the statement’s parameter dictionary, not into the text. A binding is frozen at construction; an object the library cannot copy is kept by identity and is never read or rendered.

Two different bindings for one name in one statement raise ConflictingParameterError when the statement is built.

Example

>>> from cypher_dsl import Configuration, Renderer, match, node, param
>>> person = node("Person", name="p")
>>> statement = match(person).where(person["email"] == param("email")).returning(person)
>>> rendered = Renderer.get(Configuration(server_version="5.26")).render(statement)
>>> sorted(rendered.unbound_parameters)
['email']
class cypher_dsl.CypherFragment

One layout fragment; rendering applies the target and the chosen layout.

A fragment carries break opportunities rather than finished text. render turns it into a string, in one line by default or with the fit-first multi-line layout when pretty is set.

render(pretty: bool = False, always_escape_names: bool = False) → str

Render the fragment as flat text, or as pretty text when it overflows.

Parameters:
  • pretty – Allow the fit-first multi-line layout. A fragment that fits the 120-column width still renders on one line.

  • always_escape_names – Backtick every identifier, not only the ones that need it.

Returns:

The query text for this fragment.

class cypher_dsl.CypherWriter(state: cypher_dsl.parameters.WalkState | None = None, write_context: WriteContext | None = None, reads: set[str] | None = None, collects: bool = True)

Accumulate fragments for one node and share the walk state with child writers.

A node receives a writer, appends its text and child fragments, and returns the scope it leaves. child shares the parameter collector, the write context and the read frame, while expression shares the parameter collector and the read frame but not the write context, because an expression cannot write a graph pattern. isolated starts a new read frame for a lexical child, so names read inside it do not join the enclosing clause. finish returns the accumulated fragment for the parent to append.

state
write_context = None
child(write_context: WriteContext | None = None) → CypherWriter

Return a writer for a nested fragment, sharing the walk state and the write context.

expression() → CypherWriter

Return a writer for an expression child, sharing the walk state but not the write context.

isolated() → CypherWriter

Return a writer for a lexical child frame, whose reads do not join this frame.

read(scope: cypher_dsl.scope.Scope, name: str) → None

Resolve a name this clause reads directly and record it as a local contribution.

property reads: frozenset[str]

Return the names this frame read directly.

append(fragment: CypherFragment) → None

Append one fragment.

text(text: str) → None

Append plain query text.

finish() → CypherFragment

Return the fragment accumulated so far.

cypher_dsl.UNBOUND: Final
cypher_dsl.FrozenValue: TypeAlias = FrozenScalar | _FrozenList | _FrozenMap | _OpaqueValue
class cypher_dsl.ParameterCollector

Collect the parameter occurrences of one build.

A parameter is one $name occurrence. param(“p”, value) attaches a binding when the parameter is built, and param(“p”) leaves it unbound for the execution layer. Every occurrence of one name shares one binding: a bound occurrence fills in an unbound one, and two different bound values raise ConflictingParameterError.

The collector is mutable and lives for the build. snapshot copies its state into a BindingSnapshot for the finished statement.

record(parameter_name: str, binding: FrozenValue | Unbound) → None

Record one occurrence, rejecting a different bound value for the same name.

An unbound occurrence is recorded only when the name has no bound value yet. A bound occurrence stores the value and clears any unbound mark for the name.

property parameters: dict[str, object]

Return a fresh dictionary of thawed bound values.

property unbound_parameters: frozenset[str]

Return the names no occurrence in this build bound.

snapshot() → BindingSnapshot

Return an immutable copy of the current bound and unbound names.

class cypher_dsl.Requirement

One syntax requirement stated by a node during its build.

minimum_version is a release tuple such as (2026, 7). language pins a Cypher language when the syntax needs one. Statement.requirements exposes the collected values; Renderer checks them against the configuration.

capability: str
minimum_version: tuple[int, ...]
language: str | None = None
cypher_dsl.Unbound: TypeAlias = _Unbound
class cypher_dsl.WalkState

The mutable state of one build walk, shared by every writer in it.

It is not the statement Builder. It holds the parameter collector and the capability requirements recorded by nodes during the walk, so a node records either without adding a parameter to every build_cypher signature. CypherWriter creates one when none is supplied.

parameters
require(capability: str, minimum_version: tuple[int, ...], language: str | None = None) → None

Record a capability, keeping the highest minimum for one capability and language.

property requirements: tuple[Requirement, ...]

Return the recorded requirements in first-seen order.

cypher_dsl.freeze_value(value: object, allow_opaque: bool = False) → FrozenValue

Snapshot a Python value into the frozen representation used by syntax.

Accepted scalar values are retained as they are. String-keyed mappings and sequences are snapshotted recursively. A cyclic container, a non-string mapping key and a non-finite float are rejected with InvalidLiteralError. bytes freezes but has no literal text, so rendering it raises. With allow_opaque an unsupported object is kept by identity instead of being copied, which is what param does.

Example

>>> from cypher_dsl import freeze_value, thaw_value
>>> values = [1, 2]
>>> frozen = freeze_value(values)
>>> values.append(3)
>>> thaw_value(frozen)
[1, 2]
cypher_dsl.thaw_value(value: FrozenValue) → object

Return an independent Python value for a frozen value.

Lists and maps are rebuilt, so changing the result does not reach the syntax tree. A value kept by identity is returned as the same object.

Example

>>> from cypher_dsl import freeze_value, thaw_value
>>> frozen = freeze_value({"tags": ["alpha"]})
>>> thawed = thaw_value(frozen)
>>> thawed["tags"].append("beta")
>>> thaw_value(frozen)
{'tags': ['alpha']}
class cypher_dsl.GraphPattern(patterns: tuple[cypher_dsl.patterns.nodes.PatternElement, ...])

Bases: cypher_dsl.ast.AstNode

The whole comma-separated pattern list of one matching clause.

patterns: tuple[cypher_dsl.patterns.nodes.PatternElement, ...]
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the patterns in order.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope
class cypher_dsl.NodePattern(label_expression: cypher_dsl.expressions.labels.LabelExpression | None, variable: cypher_dsl.expressions.values.SymbolicName | None = None, properties: cypher_dsl.patterns.properties.PatternPropertySlot | None = None, predicate: cypher_dsl.expressions.base.ConditionInput | None = None)

Bases: PatternElement, cypher_dsl.expressions.base.NamedExpression

A node pattern with an optional label expression, variable, property map and predicate.

An absent label expression writes no colon, so (p) and () are both node patterns. The inline predicate renders after the label and property map, inside the parentheses, and is applied while the pattern matches. with_predicate adds one to an existing pattern. as_expression returns the variable and rejects an anonymous pattern, because there is no name to reference. In a write clause the pattern renders a bare reference when its name is already visible or earlier in the same graph pattern, and a declaration with its labels and properties otherwise.

label_expression: cypher_dsl.expressions.labels.LabelExpression | None
variable: cypher_dsl.expressions.values.SymbolicName | None
properties: cypher_dsl.patterns.properties.PatternPropertySlot | None
predicate: cypher_dsl.expressions.operators.Condition | None
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the label expression, the properties and the predicate, in render order.

declared_names() → tuple[str, ...]

Return the names this element declares, in syntax order.

as_expression() → cypher_dsl.expressions.values.Variable

Return the reference, rejecting a node that binds no name.

with_labels(*labels: str | cypher_dsl.expressions.labels.DynamicLabel) → NodePattern

Return a copy with the given labels appended as a colon list.

with_predicate(condition: cypher_dsl.expressions.base.ConditionInput) → NodePattern

Return a copy that also requires the given inline predicate.

The predicate renders inside the parentheses, after the label and property map. A second call joins the two predicates with AND.

single_bindings() → tuple[str, ...]

Return the node’s variable name, or nothing when it is anonymous.

minimum_elements() → int

Return one, because a node pattern matches exactly one node.

relationship_to(target: NodePattern, relationship_type: str | cypher_dsl.expressions.labels.LabelExpression | None = None, name: str | None = None, properties: collections.abc.Mapping[str, cypher_dsl.expressions.base.ExpressionInput] | cypher_dsl.patterns.properties.PatternPropertySlot | None = None, quantifier: cypher_dsl.patterns.quantified.Quantifier | None = None, predicate: cypher_dsl.expressions.base.ConditionInput | None = None) → cypher_dsl.patterns.relationships.RelationshipPattern

Start a chain with an outgoing relationship to target, optionally filtered by predicate.

relationship_from(target: NodePattern, relationship_type: str | cypher_dsl.expressions.labels.LabelExpression | None = None, name: str | None = None, properties: collections.abc.Mapping[str, cypher_dsl.expressions.base.ExpressionInput] | cypher_dsl.patterns.properties.PatternPropertySlot | None = None, quantifier: cypher_dsl.patterns.quantified.Quantifier | None = None, predicate: cypher_dsl.expressions.base.ConditionInput | None = None) → cypher_dsl.patterns.relationships.RelationshipPattern

Start a chain with an incoming relationship from target, optionally filtered by predicate.

relationship_with(target: NodePattern, relationship_type: str | cypher_dsl.expressions.labels.LabelExpression | None = None, name: str | None = None, properties: collections.abc.Mapping[str, cypher_dsl.expressions.base.ExpressionInput] | cypher_dsl.patterns.properties.PatternPropertySlot | None = None, quantifier: cypher_dsl.patterns.quantified.Quantifier | None = None, predicate: cypher_dsl.expressions.base.ConditionInput | None = None) → cypher_dsl.patterns.relationships.RelationshipPattern

Start a chain with an undirected relationship to target, optionally filtered by predicate.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this element under the given scope.

class cypher_dsl.PatternElement

Bases: cypher_dsl.ast.AstNode

Base for an element that can stand in a graph pattern.

declared_names() → tuple[str, ...]

Return the names this element declares, in syntax order.

abstractmethod build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this element under the given scope.

cypher_dsl.node(primary_label: str | cypher_dsl.expressions.labels.LabelExpression | None = None, name: str | None = None, properties: collections.abc.Mapping[str, cypher_dsl.expressions.base.ExpressionInput] | cypher_dsl.patterns.properties.PatternPropertySlot | None = None, predicate: cypher_dsl.expressions.base.ConditionInput | None = None) → NodePattern

Build a node pattern with an optional primary label and optional properties.

primary_label is a label name or a label expression. Leave it out to write an unlabelled node, which is the form () or (p). name is the variable other code uses, and the map is snapshotted at construction.

predicate is an inline filter applied while the pattern matches. It renders after the label and the property map inside the parentheses. A write clause refuses it.

In a write clause, a name that the preceding clauses bound, or that an earlier part of the same pattern wrote, renders as a bare reference. Every other occurrence renders its labels and property map. Property agreement is Neo4j’s check.

Example

>>> from cypher_dsl import Configuration, match, node
>>> person = node("Person", name="p", properties={"email": "ada@example.com"})
>>> statement = match(person).returning(person).build()
>>> statement.render(Configuration(server_version="5.26")).cypher
"MATCH (p:Person {email: 'ada@example.com'}) RETURN p"
class cypher_dsl.PathPhrase(segments: tuple[PathSegment, ...], variable: cypher_dsl.expressions.values.Variable | None = None, selector: cypher_dsl.patterns.selectors.PathSelector | None = None)

Bases: cypher_dsl.patterns.nodes.PatternElement

One path pattern made of simple and quantified segments, with an optional name and selector.

Two simple segments cannot sit next to each other. At least one segment must match an element, so a zero-lower-bound quantified segment needs a neighbour that always matches. The path name must be fresh, and a selector other than ALL must be the only pattern of its MATCH clause.

segments: tuple[PathSegment, ...]
variable: cypher_dsl.expressions.values.Variable | None
selector: cypher_dsl.patterns.selectors.PathSelector | None
single_bindings() → tuple[str, ...]

Return every name bound to a single node or relationship.

group_bindings() → tuple[str, ...]

Return every name bound to a list of nodes or relationships.

path_bindings() → tuple[str, ...]

Return the path’s name when the phrase binds one.

minimum_elements() → int

Return the sum of the segments’ minimum element counts.

declared_names() → tuple[str, ...]

Return the names this element declares, in syntax order.

property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the path name, the selector and the segments, in render order.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this element under the given scope.

cypher_dsl.PathSegment: TypeAlias = NodePattern | RelationshipPattern | QuantifiedPathPattern
cypher_dsl.path_phrase(*segments: PathSegment, variable: cypher_dsl.expressions.values.Variable | None = None, selector: cypher_dsl.patterns.selectors.PathSelector | None = None) → PathPhrase

Concatenate simple and quantified path patterns into one path pattern.

variable is a name() value, which a later clause reads as the whole path. selector chooses which matches the MATCH returns. A single segment is a path pattern too, so naming a plain chain uses the same call.

Example

>>> from cypher_dsl import Configuration, match, name, node, path_phrase
>>> acted = node("Person", name="a").relationship_to(node("Movie"), "ACTED_IN")
>>> route = name("route")
>>> statement = match(path_phrase(acted, variable=route)).returning(route).build()
>>> statement.render(Configuration(server_version="5.26")).cypher
'MATCH route = (a:Person)-[:ACTED_IN]->(:Movie) RETURN route'
class cypher_dsl.PatternProperties(entries: tuple[tuple[cypher_dsl.expressions.values.SymbolicName, cypher_dsl.expressions.base.Expression], ...])

Bases: cypher_dsl.ast.AstNode

An explicit property map with source order and expression values.

entries: tuple[tuple[cypher_dsl.expressions.values.SymbolicName, cypher_dsl.expressions.base.Expression], ...]
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the value expressions in entry order.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope
classmethod from_mapping(items: collections.abc.Mapping[str, cypher_dsl.expressions.base.ExpressionInput]) → PatternProperties

Snapshot a caller’s mapping into typed entries.

class cypher_dsl.QuantifiedPathPattern(pattern: cypher_dsl.patterns.relationships.RelationshipPattern, quantifier: Quantifier, where: cypher_dsl.expressions.operators.Condition | None = None)

Bases: cypher_dsl.patterns.nodes.PatternElement

A relationship chain repeated within a quantifier and an optional inline predicate.

Every name inside the chain becomes a group variable outside the parentheses, so each inner name must be fresh and unique. A quantified path pattern cannot nest a quantified relationship. CREATE and MERGE reject the construct.

Example

>>> from cypher_dsl import Configuration, Quantifier, match, node, name
>>> source = node("Station", name="s")
>>> target = node("Station", name="t")
>>> route = source.relationship_to(target, "LINK").quantified(Quantifier.between(1, 3))
>>> match(route).returning(name("s"), name("t")).build().render(Configuration(server_version="5.26")).cypher
'MATCH ((s:Station)-[:LINK]->(t:Station)){1,3} RETURN s, t'
pattern: cypher_dsl.patterns.relationships.RelationshipPattern
quantifier: Quantifier
where: cypher_dsl.expressions.operators.Condition | None
minimum_elements() → int

Return the quantifier’s lower bound.

declared_names() → tuple[str, ...]

Return the names this element declares, in syntax order.

property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the inner chain, the inline predicate and the quantifier, in render order.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this element under the given scope.

class cypher_dsl.Quantifier(lower: int, upper: int | None, _form: _Form | None = None)

Bases: cypher_dsl.ast.AstNode

The repetition range of a quantified relationship or path pattern.

Every bound is a non-negative integer that fits a Cypher integer. A finite upper bound must be positive, so at_most(0) is rejected while zero_or_more() writes the open zero range. The factory that built the value decides its spelling, and source_text returns that spelling.

Example

>>> from cypher_dsl import Quantifier
>>> Quantifier.between(2, 2).source_text()
'{2,2}'
>>> Quantifier(2, 2).source_text()
'{2}'
lower: int
upper: int | None
classmethod exactly(count: int) → Quantifier

Return the {count} quantifier.

classmethod between(lower: int, upper: int) → Quantifier

Return the {lower,upper} quantifier, keeping the closed-range spelling at equal bounds.

classmethod at_least(lower: int) → Quantifier

Return a quantifier with no upper bound.

classmethod at_most(upper: int) → Quantifier

Return a quantifier with a lower bound of zero and an upper bound.

classmethod zero_or_more() → Quantifier

Return the * quantifier.

classmethod one_or_more() → Quantifier

Return the + quantifier.

source_text() → str

Return the quantifier in the spelling its factory chose, or the canonical form from its bounds.

class cypher_dsl.Relationship(left: cypher_dsl.patterns.nodes.NodePattern, right: cypher_dsl.patterns.nodes.NodePattern, direction: RelationshipDirection, type_expression: cypher_dsl.expressions.labels.LabelExpression | None = None, variable: cypher_dsl.expressions.values.SymbolicName | None = None, properties: cypher_dsl.patterns.properties.PatternPropertySlot | None = None, quantifier: cypher_dsl.patterns.quantified.Quantifier | None = None, predicate: cypher_dsl.expressions.base.ConditionInput | None = None)

Bases: cypher_dsl.ast.AstNode

One relationship between two node patterns.

Renders the arrow and the right node; the left node is written by the chain that owns this relationship. The type, variable, property map and inline predicate render between the brackets, with the predicate after the property map. A quantifier renders after the arrow, outside the brackets, so a predicate repeats with its relationship.

left: cypher_dsl.patterns.nodes.NodePattern
right: cypher_dsl.patterns.nodes.NodePattern
direction: RelationshipDirection
type_expression: cypher_dsl.expressions.labels.LabelExpression | None
variable: cypher_dsl.expressions.values.SymbolicName | None
properties: cypher_dsl.patterns.properties.PatternPropertySlot | None
predicate: cypher_dsl.expressions.operators.Condition | None
quantifier: cypher_dsl.patterns.quantified.Quantifier | None
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the type expression, properties, predicate, quantifier and reached node, in render order.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope
class cypher_dsl.RelationshipDirection

Bases: enum.Enum

Direction of a relationship, read from the pattern’s left node.

OUTGOING = 'outgoing'
INCOMING = 'incoming'
UNDIRECTED = 'undirected'
class cypher_dsl.RelationshipPattern(relationships: tuple[Relationship, ...])

Bases: cypher_dsl.patterns.nodes.PatternElement, cypher_dsl.expressions.base.NamedExpression

A chain of one or more relationships, each starting where the previous one ended.

Adjacent relationships must meet at the same node object, so build a chain by extending its endpoint. as_expression returns the last relationship’s variable and rejects an anonymous chain. with_predicate adds an inline predicate to the last relationship. A quantified relationship in the chain binds a list, not a single relationship.

relationships: tuple[Relationship, ...]
property start: cypher_dsl.patterns.nodes.NodePattern

Return the node the chain starts from.

property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the start node once, then each relationship in the chain.

property endpoint: cypher_dsl.patterns.nodes.NodePattern

Return the node the chain currently reaches.

property direction: RelationshipDirection

Return the direction of the last relationship.

nodes() → tuple[cypher_dsl.patterns.nodes.NodePattern, ...]

Return every node in the chain, start first and then each reached node.

single_bindings() → tuple[str, ...]

Return the node names and the names of unquantified relationships.

group_bindings() → tuple[str, ...]

Return the names of the quantified relationships in the chain.

minimum_elements() → int

Return one, because a chain matches at least one relationship.

declared_names() → tuple[str, ...]

Return the names this element declares, in syntax order.

as_expression() → cypher_dsl.expressions.base.Expression

Return the variable that represents the chain’s last relationship.

relationship_to(target: cypher_dsl.patterns.nodes.NodePattern, relationship_type: str | cypher_dsl.expressions.labels.LabelExpression | None = None, name: str | None = None, properties: collections.abc.Mapping[str, cypher_dsl.expressions.base.ExpressionInput] | cypher_dsl.patterns.properties.PatternPropertySlot | None = None, quantifier: cypher_dsl.patterns.quantified.Quantifier | None = None, predicate: cypher_dsl.expressions.base.ConditionInput | None = None) → RelationshipPattern

Extend the chain with an outgoing relationship from its current endpoint.

relationship_from(target: cypher_dsl.patterns.nodes.NodePattern, relationship_type: str | cypher_dsl.expressions.labels.LabelExpression | None = None, name: str | None = None, properties: collections.abc.Mapping[str, cypher_dsl.expressions.base.ExpressionInput] | cypher_dsl.patterns.properties.PatternPropertySlot | None = None, quantifier: cypher_dsl.patterns.quantified.Quantifier | None = None, predicate: cypher_dsl.expressions.base.ConditionInput | None = None) → RelationshipPattern

Extend the chain with an incoming relationship from target.

relationship_with(target: cypher_dsl.patterns.nodes.NodePattern, relationship_type: str | cypher_dsl.expressions.labels.LabelExpression | None = None, name: str | None = None, properties: collections.abc.Mapping[str, cypher_dsl.expressions.base.ExpressionInput] | cypher_dsl.patterns.properties.PatternPropertySlot | None = None, quantifier: cypher_dsl.patterns.quantified.Quantifier | None = None, predicate: cypher_dsl.expressions.base.ConditionInput | None = None) → RelationshipPattern

Extend the chain with an undirected relationship to target.

with_predicate(condition: cypher_dsl.expressions.base.ConditionInput) → RelationshipPattern

Return a copy whose last relationship also requires the given inline predicate.

The predicate renders inside that relationship’s brackets, after its type and property map. A second call joins the two predicates with AND.

quantified(quantifier: cypher_dsl.patterns.quantified.Quantifier, where: cypher_dsl.expressions.operators.Condition | None = None) → cypher_dsl.patterns.quantified.QuantifiedPathPattern

Wrap the chain in a quantified path pattern.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this element under the given scope.

cypher_dsl.relationship_pattern(source: cypher_dsl.patterns.nodes.NodePattern, target: cypher_dsl.patterns.nodes.NodePattern, direction: RelationshipDirection, relationship_type: str | cypher_dsl.expressions.labels.LabelExpression | None = None, name: str | None = None, properties: collections.abc.Mapping[str, cypher_dsl.expressions.base.ExpressionInput] | cypher_dsl.patterns.properties.PatternPropertySlot | None = None, quantifier: cypher_dsl.patterns.quantified.Quantifier | None = None, predicate: cypher_dsl.expressions.base.ConditionInput | None = None) → RelationshipPattern

Build a single-relationship pattern between two node patterns.

The function form of the relationship_to, relationship_from and relationship_with methods. direction decides the arrow, which those methods fix for you, so this factory suits a direction that is data. relationship_type, name, properties, quantifier and predicate mean the same as on those methods.

Example

>>> from cypher_dsl import Configuration, RelationshipDirection, match, name, node, relationship_pattern
>>> acted_in = relationship_pattern(
...     node("Person", name="p"),
...     node("Movie", name="m"),
...     RelationshipDirection.OUTGOING,
...     "ACTED_IN",
...     name="r",
... )
>>> match(acted_in).returning(name("p")).build().render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person)-[r:ACTED_IN]->(m:Movie) RETURN p'
class cypher_dsl.PathSelector(count: SelectorCount | None, shortest: bool = False, groups: bool = False, _all_shortest: bool = False)

Bases: cypher_dsl.ast.AstNode

The selection a path pattern returns, as a count, a shortest flag and a group flag.

count is a positive integer literal that fits a Cypher integer, or a Parameter built with param(). A parameter renders as $name and requires Neo4j 2025.06 or later with Cypher 25. None selects every path and pairs with neither flag.

count: SelectorCount | None
shortest: bool
groups: bool
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the parameter when the count is not a literal.

source_text() → str

Return the selector in its default spelling, without a target configuration.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Render the selector, requiring Cypher 25 from Neo4j 2025.06 for a parameter count.

cypher_dsl.all_paths() → PathSelector

Return the ALL selector.

Every path the pattern matches is returned, with no limit on the number and no shortest-length preference. Unlike the other selectors, ALL may share its MATCH with other patterns.

Example

>>> from cypher_dsl import Configuration, Quantifier, all_paths, match, name, node, path_phrase
>>> knows = node("Person", name="a").relationship_to(
...     node("Person"), "KNOWS", quantifier=Quantifier.one_or_more()
... )
>>> watched = node(name="a").relationship_to(node("Movie"), "WATCHED")
>>> statement = match(
...     path_phrase(knows, variable=name("p"), selector=all_paths()), watched
... ).returning(name("p")).build()
>>> statement.render(Configuration(server_version="5.26")).cypher
'MATCH p = ALL (a:Person)-[:KNOWS]->+(:Person), (a)-[:WATCHED]->(:Movie) RETURN p'
cypher_dsl.all_shortest() → PathSelector

Return the ALL SHORTEST selector.

Every path tied for the shortest length is returned for each distinct pair of start and end nodes. This is the same selection as shortest(1, groups=True).

Example

>>> from cypher_dsl import Configuration, Quantifier, all_shortest, match, name, node, path_phrase
>>> knows = node("Person", name="a").relationship_to(
...     node("Person"), "KNOWS", quantifier=Quantifier.one_or_more()
... )
>>> statement = match(
...     path_phrase(knows, variable=name("p"), selector=all_shortest())
... ).returning(name("p")).build()
>>> statement.render(Configuration(server_version="5.26")).cypher
'MATCH p = ALL SHORTEST (a:Person)-[:KNOWS]->+(:Person) RETURN p'
cypher_dsl.any_paths(count: SelectorCount = 1) → PathSelector

Return the ANY count selector.

count defaults to one. It is a positive integer literal that fits a Cypher integer or a param() value. A literal renders inline. A parameter renders as $name and requires Neo4j 2025.06 or later with Cypher 25. ANY count returns up to count matching paths for each distinct pair of start and end nodes. It states reachability: the query asks whether a path exists, not that the selected paths are the shortest.

Example

>>> from cypher_dsl import Configuration, Quantifier, any_paths, match, name, node, path_phrase
>>> knows = node("Person", name="a").relationship_to(
...     node("Person"), "KNOWS", quantifier=Quantifier.one_or_more()
... )
>>> statement = match(
...     path_phrase(knows, variable=name("p"), selector=any_paths(3))
... ).returning(name("p")).build()
>>> statement.render(Configuration(server_version="5.26")).cypher
'MATCH p = ANY 3 (a:Person)-[:KNOWS]->+(:Person) RETURN p'
cypher_dsl.shortest(count: SelectorCount, groups: bool = False) → PathSelector

Return the SHORTEST count selector, or SHORTEST count GROUPS when groups is set.

count is a positive integer literal that fits a Cypher integer or a param() value. A literal renders inline. A parameter renders as $name and requires Neo4j 2025.06 or later with Cypher 25. Without groups the selector takes up to count paths in order of length, for each distinct pair of start and end nodes. With groups it takes every path in the count shortest distinct length groups, again for each pair.

Example

>>> from cypher_dsl import Configuration, Quantifier, match, name, node, path_phrase, shortest
>>> knows = node("Person", name="a").relationship_to(
...     node("Person"), "KNOWS", quantifier=Quantifier.one_or_more()
... )
>>> statement = match(
...     path_phrase(knows, variable=name("p"), selector=shortest(2))
... ).returning(name("p")).build()
>>> statement.render(Configuration(server_version="5.26")).cypher
'MATCH p = SHORTEST 2 (a:Person)-[:KNOWS]->+(:Person) RETURN p'
class cypher_dsl.Renderer(configuration: cypher_dsl.statement.Configuration)

A stateless facade over one immutable configuration.

Build one with Renderer.get and reuse it. render accepts a Builder, a CompiledQuery or a UnionDraft, and finalises a builder or draft on the way in.

Example

>>> from cypher_dsl import Configuration, Renderer, match, node, param
>>> person = node("Person", name="p")
>>> statement = match(person).where(person["rating"] > param("min_rating")).returning(person)
>>> rendered = Renderer.get(Configuration(server_version="5.26")).render(statement)
>>> (rendered.cypher, rendered.unbound_parameters)
('MATCH (p:Person) WHERE p.rating > $min_rating RETURN p', frozenset({'min_rating'}))
classmethod get(configuration: cypher_dsl.statement.Configuration) → Renderer

Return a renderer for a configuration.

The configuration is validated when it is built, so this call only wraps it.

render(query: RenderInput) → cypher_dsl.statement.Rendered

Render a builder, a draft or a compiled query.

A builder or a draft is finalised here, so a body that needs an enclosing binding unavailable at its own root fails at this call. A compiled query is rendered by walking its clauses once more under the root scope. Each call returns a Rendered with a fresh parameter dictionary. A requirement the configuration does not meet raises UnsupportedFeatureError before any text is produced.

cypher_dsl.RenderInput: TypeAlias = Builder | CompiledQuery | UnionDraft
class cypher_dsl.Scope

The names a clause may read at one point in the build.

A scope is a value, not a mutable environment. Each node receives the scope for its position and returns the scope the next node reads. A position is one point in that order: before the first clause, between two clauses, or inside a nested body. A name is bound at a position when the scope there lists it.

A clause returns the names it received plus the names it introduces. Only a projection boundary removes names: closed is that boundary, and WITH calls it. A nested body starts from its imports or correlated names, never from the enclosing scope.

Scope.root() is the empty scope a standalone statement starts from. resolve is the only read check.

The fields partition the names by why they are or are not readable:

  • names: readable here, in first-declaration order.

  • masked: present in the statement, but rejected here.

  • reserved: imported names a nested body must not declare again.

  • carried: readable only by the filter attached to a WITH.

  • outer: fixed by an enclosing query; survives an inner projection.

  • unknown: the output names are not known, so any name resolves.

  • read_only_outer: fixed names this query part may read but does not contribute, so a wildcard does not project them.

Example

>>> from cypher_dsl.scope import Scope
>>> Scope.root().with_bound(("p",)).resolve("p")
>>> Scope.root().resolve("p")
Traceback (most recent call last):
...
cypher_dsl.errors.DslError: Name 'p' is not bound at this position.
names: tuple[str, ...] = ()
masked: frozenset[str]
reserved: frozenset[str]
carried: frozenset[str]
outer: frozenset[str]
unknown: bool = False
read_only_outer: frozenset[str]
classmethod root() → Scope

Return the scope before the first clause of a standalone statement.

resolve(name: str) → None

Reject a name this scope does not make readable.

with_bound(names: collections.abc.Iterable[str]) → Scope

Return this scope with the names added to names, keeping first-declaration order.

A name this query part binds is no longer only readable through an enclosing binding.

declare(names: collections.abc.Iterable[str]) → Scope

Bind names introduced by one pattern or YIELD list before its own elements are built.

A masked name cannot be declared, and a reserved name that is not already bound cannot be declared either, because that would turn an import into a new binding.

closed(names: collections.abc.Iterable[str]) → Scope

Return the scope after a projection, keeping its names and the fixed outer bindings.

The projected names come first. An outer name that was not projected stays visible, because it belongs to the enclosing query rather than to this projection. Every other name is dropped.

exported(names: collections.abc.Iterable[str]) → Scope

Return the scope a terminal projection leaves: exactly the columns it projects.

No clause follows a terminal projection in its query part, so the scope owes no enclosing binding and keeps no reserved name. An import the projection did not project is not a column.

with_local(names: collections.abc.Iterable[str]) → Scope

Return this scope with the names the current query part contributes.

A direct read of a fixed name brings it into the query part, so a wildcard projects it again. A name this query part already binds is unaffected.

correlated() → Scope

Return a scope for a nested body where every visible name is also a fixed outer binding.

with_carried(names: collections.abc.Iterable[str]) → Scope

Expose names beside the projected ones for the filter attached to a WITH.

The names are readable only by that filter. They are not part of the scope the next clause reads.

with_masked(names: collections.abc.Iterable[str]) → Scope

Reject the given names here, even if an enclosing scope still binds them.

with_locals(names: collections.abc.Iterable[str]) → Scope

Bind names for one nested expression, taking over any mask they had.

visible() → tuple[str, ...]

Return the names this scope currently exposes.

class cypher_dsl.CompiledQuery

A finalised query with the metadata its build produced.

A Statement or a UnionStatement is a CompiledQuery. Its requirements and parameter views are fixed at finalisation. The text is built from the clauses by each render.

abstractmethod build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write this query’s clauses through writer and return the final scope.

abstract property requirements: tuple[cypher_dsl.parameters.Requirement, ...]

Return the syntax requirements stated during the build.

abstract property parameters: dict[str, object]

Return a fresh dictionary of bound parameter values.

abstract property unbound_parameters: frozenset[str]

Return the parameter names this query leaves unbound.

render(configuration: Configuration) → Rendered

Render this query under one configuration.

The result carries the rendered text with its bound parameter values and the names still unbound. The configuration is applied here, so one query can render at several declared releases. A requirement the configuration does not meet raises UnsupportedFeatureError before any text is produced.

class cypher_dsl.Configuration

Settings that select the target, language and quoting for one or more renders.

server_version is required and names the Neo4j release the text will run on, as two or three dotted numbers. The minimum is 5.26. Constructing a configuration does not contact a server and does not verify its actual release.

Example

>>> from cypher_dsl import Configuration, Language
>>> automatic = Configuration(server_version="2026.10")
>>> pinned = Configuration(server_version="2026.10", language=Language.CYPHER_25)
>>> pinned.language
<Language.CYPHER_25: 'CYPHER_25'>
Raises:

UnsupportedFeatureError – If the release is malformed or below 5.26, or if the pinned language is unavailable on that release.

server_version: str
language: Language
always_escape_names: bool = False
pretty_print: bool = False
class cypher_dsl.Language

Bases: enum.Enum

How rendered text names, selects or omits its Cypher language.

AUTO adds a prefix only when a clause requires one. NONE never adds a prefix but still checks the declared release. CYPHER_5 and CYPHER_25 pin the prefix and reject syntax that needs the other language.

AUTO = 'AUTO'
NONE = 'NONE'
CYPHER_5 = 'CYPHER_5'
CYPHER_25 = 'CYPHER_25'
class cypher_dsl.Rendered

One render result: query text and the bindings that belong to it.

parameters is a new dictionary on each render, so changing it does not reach the statement or another result. unbound_parameters names the values the caller still has to supply. str() returns the query text.

cypher: str
parameters: dict[str, object]
unbound_parameters: frozenset[str]
class cypher_dsl.Statement(clauses: tuple[cypher_dsl.clauses.base.Clause, ...])

Bases: CompiledQuery, cypher_dsl.ast.AstNode

A finalised clause sequence with the metadata its build produced.

Construct one through Builder.build() or by passing a clause tuple. The constructor requires a complete query: at least one clause, no RETURN before the last position, a last clause that can end a statement, and every name bound where it is read.

A Statement is frozen. Its parameters property returns a new dictionary on each access.

Example

>>> from cypher_dsl import Configuration, match, node
>>> person = node("Person", name="p")
>>> statement = match(person).returning(person["name"]).build()
>>> statement.render(Configuration(server_version="5.26")).cypher
'MATCH (p:Person) RETURN p.`name`'
clauses: tuple[cypher_dsl.clauses.base.Clause, ...]
property children: tuple[cypher_dsl.ast.AstNode, ...]

Return the clauses in order.

build_cypher(scope: cypher_dsl.scope.Scope, writer: cypher_dsl.fragment.CypherWriter) → cypher_dsl.scope.Scope

Write the clauses in order and return the scope the statement leaves behind.

property requirements: tuple[cypher_dsl.parameters.Requirement, ...]

Return the syntax requirements stated during the build.

property parameters: dict[str, object]

Return a fresh dictionary of bound parameter values.

property unbound_parameters: frozenset[str]

Return the parameter names this statement leaves unbound.

class cypher_dsl.UnionDraft(parts: tuple[cypher_dsl.builder.Builder | cypher_dsl.builder.QueryDraft | cypher_dsl.statement.Statement, ...], all: bool = False)

Bases: UnionSyntax

A union that stays syntax until it is finalised as a standalone query.

Renderer.render and Builder.call accept a draft directly. Call build() when you need the completed UnionStatement rather than a render.

build() → UnionStatement

Finalise the union with one root build.

Returns:

A UnionStatement with the requirements and binding snapshot its build

produced.

Raises:

DslError – If a branch ends without RETURN, because a standalone union needs RETURN in every branch.

class cypher_dsl.UnionStatement(parts: tuple[cypher_dsl.builder.Builder | cypher_dsl.builder.QueryDraft | cypher_dsl.statement.Statement, ...], all: bool = False)

Bases: UnionSyntax, cypher_dsl.statement.CompiledQuery

A finalised union with the metadata its build produced.

property requirements: tuple[cypher_dsl.parameters.Requirement, ...]

Return the syntax requirements recorded at finalisation.

property parameters: dict[str, object]

Return a fresh dictionary of bound parameter values.

property unbound_parameters: frozenset[str]

Return the parameter names this union leaves unbound.

cypher_dsl.union(*parts: cypher_dsl.builder.Builder | cypher_dsl.builder.QueryDraft | cypher_dsl.statement.Statement, all: bool = False) → UnionDraft

Combine query branches with UNION, or UNION ALL when all is set.

The result is a UnionDraft, not a finalised query. Render it directly, pass it as a CALL body, or call build().

Example

>>> from cypher_dsl import Configuration, match, node, union
>>> people = match(node("Person", name="n")).returning(node("Person", name="n"))
>>> films = match(node("Movie", name="n")).returning(node("Movie", name="n"))
>>> union(people, films).build().render(Configuration(server_version="5.26")).cypher
'MATCH (n:Person) RETURN n UNION MATCH (n:Movie) RETURN n'

The branches must all end in RETURN or none may. The library does not compare the branches, so column agreement across them is Neo4j’s check.

Exceptions

Construction and rendering failures raised by the DSL.

Every error derives from DslError so that callers can catch the library’s own failures without catching unrelated Python exceptions. Messages name the construct that failed and, where the choice exists, the supported alternative.

exception cypher_dsl.errors.DslError

Bases: Exception

Base class for every construction and rendering failure.

exception cypher_dsl.errors.UnsupportedFeatureError

Bases: DslError

Raised when a requested construct is outside the implemented surface.

exception cypher_dsl.errors.InvalidClauseOrderError

Bases: DslError

Raised when clauses form a sequence that Cypher does not accept.

exception cypher_dsl.errors.ConflictingParameterError

Bases: DslError

Raised when one parameter name carries two different bindings.

exception cypher_dsl.errors.InvalidIdentifierError

Bases: DslError

Raised when a name cannot be rendered as a quoted identifier.

exception cypher_dsl.errors.EmptyPatternError

Bases: DslError

Raised when a grammar position requires at least one pattern or item.

exception cypher_dsl.errors.InvalidLiteralError

Bases: DslError

Raised when a Python value cannot be represented as a frozen literal.

The model subpackage

The model names are imported from cypher_dsl.model and are not part of the top-level package. The model guide explains the declarations and the rendered text they produce.

An opt-in typed model of labels, relationship types and property names.

A declaration subclasses a core pattern class and names its graph identifier once. Fields and links build the same core AST nodes as the plain builders, so the build walk, renderer and parameter handling are unchanged.

class cypher_dsl.model.NodeType(label_expression: cypher_dsl.expressions.labels.LabelExpression | None, variable: cypher_dsl.expressions.values.SymbolicName | None = None, properties: cypher_dsl.patterns.properties.PatternPropertySlot | None = None, predicate: cypher_dsl.expressions.base.ConditionInput | None = None)

Bases: cypher_dsl.patterns.nodes.NodePattern

A node pattern that declares its labels on the class.

Declare a subclass with label=, giving one name or a label expression built from names. The expression is readable as the class’s label, and named returns an instance with a variable, so a field resolves through that variable.

label
classmethod named(name: str) → Self

Return an instance of this model with name as its variable.

with_labels(*labels: str | cypher_dsl.expressions.labels.DynamicLabel) → Self

Return a copy with further labels that is still an instance of this model.

class cypher_dsl.model.RelationshipType(relationships: tuple[Relationship, ...])

Bases: cypher_dsl.patterns.relationships.RelationshipPattern

A relationship pattern that names its type on the class.

Declare a subclass with type=. A link’s to call constructs an instance, which holds the same Relationship tuple as a core relationship pattern.

cypher_dsl.model.field(value_type: object, property_name: str | None = None) → _Field[Any]

Declare a property on a model class.

value_type is declaration metadata. property_name is the name the property has in the graph and defaults to the Python attribute name. The field reads as a Property on an instance and does not inspect the attribute’s value.

Parameters:
  • value_type – The declared Python type of the property value.

  • property_name – The property name in the graph. Defaults to the attribute name.

Returns:

The field, whose property name is fixed when Python creates the declaring class.

Raises:

cypher_dsl.errors.InvalidIdentifierError – If property_name cannot be a Cypher identifier.

cypher_dsl.model.rel(relationship: type[RelT], target: type[TargetT]) → _Link[TargetT, RelT]

Declare an outgoing link to a node model.

Parameters:
  • relationship – The relationship model class the link creates.

  • target – The node model class the link accepts as its target.

Returns:

The link, which resolves to a bound relationship on an instance.

Raises:

cypher_dsl.errors.DslError – If relationship is RelationshipType itself or target is NodeType itself.