Call subqueries¶
A CALL subquery runs a query body once for every row the outer query holds at that
point, in its own scope. This library always renders the variable scope clause, so outer
variables enter the body only through it. The names the body returns become available to
the clauses after the call.
The body is written by the call, under a seed scope built from the imports. A body must
stay a builder or a union draft when standalone validation cannot resolve a name it reads.
That can happen when the body reads an import it does not declare and nothing in its own
text accounts for that name, as in the example below. A body that needs no such binding
may also be a finalised Statement or UnionStatement. The call accepts both. Only
the call knows what it imports.
from cypher_dsl import Configuration, Renderer, match, name, node
person = node("Person", name="p")
movie = node("Movie", name="m")
body = (
match(movie)
.where(movie["title"] == person["favourite"])
.returning(movie["title"].alias("title"))
)
statement = match(person).call(body, imports=("p",)).returning(name("title"))
renderer = Renderer.get(Configuration(server_version="5.26"))
print(renderer.render(statement).cypher)
MATCH (p:Person) CALL (p) { MATCH (m:Movie)
WHERE m.title = p.favourite RETURN m.title AS title } RETURN title
These statements render on one line. Pretty output does not wrap a short statement either: it keeps a group flat while it fits the remaining 120 columns.
A read pattern inside the body names an imported node with or without a label: the
occurrence renders the text it carries, so MATCH (p) and MATCH (p:Person) both
render as written, and the server decides whether a repeated label is legal. To filter the
label without restating it, add a predicate in Python with
.where(has_label(name("p"), "Person")). That renders as WHERE p:Person. See the
label-predicate rules for the release floor, which is
higher for a dynamic label in has_label() than in the pattern. A write pattern treats
an imported name as a bound reference and sends only the name, so endpoint legality is
Neo4j’s check on that rendered reference.
A body that ends in RETURN is a returning subquery: its output rows become the rows
after the call. A body that ends in a write clause is a unit subquery: it changes the
graph without changing the number of rows.
Import all, some or no variables¶
imports names the outer variables the body receives. import_all=True renders
(*) and passes every outer variable in. An omitted imports renders () and
passes nothing, so the body is independent of the outer row.
from cypher_dsl import Configuration, Renderer, call, match, name, node
person = node("Person", name="p")
team = node("Team", name="t")
player = node("Player", name="pl")
body = match(player).returning(player["name"].alias("player"))
every = (
match(person, team)
.call(body, import_all=True)
.returning(name("player"))
)
none = call(body).returning(name("player"))
renderer = Renderer.get(Configuration(server_version="5.26"))
print(renderer.render(every).cypher)
print(renderer.render(none).cypher)
MATCH (p:Person), (t:Team)
CALL (*) { MATCH (pl:Player) RETURN pl.`name` AS player } RETURN player
CALL () { MATCH (pl:Player) RETURN pl.`name` AS player } RETURN player
The imports are plain variable names. Aliases are not part of the scope clause, and an import must be bound by the clauses in front of the call.
Keep rows the subquery drops¶
optional_call renders OPTIONAL CALL. When the body produces no rows for an
incoming row, that row survives with null bindings for the returned names, the same
way OPTIONAL MATCH keeps a row without a match.
from cypher_dsl import Configuration, Renderer, match, name, node
person = node("Person", name="p")
movie = node("Movie", name="m")
body = (
match(movie)
.where(movie["title"] == person["favourite"])
.returning(movie["title"].alias("title"))
)
statement = (
match(person)
.optional_call(body, imports=("p",))
.returning(name("title"))
)
renderer = Renderer.get(Configuration(server_version="5.26"))
print(renderer.render(statement).cypher)
MATCH (p:Person) OPTIONAL CALL (p) { MATCH (m:Movie)
WHERE m.title = p.favourite RETURN m.title AS title } RETURN title
Write in batches¶
InTransactions is the transaction modifier of a CALL subquery. Pass it as
in_transactions to call(), optional_call() or the builder method of the same
name. An omitted modifier, or None, renders no transaction suffix.
InTransactions()appendsIN TRANSACTIONS.InTransactions(rows=...)appendsOF ... ROWSto set the input rows per transaction.InTransactions(concurrency=...)appends the concurrent form.TruewritesCONCURRENTwithout a count, and a count expression writes its count before it.InTransactions(rows=100, concurrency=4)combines both.
The operands are expressions, so a literal, a parameter or a computed expression is
accepted. The library builds each one under the lexical scope at the call, so an
expression that reads a query variable renders, and the library does not evaluate it. A
rendered statement is therefore not proof that a server accepts it: the transactions
manual linked below states the operand rules. The library records the IN TRANSACTIONS
floor of Neo4j 4.4 for the modifier, and records no separate floor for the CONCURRENT
keyword, which Neo4j 5.21 adds.
from cypher_dsl import (
Configuration,
InTransactions,
Renderer,
create,
fn,
name,
node,
unwind,
)
body = create(node("Clone", properties={"uid": name("item")}))
statement = (
unwind(fn("range", 1, 1_000), name("item"))
.call(
body,
imports=("item",),
in_transactions=InTransactions(rows=100, concurrency=4),
)
.returning(name("item"))
)
renderer = Renderer.get(Configuration(server_version="5.26"))
print(renderer.render(statement).cypher)
UNWIND range(1, 1000) AS item
CALL (item) {
CREATE (:Clone {uid: item})
} IN 4 CONCURRENT TRANSACTIONS OF 100 ROWS
RETURN item
The example writes 1,000 clones in ten transactions of 100 rows, with at most four running at once.
Set the DISJOINT BY hint¶
disjoint_by writes DISJOINT BY ... after OF ... ROWS and before ON ERROR
and REPORT STATUS. An omitted value, or None, writes no option and leaves the
database default in force. DisjointBy.NONE writes an explicit override instead. Three
forms render a hint:
A non-empty tuple of key expressions, which renders
DISJOINT BY (<key>, ...)in the order supplied.DisjointBy.AUTO, which rendersDISJOINT BY AUTO.DisjointBy.NONE, which rendersDISJOINT BY NONE.
Any other shape raises a DslError: a list, an empty tuple, a bare expression, a bare
string such as "AUTO", or a boolean. A key must be a value expression, so an alias and
the projection asterisk are refused.
The option requires concurrent batches. With concurrency left at its default or set
to the literal False, construction raises a DslError. True and a count
expression select the concurrent syntax. The count is rendered, not evaluated, so Neo4j
decides whether its value is legal. The library records Neo4j 2026.06 and Cypher 25 for
all three forms, so Language.AUTO selects the CYPHER 25 prefix and a CYPHER 5
pin is refused.
A key can refer to a variable from outside the expression only if the call imports it
through imports or import_all=True. Names introduced by the call body and the
REPORT STATUS name are not available. A variable bound within a key expression, such
as the item variable of a list comprehension, follows the expression’s own scope.
The library checks only the argument shape and lexical references, not whether a key is valid for scheduling. See the DISJOINT BY manual for Neo4j’s key rules.
from cypher_dsl import (
Configuration,
InTransactions,
Renderer,
create,
name,
node,
unwind,
)
item = name("item")
statement = (
unwind([1, 2], item)
.call(
create(node("Clone", properties={"uid": item})),
imports=("item",),
in_transactions=InTransactions(
rows=100,
concurrency=4,
disjoint_by=(item,),
),
)
.returning(item)
)
renderer = Renderer.get(
Configuration(server_version="2026.06", pretty_print=True)
)
print(renderer.render(statement).cypher)
CYPHER 25
UNWIND [1, 2] AS item
CALL (item) {
CREATE (:Clone {uid: item})
} IN 4 CONCURRENT TRANSACTIONS OF 100 ROWS
DISJOINT BY (item)
RETURN item
Set the error policy and read a status¶
on_error takes an OnError mode or a RetryOnError, and report_status
takes the name the call binds:
OnError.CONTINUE,OnError.BREAKandOnError.FAILrenderON ERROR CONTINUE,ON ERROR BREAKandON ERROR FAIL.RetryOnError()rendersON ERROR RETRY.for_secondsaddsFOR ... SECONDSandthenaddsTHEN ..., soRetryOnError(then=OnError.CONTINUE)rendersON ERROR RETRY THEN CONTINUE.report_status="name"appendsREPORT STATUS AS <name>.
ON ERROR RETRY needs Neo4j 2025.03. The library records that release floor and no
language pin, so Language.AUTO adds no prefix. The three simple modes and
REPORT STATUS add no floor.
What each policy does at run time, how a retry is scheduled, and the fields of the status value are server rules, stated in the manual linked below.
REPORT STATUS takes OnError.CONTINUE, OnError.BREAK, or a
RetryOnError whose then is one of those, and the library refuses every other
policy with a DslError. The call binds the status name after the body and the modifier, so
neither can read it, and a call that reports a status cannot end the statement: a
subsequent clause follows it. A status name that repeats an outer or returned name renders
as written, and Neo4j decides whether that is legal.
from cypher_dsl import (
Configuration,
InTransactions,
OnError,
Renderer,
RetryOnError,
call,
create,
name,
node,
param,
)
modifier = InTransactions(
rows=100,
concurrency=4,
on_error=RetryOnError(
for_seconds=param("retry_seconds", 30),
then=OnError.CONTINUE,
),
report_status="status",
)
statement = call(create(node("Clone")), in_transactions=modifier).returning(
name("status")["committed"]
)
renderer = Renderer.get(Configuration(server_version="2025.03"))
print(renderer.render(statement).cypher)
CALL () {
CREATE (:Clone)
} IN 4 CONCURRENT TRANSACTIONS OF 100 ROWS
ON ERROR RETRY FOR $retry_seconds SECONDS THEN CONTINUE
REPORT STATUS AS `status`
RETURN `status`.committed
The library renders the modifier and does not evaluate the row count, the concurrency count, the retry duration or a policy’s effect. The CALL subqueries in transactions manual states what those values mean to a server, including the implicit-transaction requirement.
Process a UNION¶
union returns a draft, and a draft is a valid call body. This is how a query keeps
processing rows after a UNION.
from cypher_dsl import Configuration, Renderer, call, match, name, node, union
person = node("Person", name="p")
movie = node("Movie", name="m")
left = match(person).returning(person["uid"].alias("uid"))
right = match(movie).returning(movie["uid"].alias("uid"))
statement = call(union(left, right)).returning(name("uid"))
renderer = Renderer.get(Configuration(server_version="5.26"))
print(renderer.render(statement).cypher)
CALL () { MATCH (p:Person) RETURN p.uid AS uid
UNION MATCH (m:Movie) RETURN m.uid AS uid } RETURN uid
What the library checks¶
An import must name a variable the clauses in front of the call bind.
Named imports and
import_allcannot be combined.A body must end in
RETURN, a write clause, or aCALLthat returns nothing and reports no status.A returning body may bind a name the outer query already holds, including a name a wildcard projects. The DSL renders it as given. The server decides whether the redeclaration is legal.
A
WITHinside the body may rebind an imported name. The DSL does not check the rebinding against the import set.A statement may end with a subquery call when the body does not return and the call reports no status. A body that ends in
RETURN, includingRETURN *, needs a clause after the call.
A unit subquery ends in a write clause or in a call that returns nothing, so it exports no
column. A returning body exports its projected columns: the explicit names and, for
RETURN *, every name the body’s query part contributes.
An import the body only reads through is not a column. A direct read in a clause makes
that import a column again, except in a WITH projection, which contributes only the
names it projects, and in a RETURN modifier, which reads the name for that modifier
alone. A computed column that states no name is not bound after the call, so a later
clause cannot refer to its implicit name.
The library rejects a returning call as the final clause, whether or not it can name the returned columns, and a call that reports a status cannot end the statement either. Neo4j still decides whether the statement as a whole is valid.
Cypher 5 requires a WITH between a write clause and a following MATCH,
UNWIND or CALL. The
WITH manual states that
Cypher 25 no longer requires it. The library tracks which columns a query part
contributes, but that is projection scope, not clause sequencing. It renders the sequence
without a WITH boundary in either language mode and leaves the sequencing rule to the
server.
Imported names stay readable after a body WITH that drops them, because the seed
records them as outer bindings. A name the body declared itself is dropped by that
WITH, as usual. A body WITH that binds an imported name to a new value renders as
written, because the import is already visible in the body. A read pattern in the body
renders the label it carries, including on an imported name. A write pattern treats the
imported name as a bound reference and sends only the name.
Test whether a subquery matches¶
exists builds an EXISTS { ... } subquery expression. Its value is a predicate, so
it filters in WHERE, projects in RETURN and combines with &, |, ^ and
~. Unlike a CALL subquery, the body reads the enclosing scope without a scope
clause, because Scope.correlated() copies the visible names into the body’s scope. The
names the body binds stay inside the expression. For a chain that only references names
the outer query already binds, path pattern expressions
are the concise form without a body.
from cypher_dsl import Configuration, Renderer, exists, match, node, param
person = node("Person", name="p")
dog = node("Dog", name="d")
walked = match(node(name="p").relationship_to(dog, "HAS_DOG")).where(
dog["name"] == param("dog_name")
)
statement = match(person).where(exists(walked)).returning(person["name"])
renderer = Renderer.get(Configuration(server_version="5.26"))
print(renderer.render(statement).cypher)
MATCH (p:Person) WHERE EXISTS { MATCH (p)-[:HAS_DOG]->(d:Dog)
WHERE d.`name` = $dog_name } RETURN p.`name`
A pattern element is accepted where the body is one pattern, and the rendered text names
the MATCH keyword. A final RETURN in the body is optional and its columns are
discarded: EXISTS tests only whether the body produces a row. A union body follows the
rule the UNION builder applies to branches.
from cypher_dsl import Configuration, Renderer, exists, match, node
person = node("Person", name="p")
keeps_dog = exists(node(name="p").relationship_to(node("Dog"), "HAS_DOG"))
statement = match(person).returning(person["name"], keeps_dog.alias("keeps_dog"))
renderer = Renderer.get(Configuration(server_version="5.26"))
print(renderer.render(statement).cypher)
MATCH (p:Person) RETURN p.`name`,
EXISTS { MATCH (p)-[:HAS_DOG]->(:Dog) } AS keeps_dog
The library applies four rules to this construct:
A body
WITHkeeps the enclosing names visible, because the nested scope records them as outer bindings. A name the body declared itself is dropped by thatWITH, as usual. Carry a body variable through theWITHwhen a later body clause needs it.The names the body binds do not become available outside the expression.
The body reads the names it binds itself and the names the enclosing query has bound. Where the library knows the enclosing clause’s names, a name it has not bound gets the usual
not in scoperejection.A body pattern that names an enclosing node renders the label it carries, including on the occurrence that restates an enclosing name. The server decides whether that restatement is legal.
The library does not reject a writing body for EXISTS. Cypher defines which bodies
each subquery expression accepts, and a CREATE inside EXISTS renders and is
rejected by the server.
Count the rows of a subquery¶
count_subquery builds a COUNT { ... } subquery expression. Its value is an
integer, so it compares in WHERE, projects in RETURN and assigns in SET.
The body is a read query that sees the enclosing scope without a scope clause, and a
final RETURN is optional: its columns are discarded, because the value is the
number of rows.
from cypher_dsl import (
Configuration,
Renderer,
count_subquery,
lit,
match,
node,
)
person = node("Person", name="p")
walked = match(node(name="p").relationship_to(node("Dog"), "HAS_DOG"))
statement = (
match(person)
.where(count_subquery(walked) > lit(1))
.returning(person["name"])
)
renderer = Renderer.get(Configuration(server_version="5.26"))
print(renderer.render(statement).cypher)
MATCH (p:Person) WHERE COUNT { MATCH (p)-[:HAS_DOG]->(:Dog) } > 1
RETURN p.`name`
A pattern element is accepted where the body is one pattern, and the rendered text
names the MATCH keyword, as exists does. The manual’s form without the keyword
is not produced.
A union body is checked for one shape rule. A UNION ALL body without RETURN is
accepted, because counting rows does not need columns. A plain UNION body needs
RETURN in every branch, because duplicate removal does. The scope rules are the ones
EXISTS follows above.
Collect a subquery into a list¶
collect_subquery builds a COLLECT { ... } subquery expression. Its value is a
list with one element per body row. Every branch must end in a RETURN with exactly one
expression, so a body without one is rejected when the expression is built. The body sees
the enclosing scope without a scope clause, like the other subquery expressions.
from cypher_dsl import (
Configuration,
Renderer,
collect_subquery,
in_,
lit,
match,
node,
)
person = node("Person", name="p")
dog = node("Dog", name="d")
dogs = match(node(name="p").relationship_to(dog, "HAS_DOG")).returning(dog["name"])
statement = (
match(person)
.where(in_(lit("Ozzy"), collect_subquery(dogs)))
.returning(person["name"])
)
renderer = Renderer.get(Configuration(server_version="5.26"))
print(renderer.render(statement).cypher)
MATCH (p:Person) WHERE 'Ozzy' IN COLLECT { MATCH (p)-[:HAS_DOG]->(d:Dog)
RETURN d.`name` } RETURN p.`name`
The column check is syntactic. RETURN * is one expression and passes, although it
expands to every column in scope at run time. Neo4j decides whether the body produces the
one column COLLECT needs, and the library does not attempt that check.
Calling procedures¶
A procedure call is a whole clause built with call_procedure, not a subquery: it
invokes a stored procedure by name and binds the columns it yields. Call procedures
documents the call, its yield items and the filter after them.