Typed client
cyphra generate turns your .cyphra schema into a fully typed client: model types, inputs,
filters and results are all inferred from the schema — including nested relations and edge properties.
pnpm add cyphra
pnpm add -D @cyphra/cli
pnpm cyphra generate # writes cyphra.gen.ts (path set by "generate" in cyphra.json)import { createClient } from "./cyphra.gen.js";
const db = createClient({
uri: process.env.NEO4J_URI!,
user: process.env.NEO4J_USERNAME!,
password: process.env.NEO4J_PASSWORD!,
});To reuse a Driver your app already has (neo4j-driver 5.28+ or 6.x), pass
createClient({ driver }); see Using your own driver.
Each node model becomes a delegate with a lower-cased name: node User → db.user, node BlogPost → db.blogPost.
Requires Neo4j 5.6+ (the client compiles relations to
COLLECT {}/EXISTS {}subqueries).traverseneeds Neo4j 5.9+ (quantified path patterns).findSimilarneeds Neo4j 5.15+ (vector indexes;exact: trueneeds 5.18+).searchworks on any Neo4j 5 (full-text indexes).
Reading
const users = await db.user.findMany({
where: { email: { endsWith: "@acme.io" }, posts: { some: { published: true } } },
orderBy: [{ createdAt: "desc" }],
skip: 0,
take: 20,
});
const alice = await db.user.findUnique({ where: { email: "alice@acme.io" } }); // User | null
const sure = await db.user.findUniqueOrThrow({ where: { id } }); // throws NotFoundError
const first = await db.post.findFirst({ where: { published: false } });
const total = await db.user.count({ where: { name: { not: null } } });findUnique, update, upsert and delete require at least one @id / @unique field or
composite unique key in where, enforced by the types and at runtime.
Cursor pagination
skip / take page by offset. For “load more” and infinite scroll, page by cursor instead:
ask for $cursor in select (or include), and pass the last row’s cursor as cursor.after of
the next query, with the same orderBy:
const orderBy = [{ createdAt: "desc" }] as const;
const page1 = await db.post.findMany({
where: { published: true },
orderBy,
take: 20,
select: { id: true, title: true, $cursor: true },
});
// { id: string; title: string; $cursor: string }[]
const page2 = await db.post.findMany({
where: { published: true },
orderBy,
take: 20,
cursor: { after: page1.at(-1)?.$cursor },
select: { id: true, title: true, $cursor: true },
});These are keyset cursors: a cursor holds the orderBy values of its row plus the row’s @id,
and the next page is the nodes strictly after those values. The @id is always added as the last
sort key, so nodes that tie on orderBy are never repeated or skipped at a page boundary, and a
page does not shift when nodes are created or deleted before it (or when the cursor’s own node is
deleted), which offset pages do.
cursor: { before }pages backwards: withtake, the lasttakenodes before the cursor, inorderByorder.afterandbeforetogether keep the nodes between the two.skipstill applies, after the cursor (skip: 1skips one node after it).findFirsttakescursortoo.- Any
orderByworks: several keys in mixed directions, nullable fields (nullsorts last ascending and first descending, as in Cypher), a related node’s field ({ author: { name: "asc" } }) and relation counts ({ posts: { _count: "desc" } }). - Cursors are opaque strings, safe in a URL. A cursor is tied to its model and its
orderBy: one made for another model or anotherorderBy, or a malformed one, throws aCyphraValidationError(it does not silently return the first page).wherecan change between pages. - A cursor carries the values of its row’s sort keys in readable (base64) form: do not sort by a field you would not show to whoever holds the cursor.
- A model without
@id(a union) uses the node’s element id as the tie-breaker.
The pagination how-to shows the Cypher this compiles to and when an index
makes it faster than skip.
Composite unique keys
A @@unique([a, b]) model attribute is a unique key
too. Pass it under the fields’ names joined by _ (the Prisma shape), or under the attribute’s
name when it has one:
node Account {
id String @id @default(cuid())
providerId String
accountId String
tenant String
email String
user User @relationship(type: "HAS_ACCOUNT", direction: IN)
@@unique([providerId, accountId])
@@unique([tenant, email], name: "tenantEmail")
}const key = { providerId_accountId: { providerId: "github", accountId: "42" } };
await db.account.findUnique({ where: key });
await db.account.findUniqueOrThrow({ where: { tenantEmail: { tenant: "acme", email } } });
await db.account.update({ where: key, data: { email } });
await db.account.delete({ where: key });
await db.account.upsert({
where: key,
create: { ...key.providerId_accountId, tenant: "acme", email, user: { connect: { id: userId } } },
update: {},
});
await db.user.update({ where: { id: userId }, data: { accounts: { connect: key } } });- The key’s value is typed: it needs every field of the key, each with a non-null value of the
field’s type.
where: { providerId: "github", accountId: "42" }is not accepted as a unique key by the types (the runtime accepts it). - Other filters can sit next to the key, as with a single unique field:
{ ...key, tenant: "acme" }. upsertMERGEs on every field of the key (MERGE (n:Account {providerId: $a, accountId: $b})); values of the key fields increatemust equal the key’s. Whenwherealso has an@id/@uniquefield, theMERGEuses that field and the composite key is checked like any extra filter.connect,disconnectandsettake composite keys in theirwhereobjects.- A write that would duplicate a composite key throws a
UniqueConstraintErroronce the constraint exists (cyphra pushor a migration), withfields: ["providerId", "accountId"].
select and include
include adds relations to all scalar fields; select picks exactly what you want. Both nest, and each
relation accepts where, orderBy, skip and take. The result type follows your arguments.
const user = await db.user.findUnique({
where: { id },
select: {
name: true,
posts: {
where: { published: true },
orderBy: { title: "asc" },
take: 5,
select: { title: true },
},
following: true,
},
});
// { name: string | null; posts: { title: string }[]; following: (User & { $edge: Follows })[] } | nullWhen a relation’s edge is described by a relationship { … } model, each related node carries its edge
properties under $edge.
Filters
| Field type | Operators |
|---|---|
| any scalar | value (equals), null (absent), equals, not, in, notIn |
Int, BigInt, Float, String, DateTime, Date | lt, lte, gt, gte (strings compare lexicographically) |
LocalDateTime, LocalTime, Time | lt, lte, gt, gte (compared as temporal values) |
String | contains, startsWith, endsWith, mode |
| enum | the scalar operators above only, typed to the enum’s values |
Duration | the scalar operators above only (durations have no order) |
Point, CartesianPoint | value, null, equals, not, distance, withinBBox |
Json | null, equals, not only (no bare value, see below) |
lists (String[], Role[], …) | has, hasEvery, hasSome, isEmpty, equals |
| to-many relation | some, none, every |
| to-one relation | is, isNot, null (no related node) |
Combine with AND, OR and NOT.
BigInt filters take bigint values ({ balance: { gt: 0n, lte: 2n ** 62n } }). A Json filter
compares the whole stored JSON text: { settings: { equals: { theme: "dark" } } } matches a value
written as { theme: "dark" }, with the same key order. A bare value is not accepted on a Json
field (an object would read as a filter), and there are no queries into the value: model a field
you need to filter on as its own property.
Temporal filters take ISO 8601 text ({ starts: { gte: "2024-05-01T00:00", lt: "2024-06-01T00:00" } },
{ opens: { lt: "09:30" } }) and compare temporal values in Neo4j, not strings. A Duration
compares its months, days and seconds: { stay: "PT3H" } matches a value written as "PT180M"
(the same number of seconds), but "P1D" and "PT24H" differ (a day is not a number of seconds).
mode: "insensitive" on a String filter compares lower-cased values (Cypher toLower()) for
equals, not, in, notIn, contains, startsWith and endsWith. Range filters (lt, gte, …)
stay case-sensitive. A property index is not used for these comparisons.
await db.user.findFirst({ where: { email: { equals: "Alice@Acme.io", mode: "insensitive" } } });Spatial queries
Point and CartesianPoint fields filter on a distance from a point (point.distance: meters
along the Earth’s surface for Point, the field’s units for CartesianPoint), on a bounding box
(point.withinBBox, edges included), or on equality with a bare point. Places within 5 km of a
location, nearest first:
const here = { longitude: 2.3522, latitude: 48.8566 };
const nearby = await db.place.findMany({
where: { location: { distance: { from: here, lt: 5000 } } },
orderBy: { location: { distanceFrom: here } }, // nearest first; sort: "desc" for farthest
take: 20,
});| Point filter | Cypher |
|---|---|
{ location: here }, { equals: here } | n.location = $p |
{ distance: { from, lt, lte, gt, gte } } | point.distance(n.location, $from) < $d … |
{ withinBBox: { lowerLeft, upperRight } } | point.withinBBox(n.location, $ll, $ur) |
orderBy: { location: { distanceFrom, sort } } | ORDER BY point.distance(n.location, $from) |
// A ring: between 2 and 20 km.
await db.place.findMany({
where: { location: { distance: { from: here, gte: 2000, lte: 20_000 } } },
});
// Inside a box (Paris), with the corners as points.
await db.place.findMany({
where: {
location: {
withinBBox: {
lowerLeft: { longitude: 2.25, latitude: 48.81 },
upperRight: { longitude: 2.42, latitude: 48.91 },
},
},
},
});- Declare
location Point @index: migrations then create aPOINTindex, which Neo4j uses for these distance and bounding-box predicates. - The origin and the box corners must be points of the field’s type (a
CartesianPointfilter takes{ x, y }). A point of another CRS or dimension (2D vs 3D) never matches: its distance isnull. Sorting by distance puts nodes without the property (or with such a point) last. - Points do not sort by value and take no
lt/gt. The same filters work on point edge properties (edgeWherein traversals).
Counting related nodes
_count in include or select adds the number of related nodes per to-many relation. Each count
compiles to a COUNT {} subquery in the same statement, so no related nodes are loaded.
const users = await db.user.findMany({
include: {
_count: {
select: {
posts: { where: { published: true } }, // only count published posts
followers: true,
},
},
},
});
// (User & { _count: { posts: number; followers: number } })[]_count: truecounts every to-many relation of the model.- Each relation in
_count.selecttakestrueor{ where }; thewhereis a normal filter on the related node, relation filters included ({ where: { author: { is: { name: "Alice" } } } }). _countalso works inside an included or selected relation, at any depth (include: { author: { select: { name: true, _count: { select: { posts: true } } } } }), and in the results ofcreate,update,upsertanddelete.- As in Prisma, to-one relations cannot be counted; check them with an
is/isNotfilter instead.
To sort by a relation count, use orderBy: { posts: { _count: "desc" } }. It works at the top level
and inside an included relation, and combines with other sort keys:
const mostFollowed = await db.user.findMany({
orderBy: [{ followers: { _count: "desc" } }, { email: "asc" }],
take: 10,
});To count only some of the related nodes, add a where next to _count (a normal filter on the
related model, as in _count.select). Users with the most published posts first, and each user’s
followers by how many of their own followers are adults:
const prolific = await db.user.findMany({
orderBy: [{ posts: { _count: "desc", where: { published: true } } }, { email: "asc" }],
include: {
followers: { orderBy: { followers: { _count: "desc", where: { age: { gte: 18 } } } } },
},
});It compiles to ORDER BY COUNT { MATCH (n)-[:AUTHORED]->(m:Post) WHERE m.published = $p0 } DESC.
Prisma has no equivalent; where alone, without _count, does not sort.
To sort by a field of a to-one relation, nest it under the relation:
orderBy: { author: { name: "asc" } }. Nodes without the related node sort as null (last
ascending, first descending).
Aggregations
aggregate computes _count, _sum, _avg, _min and _max over the nodes matching where, in
one Cypher statement. The result has exactly the aggregates you ask for (same shape as Prisma).
const stats = await db.post.aggregate({
where: { published: true },
_count: true, // or { _all: true, score: true }
_sum: { views: true },
_avg: { views: true, score: true },
_min: { publishedOn: true },
_max: { views: true, title: true },
});
// {
// _count: number;
// _sum: { views: number | null };
// _avg: { views: number | null; score: number | null };
// _min: { publishedOn: Date | null };
// _max: { views: number | null; title: string | null };
// }| Aggregate | Fields | Result |
|---|---|---|
_count | true (nodes), _all (nodes), any scalar | number (non-null values for a field) |
_sum | Int, Float, BigInt | number | null (bigint | null for BigInt) |
_avg | Int, Float, BigInt | number | null (a mean, so not always whole) |
_min, _max | Int, Float, BigInt, String, enum, DateTime, Date, LocalDateTime, LocalTime, Time | the field type, or null |
nullvalues (absent properties) are ignored, as in SQL.- On an empty match, counts are
0and every other aggregate isnull(Cypher’ssum()returns 0; Cyphra returnsnull, like SQL and Prisma). DateTimeandDateresults come back asDate(UTC),LocalDateTime/LocalTime/Timeresults as ISO text. Strings and enums compare by code point.Durationand point fields have no_min/_max.- A
BigInt_sumpast 2^63-1 overflows in Neo4j (it returns a rounded float): Cyphra throws aRangeErrorinstead of returning a wrong value. orderBy,skipandtakepick a window of the matching nodes first:{ orderBy: { views: "desc" }, take: 10, _avg: { views: true } }is the average of the ten most viewed posts.
Asking for an aggregate that does not fit the field (_sum on a String, _min on a Boolean or a
list) is a type error, and a CyphraValidationError for untyped callers.
groupBy
groupBy groups the matching nodes by one or more fields and aggregates each group, in one statement.
It takes the same _count, _sum, _avg, _min and _max as aggregate, plus having, orderBy,
skip and take on the groups.
const byStatus = await db.post.groupBy({
by: ["published"], // or a single field: by: "published"
where: { views: { gt: 0 } },
_count: { _all: true },
_avg: { views: true },
having: { views: { _avg: { gt: 10 } } },
orderBy: [{ _count: { id: "desc" } }, { published: "asc" }],
take: 10,
});
// { published: boolean; _count: { _all: number }; _avg: { views: number | null } }[]havingfilters groups. On any scalar field it takes aggregate filters ({ views: { _sum: { gte: 100 } } },{ id: { _count: { gt: 1 } } }); on a field listed inbyit also takes the usual filters ({ published: true }).AND,ORandNOTcombine them.orderBysorts by fields listed inbyor by aggregates ({ _max: { views: "desc" } },{ _count: { _all: "asc" } }).- A
nullkey is a group of its own (nodes without the property).
Grouping by a related node
Fields of a to-one relation are written "relation.field" in by, and come back nested under the
relation name. having and orderBy use the nested form.
const perAuthor = await db.post.groupBy({
by: ["author.name", "author.email"],
_sum: { views: true },
having: { author: { name: { not: null } } },
orderBy: { author: { name: "asc" } },
});
// { author: { name: string | null; email: string | null }; _sum: { views: number | null } }[]Posts without an author fall into the group whose related fields are all null. To-many relations
cannot be grouped on (a post would belong to several groups); aggregate from the other side instead,
for example db.user.groupBy with where: { posts: { some: … } }.
Traversals
traverse follows a relation for several hops and returns the nodes it reaches: “friends of friends”,
“everyone downstream of this service”, “people within three introductions”. It compiles to one Cypher
statement with a quantified path pattern
(Neo4j 5.9+), with every value sent as a parameter.
node User {
id String @id @default(cuid())
email String @unique
name String?
age Int?
following User[] @relationship(type: "FOLLOWS", direction: OUT)
followers User[] @relationship(type: "FOLLOWS", direction: IN)
}
relationship Follows {
type "FOLLOWS"
from User
to User
since DateTime @default(now())
}// Friends of friends: everyone Alice follows, and everyone they follow.
const fof = await db.user.traverse({
from: { email: "alice@acme.io" },
via: "following",
depth: { max: 2 },
where: { age: { gte: 18 } }, // filter on the reached nodes
orderBy: { name: "asc" },
take: 20,
});
// User[]The generated Cypher is:
MATCH (s:`User`) WHERE s.`email` = $p0
MATCH (s)((:`User`)-[e0:`FOLLOWS`]->(:`User`)){1,2}(n:`User`)
WHERE (n <> s) AND (n.`age` >= $p1)
WITH DISTINCT n ORDER BY n.`name` ASC LIMIT $p2
RETURN n{.`id`, .`email`, .`name`, .`age`} AS row ORDER BY n.`name` ASC| Argument | Meaning |
|---|---|
from | Start node(s): any where filter on the model ({ id }, { email }, { age: { gt: 30 } }). Required. |
via | A relation of the model that leads back to the same model ("following"), or a list of them (["following", "followers"]): each hop takes any of them. |
depth | { min?, max } hops. max is required; min defaults to 1, and min: 0 also returns the start node. |
direction | "out", "in" or "both": the arrow direction of every hop. Default: each relation’s declared direction. |
where | Filter on the reached nodes, the same as in findMany (relation filters included). |
edgeWhere | Filter on the properties of every edge of the path, typed from the relationship { … } model. Only when every relation in via has one. |
distinct | true (default): each reached node once. false: one result per path, so a node reached two ways appears twice. |
select, include | Shape the reached nodes, as in findMany (_count and nested relations included). |
orderBy, skip, take | Sort and page the reached nodes. |
returnPaths | true: return { node, path } instead of the node (see Paths). |
- Upper bound.
depth.maxis required and capped by the client optionmaxTraversalDepth(default10):createClient({ uri, user, password, maxTraversalDepth: 4 }). Every extra hop can multiply the number of paths Neo4j explores, so set the cap as low as your queries allow. A missingmax, amaxabove the cap or an unknown relation inviais a type error where TypeScript can see it, and aCyphraValidationErrorat run time. - Cycles. Neo4j never uses the same relationship twice in one path, so cycles end on their own. A path that comes back to its own start node is skipped: Alice is not her own friend of a friend.
- Same model. With relation names, each relation in
viamust lead back to the model (UsertoUser). For chains over different models (ChunktoEntitytoChunk), give a list of hops: see Multi-hop traversals. traverseworks in$transactionand sees the transaction’s own writes.
Edge filters apply to every hop. Only follows made since 2024, both directions, exactly two hops away:
const recent = await db.user.traverse({
from: { id: alice.id },
via: ["following", "followers"], // same as via: "following", direction: "both"
depth: { min: 2, max: 2 },
edgeWhere: { since: { gte: new Date("2024-01-01") } },
select: { email: true, _count: { select: { followers: true } } },
});
// { email: string; _count: { followers: number } }[]Multi-hop traversals
via also takes a list of hops, followed in order. Each hop names relation(s) of the model the
previous hop reached, so a traversal can cross models: from a chunk to the entities it mentions, to
related entities, to the other chunks that mention them. The results are nodes of the last hop’s
model.
node Chunk {
id String @id
text String
draft Boolean @default(false)
entities Entity[] @relationship(type: "MENTIONS", direction: OUT)
}
node Entity {
id String @id
name String
kind String
chunks Chunk[] @relationship(type: "MENTIONS", direction: IN)
related Entity[] @relationship(type: "RELATED_TO", direction: OUT)
relatedFrom Entity[] @relationship(type: "RELATED_TO", direction: IN)
}
relationship RelatedTo {
type "RELATED_TO"
from Entity
to Entity
weight Int @default(0)
}const context = await db.chunk.traverse({
from: { id: "c1" },
via: [
{ rel: "entities", where: { kind: "person" } }, // the people c1 mentions
{
rel: "related",
direction: "both",
depth: { min: 0, max: 2 }, // zero to two RELATED_TO hops
edgeWhere: { weight: { gte: 2 } },
},
{ rel: "chunks" }, // the chunks that mention them
],
where: { draft: false }, // on the reached chunks
orderBy: { entities: { _count: "desc", where: { kind: "person" } } },
take: 5,
select: { id: true, text: true },
});
// { id: string; text: string }[]It compiles to one statement, a quantified path pattern per hop:
MATCH (s:`Chunk`) WHERE s.`id` = $p0
MATCH (s)((:`Chunk`)-[e0:`MENTIONS`]->(t1:`Entity`) WHERE (t1.`kind` = $p1)){1,1}
((:`Entity`)-[e2:`RELATED_TO`]-(:`Entity`) WHERE (e2.`weight` >= $p2)){0,2}
((:`Entity`)<-[e3:`MENTIONS`]-(:`Chunk`)){1,1}(n:`Chunk`)
WHERE (n <> s) AND (n.`draft` = $p3)
…| Hop option | Meaning |
|---|---|
rel | A relation of the model the previous hop reached (the start model for the first hop), or a list of them leading to the same model. Required. |
direction | "out", "in" or "both" for this hop. Default: each relation’s declared direction. |
depth | { min?, max }: repeat this hop. Only on a relation back to the same model (Entity.related); without it, the hop is taken once. |
where | Filter on every node this hop steps to (relation filters included). A hop repeated zero times checks nothing. |
edgeWhere | Filter on the edges of this hop, typed from their relationship { … } model. |
- Everything else works as above:
fromfilters the start model,where,orderBy,select/includeand the result type are those of the last hop’s model, anddistinct,skip,takeandreturnPathskeep their meaning.depth,directionandedgeWherego on the hops. - Every hop is typed: an unknown relation, a
depthon a hop to another model, or awherewith a field of the wrong model is a compile error, and aCyphraValidationErrorat run time. - The hops’
depth.max(1 for a hop withoutdepth) add up to at mostmaxTraversalDepth. - A path that comes back to its start node is skipped, unless every hop allows zero repetitions.
- With
returnPaths,path.nodesholds the models met along the way (Chunk | Entityabove) andpath.edgestheir typed edges; the type is exported asHopPath. - Computed fields from
$extendsapply to the last hop’s model.
Paths
With returnPaths: true, each result is { node, path }. The path lists the nodes from the start node
to the reached node and the edges between them, with edge properties typed from the
relationship { … } model:
const rows = await db.user.traverse({
from: { email: "alice@acme.io" },
via: "following",
depth: { max: 3 },
where: { email: "dave@acme.io" },
select: { email: true },
returnPaths: true,
});
const { node, path } = rows[0]!;
node.email; // string
path.nodes.map((u) => u.name); // ["Alice", "Carol", "Dave"]: User scalars
path.edges[0]; // { type: "FOLLOWS", direction: "out", properties: { since: Date } }path.edges[i]joinspath.nodes[i]andpath.nodes[i + 1], andpath.edges.lengthis the number of hops.directionis"out"when the edge points fromnodes[i]tonodes[i + 1],"in"when it points back (for example when walkingfollowers).- Path nodes carry the model’s scalar fields;
selectandincludeshapenodeonly. - With
distinct(default),pathis one of the shortest paths to the node. Withdistinct: false, every path is its own result. - The types are exported for your own code:
Path<Node, Edge>,PathEdge<Props>, andModelPath<CyphraTypeMap, "User", "following">for the path of a given model and relation.
Shortest path
shortestPath finds one shortest path between two nodes along a relation: “how is Alice connected to
Dave?”, “the fewest introductions between two people”. allShortestPaths returns every path of that
minimal length. Both compile to one Cypher statement with a
shortest path selector
(SHORTEST 1 / ALL SHORTEST, Neo4j 5.21+), with every value sent as a parameter.
const path = await db.user.shortestPath({
from: { email: "alice@acme.io" },
to: { email: "dave@acme.io" },
via: "following",
maxDepth: 4,
});
// ModelPath<CyphraTypeMap, "User", "following"> | null
path?.nodes.map((u) => u.name); // ["Alice", "Carol", "Dave"]
path?.edges[0]; // { type: "FOLLOWS", direction: "out", properties: { since: Date } }The generated Cypher is:
MATCH (s:`User`) WHERE s.`email` = $p0
MATCH (t:`User`) WHERE t.`email` = $p1
MATCH p = SHORTEST 1 (s)((:`User`)-[e0:`FOLLOWS`]->(:`User`)){0,4}(t)
WITH p ORDER BY length(p) LIMIT 1
RETURN [n1 IN nodes(p) | n1{.`id`, .`email`, .`name`, .`age`}] AS nodes, {…} AS path| Argument | Meaning |
|---|---|
from, to | Start and end node(s): any where filter on the model. Both required. |
via | A relation of the model that leads back to the same model, or a list of them, as in traverse. |
maxDepth | Longest path searched, in hops. Required, and at most the client option maxTraversalDepth (default 10). |
direction | "out", "in" or "both", as in traverse. Default: each relation’s declared direction. |
where | Filter every intermediate node must match (not the start or end node), relation filters included. |
edgeWhere | Filter on the properties of every edge of the path, typed from the relationship { … } model. |
select, include | Shape the nodes of the path, as in findMany (_count and nested relations included). |
take | allShortestPaths only: return at most this many paths. |
- Result. A path:
nodesfrom the start node to the end node (shaped byselect/include, all scalar fields by default) and typededges.shortestPathreturnsnullwhen no path of at mostmaxDepthhops exists;allShortestPathsreturns[]. - Several start or end nodes.
fromandtoare filters, so each may match several nodes. Cyphra searches every start/end pair and keeps the overall shortest:shortestPathreturns one path of the minimal length (which one, when several tie, is up to Neo4j), andallShortestPathsreturns every path of that length, over all pairs. Use a unique field ({ id },{ email }) for a single pair. - Same node. A node that matches both
fromandtois joined to itself by a zero-hop path:{ nodes: [node], edges: [] }. - Filters apply during the search.
whereandedgeWhereare checked before the shortest path is picked, so when they rule out the shortest path you get the next shortest one, notnull. - Same rules as
traverse.maxDepthis capped bymaxTraversalDepth;viatakes relations that lead back to the same model; a missingmaxDepthorto, or a bad relation, is a type error and aCyphraValidationError. Both methods work in$transaction.
Every tied shortest path, through adults only, along follows made since 2024 in either direction:
const routes = await db.user.allShortestPaths({
from: { id: alice.id },
to: { id: dave.id },
via: "following",
direction: "both",
maxDepth: 6,
where: { age: { gte: 18 } },
edgeWhere: { since: { gte: new Date("2024-01-01") } },
select: { name: true },
take: 10,
});
// { nodes: { name: string | null }[]; edges: PathEdge<{ since: Date }>[] }[]The result type is exported as ShortestPathResult<CyphraTypeMap, "User", "following", Node>.
Vector search
findSimilar returns the k nodes whose embedding is closest to a query vector, through the
field’s vector index: the retrieval step of semantic search and GraphRAG.
It is available on models with a Vector(N) @vectorIndex field, and field only accepts those fields.
const chunks = await db.chunk.findSimilar({
field: "embedding",
vector: await embed("How do I rotate API keys?"), // number[] of length 1536
k: 5,
where: { document: { is: { published: true } } },
include: { document: { select: { title: true, url: true } } },
});
// (Chunk & { document: { title: string; url: string } | null; $score: number })[]
chunks[0].$score; // 0.93Results come best first, shaped by select / include like findMany, each with a $score
(model fields cannot start with $, so it never collides). include is how the graph helps
retrieval: load the chunk’s document, its neighbours or its entities in the same statement.
| Argument | Meaning |
|---|---|
field | The Vector(N) field to search. It must have a @vectorIndex. |
vector | The query embedding. Its length must be N, else CyphraValidationError (checked before any query). |
k | Number of results (a positive integer). |
where | Any filter on the model, relation filters included. See below for how it combines with the index. |
minScore | Drop results that score below this. |
candidates | Neighbours asked from the index on the first attempt (at least k). Default k, or max(10 × k, 100) with where. |
maxCandidates | Upper bound on the neighbours a filtered search asks for (default: no bound). |
exact | true: skip the index and score every node matching where (see below). |
select, include | Shape each result, as in findMany. |
Scores are the index’s, in [0, 1], higher is more similar: (1 + cos) / 2 for cosine
(so 0.5 is orthogonal) and 1 / (1 + d²) for euclidean. With Neo4j’s default quantization the
index stores compressed vectors, so scores are close to, not exactly, the exact similarity.
How where works. Without a filter, findSimilar is one call to
db.index.vector.queryNodes(index, k, vector). Neo4j 5 vector indexes take no filter: the procedure
returns its nearest neighbours and anything else is applied afterwards, so filtering the top k
could leave fewer than k results. With where, findSimilar instead asks the index for
candidates neighbours, filters them in the same statement and keeps the best k. If fewer than
k pass, it asks again for four times as many, until it has k results, the index has no more
nodes, the scores fall below minScore, or it reaches maxCandidates. So you get the k best
matching nodes, as far as the approximate index can tell, at the cost of extra queries when the
filter is selective.
exact: true skips the index: it matches the nodes that pass where and ranks them with
vector.similarity.cosine / vector.similarity.euclidean (Neo4j 5.18+), in one statement. Use it
when where narrows the search to a few thousand nodes (the chunks of one document, one tenant’s
data): results are exact and nothing is over-fetched. It also sees nodes written earlier in the same
$transaction, which the vector index does not (it only holds committed data).
The generated Cypher for a filtered search, here where: { document: { is: { published: true } } }
with include: { document: { select: { title: true } } } ($cyphraCandidates grows between
attempts):
CALL db.index.vector.queryNodes($p3, $cyphraCandidates, $p1) YIELD node, score
WITH collect({n: node, s: score}) AS hits
CALL {
WITH hits UNWIND hits AS h WITH h.n AS n, h.s AS score
WHERE EXISTS { MATCH (n)-[:`PART_OF`]->(m0:`Document`) WHERE m0.`published` = $p0 }
WITH n, score ORDER BY score DESC LIMIT $p2
RETURN collect({row: n{.`id`, .`text`, .`embedding`,
`document`: head(COLLECT { MATCH (n)-[r2:`PART_OF`]->(m1:`Document`) RETURN m1{.`title`} })
}, score: score}) AS rows
}
RETURN size(hits) AS fetched, hits[-1].s AS lowest, rowsFor retrieval end to end (chunking, embeddings, hybrid search with search and
expansion through entities), see the GraphRAG guide.
findSimilar works in $transaction and with either driver major. Vectors are
written with a plain SET of a float list, which Neo4j indexes like
db.create.setNodeVectorProperty would. The FindSimilarArgs and SimilarResult types are exported.
Full-text search
search runs a full-text query through one of the model’s @@fulltext indexes
and returns the matching nodes, most relevant first: search boxes, autocomplete, keyword search
next to (or combined with) vector search. It is available on models with a
@@fulltext attribute, and index only accepts that model’s index names.
const posts = await db.post.search({
index: "postSearch",
query: userInput,
mode: "terms", // treat the input as plain words
where: { published: true, author: { is: { country: "FR" } } },
take: 10,
select: { id: true, title: true, author: { select: { name: true } } },
});
// { id: string; title: string; author: { name: string } | null; $score: number }[]Results are shaped by select / include like findMany, each with a $score: Lucene’s relevance
score (BM25), positive and unbounded. Scores rank the hits of one query; they are not comparable
across queries or with findSimilar scores.
| Argument | Meaning |
|---|---|
index | The @@fulltext index to query, by name. |
query | The search text. A blank query returns [] without querying. |
mode | "lucene" (default), "terms" or "phrase": how query is read (see below). |
where | Any filter on the model, relation filters included, applied to the hits before paging. |
minScore | Drop hits that score below this. |
skip, take | Page through the ranked hits, after filtering (default: every hit). |
select, include | Shape each result, as in findMany. |
Query syntax. By default query is Lucene query syntax ,
passed through to Neo4j: graph databases (any of the words), "graph databases" (the phrase),
+graph -sql, graph AND neo4j, title:graph (one field of the index), graph* (prefix),
grph~ (fuzzy), title:graph^5 OR body:graph (boost). Malformed syntax such as C++ (beta makes
Neo4j throw. For text typed by users, pick a mode that escapes it:
mode: "terms"escapes the input and matches any of its words, ranked by relevance.mode: "phrase"escapes the input and matches its words in that order.escapeLucene(text)(exported) escapes the special characters (+ - && || ! ( ) { } [ ] ^ " ~ * ? : \ /) and theAND/OR/NOToperators, to mix user input into a query you build:
import { escapeLucene } from "cyphra";
const prefix = await db.post.search({
index: "postSearch",
query: `title:${escapeLucene(input)}*`,
});
const allWords = await db.post.search({
index: "postSearch",
query: input
.split(/\s+/)
.filter(Boolean)
.map((w) => `+${escapeLucene(w)}`)
.join(" "),
});The index’s analyzer applies to the query as it does to the text: with analyzer: "english",
run finds “running”; with keyword, only the exact, case-sensitive value matches.
How where works. db.index.fulltext.queryNodes(index, query) returns every node matching the
query, not a top-k, so filtering afterwards loses nothing: where and minScore filter the hits in
the same statement, then the rows are ranked by score and skip / take apply. Without a filter,
take is passed to the procedure as {limit: skip + take} so Lucene only collects the hits it
returns. The statement for the example above (paged with take: 10):
CALL db.index.fulltext.queryNodes($p1, $p2) YIELD node, score
WITH node AS n, score WHERE (n.`published` = $p0)
WITH n, score ORDER BY score DESC LIMIT $p3
RETURN n{.`title`, `author`: head(COLLECT {
MATCH (n)<-[r1:`WROTE`]-(m0:`Author`) RETURN m0{.`name`}
})} AS row, score ORDER BY score DESCsearch works in $transaction and with either driver major. Unlike a vector
index, a full-text index sees the nodes created or changed earlier in the same transaction (unless it
is eventuallyConsistent, in which case it only sees committed writes, a moment after commit). The
SearchArgs, SearchMode and SearchResult types are exported.
Querying interfaces
An interface has a delegate like a node (db.person
for interface Person) with every read operation: findMany, findFirst, findUnique, count,
aggregate, groupBy, traverse, shortestPath, search and findSimilar. It matches every
node with the interface’s label, so the results are its implementations, as a union discriminated
by __typename:
// schema: interface Person { … } node Employee implements Person { salary Int }
// node Customer implements Person { tier String }
const people = await db.person.findMany({ where: { name: { startsWith: "A" } } });
for (const p of people) {
if (p.__typename === "Employee")
console.log(p.name, p.salary); // salary: number
else console.log(p.name, p.tier); // "Customer": tier: string
}__typenamecomes from the node’s labels. It is only on results of interface queries (and of relations whose target is an interface, such asinclude: { manager: true }); results ofdb.employeekeep their shape, inherited fields included.- Without
select, each result has every scalar field of its implementation.includeloads the interface’s relations, and$onan implementation’s own. selectpicks interface fields and relations (plus, under$on, an implementation’s own);__typenameis always returned.where,orderByand_counttake the interface’s fields and relations, and__typename.- A node that has the interface label but no implementation label (written outside Cyphra) comes
back with
__typenameset to the interface name and only the interface’s fields. - An interface extending another has its own delegate
(
db.staff), whose results are the implementations below it.
Filtering by implementation (__typename)
where: { __typename } keeps the results of some implementations, by their labels. It takes an
implementation name or { equals, not, in, notIn }, works wherever the model is an interface
(including relation filters such as manager: { is: { __typename: "Customer" } }), and is typed
with the implementation names. orderBy: { __typename: "asc" } sorts by implementation name.
const employees = await db.person.findMany({ where: { __typename: "Employee" } });
const notCustomers = await db.person.count({ where: { __typename: { notIn: ["Customer"] } } });
const grouped = await db.person.findMany({ orderBy: [{ __typename: "asc" }, { name: "asc" }] });The result type stays the union of every implementation (narrow it with p.__typename), and on a
node model __typename is rejected.
where: { $on } filters per implementation: it keeps the nodes of the implementations it lists
that match their own where (fields the interface does not have included), and leaves the others
out. {} keeps every node of an implementation, and an empty $on matches nothing (like
OR: []):
// Employees earning more than 100, and every customer.
const people = await db.person.findMany({
where: { $on: { Employee: { salary: { gt: 100 } }, Customer: {} } },
});Per-implementation fields ($on)
$on in the select or include of an interface query loads, for each implementation it names,
that implementation’s own select / include: fields and relations the interface does not have.
They are added to that implementation’s results only, and the result type follows:
const people = await db.person.findMany({
include: {
manager: true,
$on: {
Employee: { team: true, badges: { take: 3 } },
Customer: { _count: { select: { orders: true } } },
},
},
});
for (const p of people) {
if (p.__typename === "Employee")
p.team; // { id, name } | null
else p._count.orders; // number
}
const names = await db.person.findMany({
select: { name: true, $on: { Employee: { salary: true } } },
}); // ({ __typename: "Employee"; name: string; salary: number } | { __typename: "Customer"; name: string })[]- Under
include,$on.<Implementation>takes relations and_count(its scalars are already there); underselect, its scalars and relations too. - Keys are implementation names; anything else is a
CyphraValidationError, and so is$onon a node model. It works on nested loads whose target is an interface (include: { owner: { include: { $on: { Employee: { team: true } } } } }). - Cyphra evaluates each part only on the nodes of that implementation (
CASE WHEN n:Employee), and computed fields of$extendsapply inside it.
Writes: an interface has no create, createMany or upsert (they are not in its type and throw
a CyphraValidationError), and a nested create into a relation that targets an interface is
rejected: create an implementation instead. connect works by the interface’s unique fields
(manager: { connect: { email: "boss@acme.io" } }), and update, updateMany, delete and
deleteMany work through the interface on its fields. Deleting through an interface applies the
onDelete rules of each node’s implementation, so db.person.delete(…) on an
employee still cascades along the employee’s own Cascade relations.
Querying unions
A union has a read-only delegate (db.searchHit for
union SearchHit = Post | User | Comment) with findMany, findFirst and count. It matches the
nodes of every member, and results are discriminated by __typename, each with every scalar field
of its member:
const hits = await db.searchHit.findMany({
where: {
$on: {
Post: { title: { contains: "graph", mode: "insensitive" } },
User: { name: { startsWith: "Gra" } },
},
},
orderBy: { __typename: "asc" },
take: 20,
});
for (const h of hits) {
if (h.__typename === "Post") console.log(h.title);
else if (h.__typename === "User") console.log(h.name);
}- A union has no fields of its own, so
wheretakes__typenameand$on(each listed member with its own filter; members not listed are left out), plusAND/OR/NOT.orderBytakes__typename. selectandincludetake$ononly:select: { $on: { Post: { title: true, author: true } } }returns{ __typename: "Post", title, author } | { __typename: "User" } | ….- There is no unique key, so no
findUnique, and no fields to aggregate:aggregate,groupByand the traversals are not on a union delegate (they are not in its type and throw aCyphraValidationError). Neither are writes: write through the members. searchandfindSimilarquery the members’ own indexes and merge the hits by rank.- Relations whose target is a union load, filter and count like any relation
(
include: { items: { where: { __typename: "Post" } } },where: { items: { some: { $on: { User: { name: "Ada" } } } } },_count), and traversals can end on one (via: [{ rel: "items" }]).
Writes through a relation to a union name the member of each item, since the members share no key:
await db.board.update({
where: { id: boardId },
data: {
items: {
create: [{ Post: { title: "Release notes" } }, { Comment: { text: "First" } }],
connect: { User: { email: "ada@example.com" } },
disconnect: { Post: { id: oldPostId } },
},
},
});
await db.pin.update({ where: { id }, data: { subject: { connect: { Post: { id: postId } } } } });- Each
create,connect,disconnectandsetitem has exactly one member key; anything else is aCyphraValidationError(and a type error). The member’s value is its own create data or unique key, with its validation rules checked. connecton a to-one relation to a union replaces the edge to any member, and keeps the member’s own to-one inverse field (Post.pin) to a single edge, as for other relations.onDeleterules on a relation to a union apply to every member:Cascadedeletes each related node with the rules of the model it is.
With a relationship { … } model to the union, $edge goes next to the member
key, and every related node comes back with its edge properties under $edge:
const board = await db.board.update({
where: { id: boardId },
data: {
picks: {
create: { Post: { title: "Release notes" }, $edge: { rank: 1 } },
connect: { User: { email: "ada@example.com" }, $edge: { rank: { increment: 1 } } },
},
},
include: { picks: true },
});
board.picks[0]!.$edge.rank; // number, whatever the memberset items take $edge the same way, the members’ inverse fields (Post.pickedBy) read the same
edges with their $edge, and traversals filter on them with
edgeWhere.
A union with an interface member (union Party = Person | Team) returns the
interface’s implementations, typed by __typename. Writes and $on may name the interface to
cover every implementation: connect: { Person: { email } } connects by the interface’s unique
fields, where: { $on: { Person: { email: { endsWith: "@acme.io" } } } } keeps every person
matching it, and select: { $on: { Person: { email: true } } } applies to each implementation
not listed itself. A nested create names an implementation (create: { Employee: { … } }): an
interface cannot be created.
Searching a union
search and findSimilar on a union query one index per member (@@fulltext indexes for
search, @vectorIndex fields for findSimilar) and merge the hits into one ranked list: the
results box of a site search over posts, users and comments. They are on the delegate when at
least one member has such an index.
const hits = await db.searchHit.search({
query: input,
mode: "terms",
indexes: { Post: "postSearch", User: "userName" }, // one index per member searched
where: { $on: { Post: { published: true }, User: {} } },
select: { $on: { Post: { title: true, author: true }, User: { name: true } } },
take: 20,
scores: true,
});
for (const h of hits) {
if (h.__typename === "Post") console.log(h.title, h.$score);
h.$scores; // { postSearch: { score: 4.2, normalized: 1, rank: 1 } }
}
const similar = await db.searchHit.findSimilar({
vector: await embed(input),
fields: { Post: "embedding", Comment: "embedding" },
take: 10,
});Ranking. Scores of different indexes are not comparable: Lucene’s depend on each index’s statistics, and two vector indexes may use different similarity functions. So each member’s index is queried and ranked on its own, and the lists are merged with reciprocal rank fusion (RRF):
- A hit’s
$scoreisΣ 1 / (k + rank)over the lists it appears in, itsrankin each list counting from 1 (kisrrfK, 60 by default). The best hit of each list scores1 / 61. - Each list is also min-max normalised:
normalized = (score - min) / (max - min)over the hits that index contributed to the fusion (afterwhereandminScore, and within itsskip + takebest),1when they all score the same. It is reported in$scoresand breaks ties. - The order is total and stable:
$score(descending), then the best normalised score (descending), then the member’s position (the order ofindexes/fields, else the union’s declaration order), then the node’s id. Within one list, hits with the same raw score are ranked by node id.
With scores: true each result also has $scores, keyed by index name, with the index’s raw
score, its normalized score and its rank.
| Argument | Meaning |
|---|---|
query, mode | search: the text and how to read it, sent to every index (as for search). |
indexes | search: { <member>: <index> }, the members to search. Default: every member with exactly one @@fulltext index (a member with several must be listed). |
vector | findSimilar: the query embedding; its length must match every searched field. |
fields | findSimilar: { <member>: <field> }. Default: every member with exactly one @vectorIndex field. |
candidates | findSimilar: neighbours asked from each index (default skip + take, or max(10 × (skip + take), 100) with where). |
where | The union’s filter (__typename, $on per member, AND / OR / NOT), applied in every list before ranking. |
minScore | Drop hits whose raw score in their own index is below this, before ranking. |
skip, take | Page through the fused list. take is required for findSimilar; each list contributes its skip + take best hits. |
rrfK | The k of RRF (default 60). Lower values weigh the top ranks more. |
scores | true: add $scores to each result. |
select, include | Per member with $on, as in findMany; related nodes are loaded for the returned page only. |
- An index a member inherits from an interface (
@@fulltextoninterface Person) keeps that member’s nodes only; an interface member of the union (union Party = Person | Team) is searched through the interface’s own index and covers every implementation. - A union
findSimilarasks each index once: with a selectivewhereit can return fewer thantakehits (raisecandidates), where a model’sfindSimilarwidens the search. It has nok(page withtake/skip) and noexact.
It is one read-only statement: a CALL { … } subquery per index collects that index’s hits
(filtered, ranked, cut to skip + take), then the lists are fused, paged and projected. Chained
subqueries rather than a UNION inside one CALL keep one list per index, which ranking needs,
and run unchanged on Neo4j, Memgraph and FalkorDB:
CALL { CALL db.index.fulltext.queryNodes($p0, $p1) YIELD node, score WITH node AS n, score
WHERE (((n:`Post`) AND (n.`published` = $p2)) OR (n:`User`))
WITH n, score ORDER BY score DESC, elementId(n) ASC LIMIT $p5
RETURN collect({n: n, s: score}) AS hits0 }
CALL { CALL db.index.fulltext.queryNodes($p3, $p4) YIELD node, score … AS hits1 }
WITH [hits0, hits1] AS lists
UNWIND range(0, size(lists) - 1) AS li WITH li, lists[li] AS hits
UNWIND range(0, size(hits) - 1) AS pos
WITH li, hits[pos].n AS n, hits[pos].s AS score, pos + 1 AS rank,
hits[0].s AS hi, hits[size(hits) - 1].s AS lo
WITH n, li, score, rank, CASE WHEN hi = lo THEN 1.0 ELSE (score - lo) / (hi - lo) END AS norm
WITH n, sum(1.0 / ($p6 + rank)) AS fused, max(norm) AS best, min(li) AS first, collect(…) AS parts
ORDER BY fused DESC, best DESC, first ASC, elementId(n) ASC LIMIT $p7
RETURN n{…} AS row, fused, parts …The UnionSearchArgs, UnionFindSimilarArgs, FusedResult and IndexScore types are exported.
Dynamic labels
Models declaring @@labels([…]) take $labels in writes, filters and
select / include, typed with the declared labels:
// schema: node Post { … @@labels([Archived, Featured]) }
const post = await db.post.create({ data: { title: "Hi", $labels: ["Featured"] } });
await db.post.update({
where: { id: post.id },
data: { $labels: { add: ["Archived"], remove: ["Featured"] } },
});
await db.post.update({ where: { id: post.id }, data: { $labels: { set: ["Archived"] } } });
await db.post.updateMany({
where: { $labels: { has: "Archived" } },
data: { $labels: { remove: ["Archived"] } },
});
const featured = await db.post.findMany({
where: { $labels: { has: "Featured", hasNone: ["Archived"] } },
select: { title: true, $labels: true },
}); // { title: string; $labels: ("Archived" | "Featured")[] }[]- Writes.
create,createMany, nestedcreateand thecreateofupserttake$labels: [...], the labels the new node gets.update,updateManyand theupdateofupserttake{ add, remove }(a label in both is an error) or{ set }: exactly these labels, every other declared label removed. A label change is part of the same statement as the rest of the write: when a@min/@maxcheck fails, labels are left as they were. - Filters.
where: { $labels: … }takeshas(one label),hasSome,hasEvery,hasNone(arrays) andisEmpty: true(none of the model’s dynamic labels). It works wherever awhereof the model does: relation filters (posts: { some: { $labels: { has: "Featured" } } }),count,aggregate,groupBy,_countfilters,AND/OR/NOT. An emptyhasSomematches nothing, an emptyhasEveryeverything. - Results.
$labelsis only returned when asked for:select: { $labels: true }orinclude: { $labels: true }(with every scalar field), also on loaded relations. It lists the node’s dynamic labels in declaration order, never its model or interface labels. - Interfaces.
@@labelson an interface is shared by its implementations: the interface’s delegate (db.person) filters and writes the interface’s labels, an implementation’s delegate those and its own. - Safety. Labels are checked against the schema’s list before anything runs (any other value,
or
$labelson a model without@@labels, is aCyphraValidationError), and the statement uses the schema’s spelling:SET n:Archived,REMOVE n:Featured,WHERE n:Featured. No label name is ever taken from a value, so there is no Cypher injection through$labels, and the same statements run on Memgraph and FalkorDB.
Writing
const alice = await db.user.create({
data: {
email: "alice@acme.io",
posts: { create: [{ title: "Hello graph" }] },
following: { connect: { email: "bob@acme.io", $edge: { since: new Date() } } },
},
include: { posts: true },
});
await db.user.update({
where: { id: alice.id },
data: {
name: "Alice",
loginCount: { increment: 1 },
following: { disconnect: { email: "bob@acme.io" } },
},
});
await db.post.update({ where: { id }, data: { author: { connect: { id: alice.id } } } }); // replaces the edge
await db.post.update({ where: { id }, data: { author: { disconnect: true } } });
await db.user.upsert({ where: { email }, create: { email }, update: { name: "again" } });
await db.user.delete({ where: { id } }); // returns the deleted node
await db.user.createMany({ data: [{ email: "a@x.io" }, { email: "b@x.io" }] });
await db.user.updateMany({ where: { name: null }, data: { name: "anonymous" } });
await db.user.deleteMany({ where: { email: { endsWith: "@spam.io" } } });createMany, updateMany and deleteMany return { count }. Pass select to also get the
affected nodes as nodes, read in the same statement: the created nodes (in data order), the
nodes as updated, or the deleted nodes as they were before the delete. select takes the same
fields and relation loads as on findMany (include is not accepted: it would load every field of
every node):
const { count, nodes } = await db.user.updateMany({
where: { name: null },
data: { name: "anonymous" },
select: { id: true, email: true, _count: { select: { posts: true } } },
});
// count: 2, nodes: [{ id, email, _count: { posts } }, …]
const removed = await db.user.deleteMany({
where: { email: { endsWith: "@spam.io" } },
select: { email: true, posts: { select: { title: true } } }, // read before the delete
});Relation operations: create and connect (on create and update), plus disconnect and set
(to-many only) on update. set makes the listed nodes the only linked ones: edges to other nodes
are deleted, edges to the listed nodes are kept (and updated with their $edge) or created. On a
to-one relation, connect / create replace the existing edge.
connect is idempotent: it MERGEs the relationship, so connecting a pair that is already linked
keeps one edge. When the other side is declared to-one (connecting a post through user.posts
while Post.author is User?), connect moves the post: its edge to the previous author is
deleted in the same statement. Many-to-many relations are left alone. On a typed edge, $edge and the edge’s schema defaults are set when the edge is
created; on an existing edge only the $edge properties you pass are updated.
On connect and set, a number property of $edge also takes { increment, decrement, multiply },
applied by the same statement as the MERGE: to the current value on an existing edge (a missing
value counts as 0), to the schema default (or 0) on a new one. Counting co-occurrences is one
call per pair, safe under concurrent writes:
await db.entity.update({
where: { id: "ada" },
data: { related: { connect: { id: "babbage", $edge: { weight: { increment: 1 } } } } },
});
// … MERGE (a)-[r:RELATED_TO]->(b) ON CREATE SET r += $p4 SET r.weight = (coalesce(r.weight, $p0) + $p1)@min / @max on the edge property are checked on the value the update produces, as for node
fields (validation rules): a broken rule throws a CyphraValidationError and
the write (or the whole $transaction) is rolled back. create makes a new edge, so its $edge
takes values only.
upsert is one atomic MERGE on the unique key in where (ON CREATE SET the create data,
ON MATCH SET the update), then any nested relation writes of the branch it took. Concurrent
upserts of the same key yield one node as long as the key has a uniqueness constraint, which
@id / @unique / @@unique create through cyphra push or a migration. See
Upsert with MERGE.
Deleting
delete removes one node (by a unique key, NotFoundError when none matches) and returns it as it
was; deleteMany removes every match and returns { count } (and the deleted nodes as nodes
with a select, see Writing). Edges are removed with the node
(DETACH DELETE). onDelete rules in the schema decide what happens to
the linked nodes:
// schema: sessions Session[] @relationship(type: "HAS_SESSION", onDelete: Cascade)
// invoices Invoice[] @relationship(type: "BILLED", onDelete: Restrict)
try {
await db.user.delete({ where: { id } }); // deletes the user's sessions too
} catch (e) {
if (e instanceof RestrictError) console.log(e.model, e.relation, e.target, e.count);
// "User", "invoices", "Invoice", 2: nothing was deleted
}Cascadedeletes the linked nodes, then applies their own rules, recursively. Each node is visited once, so cycles (a node linked to itself, a ring of nodes) end.Restrictthrows aRestrictErrorwhile linked nodes exist, before anything is deleted, on the root nodes as well as on nodes a cascade reaches. Linked nodes that the same operation deletes (adeleteManymatching both ends, a cascade) do not count.SetNull, the default, only removes the edges.deleteManycounts the nodes itswherematched, not the cascaded ones.
Everything happens in the delete’s transaction (or your $transaction). The nodes are
write-locked before their edges are read: a concurrent write that links a new node to one of them
waits for the delete, so a cascade or a Restrict check never misses it. The whole delete is one
statement (lock, every cascade level, the Restrict checks, then the delete only if they pass)
unless a cascade path comes back to a model already on it or goes through an interface: then each
cascade level is one statement. A model with no rule (on itself or on the models its cascades
reach) is deleted in a single statement too.
A nested write runs in one statement (children created in batches, one per relation, and the
result read back in the same statement) and one write transaction: if any step fails (for
example a connect target does not exist) nothing is written.
Defaults from the schema are applied on create: cuid(), uuid(), now() and literals
(@default("draft"), @default(0), @default(true), an enum value, JSON text on a Json field,
ISO text on a temporal field).
Every write checks enum values (including nested creates, createMany, upsert and $edge
properties) and throws a CyphraValidationError before reaching Neo4j. On a BigInt field,
{ increment: 1n } (and decrement, multiply) takes a bigint. On a Json field, an object is
the new value, not an update: { settings: { increment: 1 } } stores that object.
Validation rules
Fields with validation rules (@length, @min, @email, …) are
checked on every write: create, createMany, update, updateMany, upsert (its create,
update and the key in where), nested create at any depth, and $edge properties of
create, connect and set. Every value is checked before the first statement is sent, so a
write that breaks a rule sends nothing to Neo4j, and the CyphraValidationError lists every
broken rule in issues:
// schema: User.name String @length(2, 40), User.email String @email,
// Post.title String @length(3, 100)
try {
await db.user.create({
data: {
name: "A",
email: "alice@example.com",
posts: { create: [{ title: "Hello graph" }, { title: "Hi" }] },
},
});
} catch (e) {
if (e instanceof CyphraValidationError) console.log(e.issues);
}
// [
// { path: ["data", "name"], model: "User", field: "name", rule: "length",
// message: "must be at least 2 characters long (got 1)." },
// { path: ["data", "posts", "create", 1, "title"], model: "Post", field: "title",
// rule: "length", message: "must be at least 3 characters long (got 2)." },
// ]pathleads to the value in the operation’s arguments: it starts withdata(create,update, …, and the row index forcreateMany), or withcreate,updateorwhereforupsert.ruleis the decorator name without@, andmessagesays what the value must be, ready to show next to a form field.nulland absent values break no rule. On create, an absent list counts as empty (it is stored empty), so@nonEmptyand@size(1, …)lists must be given.- Numeric operators (
increment,decrement,multiply) on a@min/@maxfield are checked against the value they produce, in the update statement itself: when the result is out of range nothing is updated (forupdateMany, no node is) and the error has one issue per field. This is the one case where a statement runs; it changes nothing. The same goes for operators on$edgeproperties ofconnectandset(pathends with"$edge", "<field>"): the write is rolled back.
Validating API input with zod
The client checks every write, but at an API boundary you usually want to reject bad input with a
400 before calling it, and to share the checks with a form. Configure the
zod generator and cyphra generate also writes cyphra.zod.ts:
{
"schema": "./schema.cyphra",
"migrations": "./migrations",
"generators": { "zod": { "output": "./src/cyphra.zod.ts", "coerce": true } }
}import { UserCreateInputSchema } from "@/cyphra.zod";
import { db } from "@/lib/db";
export async function POST(req: Request) {
const parsed = UserCreateInputSchema.safeParse(await req.json());
if (!parsed.success) {
// [{ path: ["name"], message: "must be at least 2 characters long.", … }]
return Response.json({ issues: parsed.error.issues }, { status: 400 });
}
const user = await db.user.create({ data: parsed.data });
return Response.json(user, { status: 201 });
}For each node model and each relationship model (its edge properties), the module exports:
| Schema | Accepts |
|---|---|
UserSchema | The properties the client returns: optional fields are null when unset, lists are arrays |
UserCreateInputSchema | Scalar data of a create: fields with a default, optional fields and lists may be left out |
UserUpdateInputSchema | Scalar data of an update: every field may be left out, optional fields may be null to remove them |
RoleSchema | One value of the enum (z.enum([...])) |
What they parse type-checks as the client’s data, and they check what the client checks:
- Every validation rule with the same semantics and messages:
@lengthcounts characters (Unicode code points, not UTF-16 units),@urltakes absolutehttp:/https:URLs only,@nonEmptyrefuses blank strings,@min/@maxare inclusive (aDatebound compares the UTC calendar day),@regexuses the pattern and flags of the schema. - Types: integers for
Int, the 64-bit range forBigInt(abigint),Dates forDateTimeandDate, ISO 8601 text forLocalDateTime,LocalTime,TimeandDuration(checked as the runtime parses it:"2023-02-29T10:00"and"24:00"are refused),{ longitude, latitude, height? }within range forPoint,{ x, y, z? }forCartesianPoint,Nfinite numbers forVector(N), any JSON value forJson. - Required fields: a create without
emailfails, and so does one without a@nonEmptylist (an absent list is stored empty).
JSON has no dates or bigints: with "coerce": true the schemas read ISO 8601 strings as Dates and
decimal strings as bigints ("2025-01-01T00:00:00Z", "42"), as you would send them from a
browser. Without it they expect Date and bigint values, for input that is already typed.
A public API rarely lets callers choose an id or a createdAt. With "omitGenerated": true the
create and update schemas leave out every field Cyphra generates (an @id with a @default, and
now(), cuid() and uuid() defaults), so no .omit({ id: true, createdAt: true }) is needed.
Relation fields are not part of the schemas (unknown keys are dropped). To accept a nested write,
extend the input schema, for example
UserCreateInputSchema.extend({ posts: z.object({ connect: z.array(z.object({ id: z.string() })) }).optional() }).
Numeric operators ({ increment: 1 }) are not accepted by the update schemas either.
The tRPC guide uses these schemas as procedure inputs and maps
CyphraValidationError and NotFoundError to tRPC error codes.
Transactions
await db.$transaction(async (tx) => {
const from = await tx.account.update({ where: { id: a }, data: { balance: { decrement: 10 } } });
if (from.balance < 0) throw new Error("insufficient funds"); // rolls everything back
await tx.account.update({ where: { id: b }, data: { balance: { increment: 10 } } });
});The driver may retry the callback on transient errors, so keep it free of outside side effects.
On an extended client, tx has the same hooks, computed fields and model methods.
Extensions
db.$extends({ query, result, model, client }) returns a new client with logic attached to
your models: hooks around operations, computed fields, custom model methods and client members.
The original client is unchanged, extensions compose (db.$extends(a).$extends(b)), and
everything stays typed: computed fields appear in result types, model methods return typed
results, hooks see the arguments of the operation they wrap.
Query hooks
A hook wraps one operation. It receives { model, operation, args, query, client }, can change
args, calls query(args) to run the operation (or skips it), and returns the result, changed
or not. Hashing a password before it is stored:
import { hash } from "@node-rs/argon2";
const xdb = db.$extends({
query: {
user: {
async create({ args, query }) {
return query({ ...args, data: { ...args.data, password: await hash(args.data.password) } });
},
async update({ args, query }) {
const { password } = args.data;
if (typeof password === "string") args.data.password = await hash(password);
return query(args);
},
},
},
});Hooks go per model and operation (user: { create }), on every operation of a model
(user: { $allOperations }), or on every model ($allModels: { findMany },
$allModels: { $allOperations }). In $allOperations, checking operation narrows args. Hooks
run from the first extension added to the last; within one extension, from the most general
($allModels.$allOperations) to the most specific (user.create). Events and spans keep the
name of the operation that was called (User.create).
Computed fields
result adds fields computed from others. needs lists the scalar fields compute reads (its
argument is typed with exactly those):
const xdb = db.$extends({
result: {
user: {
fullName: {
needs: { firstName: true, lastName: true },
compute: (u) => `${u.firstName} ${u.lastName}`,
},
},
},
});
const users = await xdb.user.findMany({ include: { posts: true } }); // users[0].fullName: string
const names = await xdb.user.findMany({ select: { id: true, fullName: true } }); // { id, fullName }[]Computed fields are added to every result of the model: without select, with include, on
nested relations (post.findMany({ include: { author: true } }) computes the author’s), and on
the nodes traverse, shortestPath, allShortestPaths, findSimilar and search return. They
can be selected: the fields in needs are then fetched even when select leaves them out, and
removed from the result. They are computed in JS once the rows are read, so they cannot be used in
where, orderBy, aggregate or groupBy, and are not on traverse’s path.nodes (scalar
fields only). On an interface, results have the interface’s computed
fields and (without select) their implementation’s. A computed field can shadow a scalar of the
same name; $allModels fields apply to every model, and a model’s own fields win.
Model methods
model adds methods to delegates. this is the extended delegate (with computed fields and the
other methods), plus this.$name (the model name) and this.$parent (the client):
const xdb = db.$extends({
model: {
user: {
findByEmail(email: string) {
return this.findUnique({ where: { email: email.toLowerCase() } });
},
},
$allModels: {
async exists(where: object) {
return (await this.count({ where })) > 0;
},
},
},
});
const ada = await xdb.user.findByEmail("Ada@Example.com"); // typed, with computed fieldsgetExtensionContext(this) (from cyphra) returns the same, typed: useful when a method is
written outside the $extends call.
Client members
client adds members to the client itself; this is the extended client:
const xdb = db.$extends({
client: {
async $health() {
const [row] = await this.$cypher<{ ok: number }>`RETURN 1 AS ok`;
return row?.ok === 1;
},
},
});Soft delete
Hooks can replace an operation. client in the hook params is the client the call was made on
(the transaction client inside $transaction), so the replacement runs in the same transaction:
const xdb = db.$extends({
name: "soft-delete",
query: {
post: {
delete({ args, client }) {
return client.post.update({ where: args.where, data: { deletedAt: new Date() } });
},
async $allOperations({ operation, args, query }) {
if (operation === "findMany" || operation === "findFirst" || operation === "count") {
return query({ ...args, where: { ...args.where, deletedAt: null } });
}
return query(args);
},
},
},
});Extensions in transactions
xdb.$transaction(async (tx) => …) hands an extended transaction client: hooks, computed fields
and model methods apply inside it (client members do not). A reusable extension is a function of
the client: const withSoftDelete = (c: Db) => c.$extends({ … }), applied with
db.$extends(withSoftDelete).
Raw Cypher
Cypher is never hidden. db.$cypher runs a parameterized tagged template and converts values to plain
JS (integers → number, temporals → Date, nodes → their properties):
const rows = await db.$cypher<{ name: string; n: number }>`
MATCH (u:User)-[:AUTHORED]->(p:Post) WHERE p.published = ${true}
RETURN u.name AS name, count(p) AS n ORDER BY n DESC
`;The low-level runtime (db.$client) and the query builder remain available.
Logging and tracing
createClient({ log: ["query", "warn", "error"] }) prints every statement with its duration, row
count and redacted parameters; db.$on("query", fn) subscribes to the same events, tracer adds
OpenTelemetry spans per operation and statement, and warnMissingIndexes: true (development only)
reports filters that scan a whole label. See Logging and tracing and
Missing index warnings.
The Cypher how-tos show common queries (upserts, pagination, counts) both ways.
Types and values
| Schema | TypeScript | Stored in Neo4j as |
|---|---|---|
String | string | String |
Int | number | Integer (64-bit; values outside the JS safe range throw on read) |
Float | number | Float |
Boolean | boolean | Boolean |
DateTime | Date | DateTime |
Date | Date (UTC midnight) | Date |
BigInt | bigint (-2^63 to 2^63-1) | Integer (64-bit, exact) |
Json | JsonValue (exported) | String (the value’s JSON text) |
enum Role | Role ("ADMIN" | "USER"), Role.ADMIN | String (checked against the enum on write) |
Vector(N) | number[] (length N, checked on write) | LIST<FLOAT> |
LocalDateTime | LocalDateTime ("2024-05-01T10:30:00") | LocalDateTime |
LocalTime | LocalTime ("10:30:00") | LocalTime |
Time | Time ("10:30:00+02:00") | Time (with its offset) |
Duration | Duration ("PT1H30M") | Duration |
Point | Point ({ longitude, latitude, height? }) | Point (WGS-84, SRID 4326 / 4979) |
CartesianPoint | CartesianPoint ({ x, y, z? }) | Point (Cartesian, SRID 7203 / 9157) |
T? | T | null | absent property |
T[] | T[] | List (absent reads as []) |
cyphra generate exports each enum as a const object and a union type of the same name:
import { Role, createClient } from "./cyphra.gen";
await db.user.create({ data: { email, role: Role.ADMIN } }); // or role: "ADMIN"
await db.user.findMany({ where: { role: { in: [Role.ADMIN, Role.EDITOR] } } });A Json field takes and returns any JsonValue (import type { JsonValue } from "cyphra"):
writes go through JSON.stringify (a Date becomes its ISO string; a bigint or a cycle throws),
reads through JSON.parse. null on a Json? field removes the property. BigInt values are read
as bigint whichever integer representation the driver returns (both neo4j-driver majors,
useBigInt or not); writes take a bigint (a safe-integer number is accepted too) and reject
values outside the 64-bit range.
The temporal types are ISO 8601 strings in JS (see Temporal types for
why): "2024-05-01T10:30:00", "10:30:00", "10:30:00+02:00", "PT1H30M". The generated types are
template literal types (import type { LocalTime, Duration } from "cyphra"), so a literal of the
wrong shape is a compile error; a string from elsewhere needs a cast (value as LocalTime), and
Cyphra validates the text on write. Reads return the Temporal API’s format (seconds always, no
trailing zeros in fractions, Z for offset 0, "PT1H30M" rather than "PT90M"), from either
neo4j-driver major. Points are plain objects: { longitude: 2.35, latitude: 48.85 }, with
height (or z) only for a 3D point.
DateTime values
Cyphra writes every DateTime (including @default(now()) and the values in where filters) at
UTC offset Z, whatever the time zone of the server process, and reads it back as a Date. The
offset matters in Cypher: = and < on datetimes take it into account, so the same instant stored
as 2023-12-31T19:00-05:00 is not = to 2024-01-01T00:00Z, and sorts just before it.
Versions before 0.3 used the local offset of the process that wrote the value. If your servers did
not run in UTC, such values still read back as the right Date and range filters still work, but
equals, in, and lte / gte on that exact instant will not match them. Rewrite them in UTC
once (per label and property):
MATCH (n:User) WHERE n.createdAt.offsetSeconds <> 0
SET n.createdAt = datetime({datetime: n.createdAt, timezone: "Z"})Errors
CyphraValidationError: unknown field or operator, wrong value type, missing required field, missing unique key, or values that break the schema’s validation rules. For the rules,issueslists every broken one as{ path, model, field, rule, message }(empty for the other cases).NotFoundError:update/delete/connect/findUniqueOrThrowtarget not found.RestrictError: adelete/deleteManyrefused by anonDelete: Restrictrule, withmodel,relation,targetandcount.UniqueConstraintError: a write that duplicates an@id,@uniqueor@@uniquevalue (see below).CyphraError(the base class of all four): for example anupsertwhosewherehas extra conditions that the existing node does not match.
Unique constraint errors
Neo4j enforces @id, @unique and @@unique with the uniqueness constraints that cyphra push
and migrations create. A write that breaks one throws a UniqueConstraintError instead of the
driver’s Neo.ClientError.Schema.ConstraintValidationFailed error, on Bolt and on the HTTP
transport. The transaction is rolled back, so nothing from the operation is written.
import { UniqueConstraintError } from "cyphra";
import { db } from "./db.js";
try {
await db.user.create({ data: { email: "ada@example.com" } });
} catch (e) {
if (e instanceof UniqueConstraintError && e.fields.includes("email")) {
// e.model === "User", e.constraint === "User_email_unique"
throw new Error("This email is already registered.");
}
throw e;
}| Property | Value |
|---|---|
model | Model that declares the constraint: the node model of the label, the interface for a field or @@unique declared on an interface, or the relationship { … } model. undefined for a label the schema does not have. |
fields | Constrained fields, in the constraint’s order (["tenantId", "email"] for @@unique([tenantId, email])). |
constraint | Constraint name as cyphra push creates it (User_email_unique, User_id_id, a @@unique name), or undefined when the schema does not declare it. |
code | The Neo4j code, Neo.ClientError.Schema.ConstraintValidationFailed. |
gqlStatus | The GQL status when the server sends one (22N79 on Neo4j 2025+). |
cause | The original error: a Neo4jError (Bolt) or a Neo4jHttpError (HTTP). |
The message names the model, fields and constraint, never the duplicate value (that stays in
cause.message). Every write throws it: create, createMany, update, updateMany, upsert
(when its create branch hits another unique field), nested create, $edge properties with a
relationship @unique, and raw $cypher statements, also inside
$transaction (catch it there, or around the $transaction call). The error
event of the failing statement still carries the Neo4j code. Errors from
db.$client (sessions you run yourself) and from @cyphra/graphql are left as Neo4j raises them.
Field names, labels and relationship types always come from your schema and unknown keys are rejected, so arguments cannot inject Cypher. Every value is sent as a parameter.