Schema DSL
Your graph lives in one file, schema.cyphra: its nodes, the relationships between them and the
decorators that become Neo4j constraints and indexes. The CLI, the typed client and migrations all
read it.
node User {
id String @id @default(cuid())
email String @unique
name String @index
following User[] @out(FOLLOWS)
}
node Post {
id String @id
title String
author User? @in(AUTHORED)
}
relationship FOLLOWS {
since DateTime @index
requestId String @unique
}Scalar types
Append ? for optional (String?) or [] for a list (String[]). Lists are never optional; an
absent list reads as [].
| Type | Neo4j property | TypeScript |
|---|---|---|
String | STRING | string |
Int | INTEGER | number (safe integers only) |
BigInt | INTEGER | bigint (full 64-bit range) |
Float | FLOAT | number |
Boolean | BOOLEAN | boolean |
DateTime | ZONED DATETIME | Date |
Date | DATE | Date |
Json | STRING (JSON) | JsonValue |
an enum name | STRING | the enum’s union of values |
Vector(N) | LIST<FLOAT> | number[] (see below) |
LocalDateTime | LOCAL DATETIME | LocalDateTime: ISO text, "2024-05-01T10:30:00" |
LocalTime | LOCAL TIME | LocalTime: ISO text, "10:30:00" |
Time | ZONED TIME | Time: ISO text with offset, "10:30:00+02:00" |
Duration | DURATION | Duration: ISO text, "P1DT2H30M" |
Point | POINT (WGS-84) | Point: { longitude, latitude, height? } |
CartesianPoint | POINT (Cartesian) | CartesianPoint: { x, y, z? } |
BigIntholds 64-bit integers (counters, external ids) from -2^63 to 2^63-1, read and written as JSbigintwith no precision loss.Intuses the same Neo4j type but reads as a JSnumber, and throws on a value beyondNumber.MAX_SAFE_INTEGER. BigInt fields sort, filter withlt/gt/inand aggregate like numbers:_sumis abigint,_avganumber.@default(0)and@default(9223372036854775807)keep every digit.Jsonholds any JSON value (object, array, string, number, boolean). It is stored as its JSON text, a string property: writesJSON.stringifythe value, reads parse it back. AJson?set tonullremoves the property, so a JSONnullcannot be stored apart from “absent”. Json fields filter onnull,{ equals: value }and{ not: value }only (the whole stored text is compared, key order included; there are no queries into the value), cannot be sorted, and take no@id,@uniqueor@index.Json[]is not supported: use aJsonholding an array. A default is a string of JSON text:@default("{}").- Enums are declared once and used as a type (see Enums).
- Temporal types and points are described in Temporal types and Spatial points.
Temporal types
Besides DateTime (an instant, a JS Date, stored at UTC) and Date, Cyphra has the other Neo4j
temporal types:
node Shop {
id String @id
opens LocalTime @default("09:00")
closes LocalTime?
slot Time?
updated LocalDateTime @default(now())
delivery Duration @default("PT45M")
}| Type | Holds | Example value | Sorts, lt / gt, _min / _max |
|---|---|---|---|
LocalDateTime | a date and wall-clock time, no time zone | "2024-05-01T10:30:00" | yes |
LocalTime | a wall-clock time, no time zone | "10:30:00", "08:15:30.5" | yes |
Time | a time of day with a UTC offset | "10:30:00+02:00", "10:30:00Z" | yes (by the UTC instant) |
Duration | an amount of months, days and seconds | "PT1H30M", "P1Y2M", "-P3D" | no: equality and in only |
- JS values are ISO 8601 strings, with a precision of up to nanoseconds. Neo4j stores (and
compares, sorts and indexes) temporal values, not strings: Cyphra converts on every write and
read. Strings fit JSON and HTTP as is, carry the full precision (a JS
Datestops at milliseconds, and aDatefor a value without a time zone invites time-zone bugs), and need no runtime dependency. Values come back in the form of theTemporalAPI’stoString(), soTemporal.PlainTime.from(shop.opens)orTemporal.Duration.from(shop.delivery)work whereTemporalis available. - Typed strings.
cyphra generatetypes these fields with template literal types exported fromcyphra(LocalTimeis`${number}:${number}${string}`,Durationis`P${string}`), so a literal of the wrong shape is a compile error. Astringfrom elsewhere (a request body) needs a cast,opens: body.opens as LocalTime; Cyphra validates it on write either way and throws aCyphraValidationErrorfor text that is not valid ISO 8601. - No time-zone conversion.
LocalDateTimeandLocalTimeare stored exactly as written. ATimekeeps its offset; Neo4j compares and sorts times by their UTC instant ("11:00+01:00"sorts after"09:00Z"). Write the same offset everywhere if you filter withequals. - Durations keep months, days and seconds apart, as Neo4j does:
"P1D"is not equal to"PT24H"(a day is not always 24 hours), and"PT90M"is stored and returned as"PT1H30M". Durations have no total order, so they filter withequals,not,inandnotInonly, and do not sort or aggregate with_min/_max. - Defaults.
@default(now())works onLocalDateTime,LocalTimeandTime: the current UTC wall-clock time (Timeat offsetZ), the same as Cypher’slocaldatetime()/localtime()/time()with Neo4j’s default time zone. All four types take an ISO text default:@default("09:00"),@default("PT45M"), normalized to the form the client returns.
Spatial points
node Place {
id String @id
name String
location Point @index
floor CartesianPoint?
}Pointis a WGS-84 geographic point:{ longitude, latitude }in degrees, with an optionalheightin meters (a 3D point).CartesianPointis a point in a plane or space:{ x, y }, or{ x, y, z }, in your own units. Both are Neo4jPOINTvalues (SRID 4326 / 4979 and 7203 / 9157), and the JS typesPointandCartesianPointare exported fromcyphra. Two types instead of one type with a CRS option keep the field’s JS shape fixed, and match@neo4j/graphql’sPointandCartesianPoint.- Writes are checked: finite coordinates, longitude in [-180, 180] and latitude in [-90, 90].
A field accepts 2D and 3D points; distances between a 2D and a 3D point are
nullin Neo4j, so they never match a distance filter. @indexon a point field creates aPOINTindex (instead of a range index), which serves distance and bounding-box queries.- Queries: equality, distance from a point (meters for
Point), within a bounding box, and sorting by distance. See Spatial queries. Point[]lists are supported (no index, and no distance filter on a list).
Enums
enum Role {
ADMIN
EDITOR
VIEWER
}
node User {
id String @id @default(cuid())
role Role @default(VIEWER)
roles Role[]
level Role?
}- Values are identifiers, separated by whitespace or commas (
enum Level { LOW, HIGH }), and are stored as strings ("ADMIN"), so existing string data can become an enum without conversion. An enum cannot reuse a built-in type name or the name of a node or relationship model. - Usage. An enum name is a field type on nodes and relationship properties:
Role,Role?,Role[].@default(VIEWER)must name one of its values (lists take no default). - Typed client.
cyphra generateemits a const object and a union type per enum:Role.ADMIN === "ADMIN",type Role = "ADMIN" | "EDITOR" | "VIEWER". Every write (create, nested create,createMany,update,updateMany,upsert, edge properties) rejects a value outside the enum before reaching Neo4j. Filters areequals,not,inandnotIn, typed to the enum (list fields takehas,hasSome,hasEvery,isEmpty); enum fields sort as strings. - Migrations. Enums need no DDL.
cyphra migratewarns when a value is removed, with a query that finds the nodes still holding it, since they would no longer read as the enum.cyphra pullcannot tell an enum, aJsonor aBigIntfrom aString/Intproperty: change those types by hand after pulling.
Vector fields
Vector(N) is an embedding of N floats, from 1 to 4096 (the limit of Neo4j 5 vector indexes).
@vectorIndex declares the vector index that findSimilar searches:
node Chunk {
id String @id @default(cuid())
text String
embedding Vector(1536)? @vectorIndex(similarity: cosine)
document Document? @out(PART_OF)
}- Stored as
LIST<FLOAT>, typednumber[]in the client (number[] | nullwhen optional). Writes check the length:[0.1, 0.2]on aVector(1536)field throws before reaching Neo4j. Make the field optional if embeddings are computed after the node is created. @vectorIndex(similarity: cosine | euclidean, name: "…", quantization: true | false). All arguments are optional:similaritydefaults tocosineandnameto<Label>_<field>_vector.quantizationsetsvector.quantization.enabled(Neo4j 5.23+; when left out, Neo4j’s default applies, which is on: smaller index, slightly approximate scores).cyphra pushand migrations create the index withCREATE VECTOR INDEX, setting its dimensions and similarity function (Neo4j 5.15+).- A vector field takes no other decorator, cannot be sorted, and filters only on
null({ embedding: null },{ embedding: { not: null } }). Vectors are supported on node models, not on relationship properties.
Full-text indexes
A full-text index spans one or more text fields of a model, so it is declared on the model with a
model attribute: a line starting with @@ inside the node block, usually after the fields.
@@fulltext declares the index that search queries:
node Post {
id String @id @default(cuid())
title String
body String?
tags String[]
@@fulltext([title, body], name: "postSearch", analyzer: "english")
@@fulltext([tags], analyzer: "keyword")
}- Fields. The leading list names
StringorString[]fields of the model (each value of a list is indexed). It cannot be empty or name a field twice. name: "…"defaults to<Label>_<field>_<field>…_fulltext(Post_tags_fulltextabove). Index and constraint names share one namespace in Neo4j, so the schema rejects a name already taken by another full-text or vector index, or by a constraint or range index the schema implies.analyzer: "…"setsfulltext.analyzer: how text is split into terms, lower-cased, stemmed and filtered. When left out, Neo4j’s default applies,standard-no-stop-words. The schema accepts the built-in analyzers of Neo4j 5 (CALL db.index.fulltext.listAvailableAnalyzers()):standard,standard-folding(also folds accents),simple,whitespace,keyword(the whole value is one token: tags, codes),email,url,url_or_email,classic,stop,unicode_whitespace,cjkand the language analyzers (english,french,german,spanishand 30 others, which stem words and drop stop words). The list is exported asFULLTEXT_ANALYZERS.eventuallyConsistent: true | falsesetsfulltext.eventually_consistent(defaultfalse). An eventually consistent index is updated in the background after commit: writes are faster, but a search right after a write can miss it.cyphra pushand migrations create the index withCREATE FULLTEXT INDEX. Full-text indexes are supported on node models, not on relationships.
Model attributes are a general syntax, @@name([fields], key: value, …): @@fulltext, and
@@unique / @@index below.
Composite constraints and indexes
@unique and @index cover one field. When uniqueness or a lookup spans several fields (a
provider and an account id, a tenant and an email), declare it on the model with @@unique or
@@index:
node Account {
id String @id @default(cuid())
providerId String
accountId String
tenant String
email String
createdAt DateTime @default(now())
@@unique([providerId, accountId])
@@unique([tenant, email], name: "tenantEmail")
@@index([tenant, createdAt])
}@@unique([a, b])is a composite uniqueness constraint (CREATE CONSTRAINT … REQUIRE (n.a, n.b) IS UNIQUE): no two nodes of the label share the same values for all the fields. It works on Neo4j Community and Enterprise. A node that lacks one of the fields (an optional field leftnull) is not constrained. Cyphra does not create aNODE KEY(a uniqueness constraint that also requires every field), because node keys need Neo4j Enterprise Edition.@@index([a, b])is a composite range index (CREATE RANGE INDEX … ON (n.a, n.b)). Neo4j uses it for queries that filter on all its fields, so the order of the fields matters.- Fields. At least two, each a scalar field of the model that holds one value: no relations,
no lists, no
Jsonand noVector(N)fields, none listed twice. For one field, use@uniqueor@indexon the field. name: "…"is the constraint or index name. It defaults to<Label>_<field>_<field>…_unique(Account_providerId_accountId_unique) or…_idx. Like every index and constraint name, it must be unique across the schema.- Each
@@uniqueis also a key forfindUnique,upsert,connectand the other operations that take a uniquewhere:{ providerId_accountId: { providerId, accountId } }, the fields joined by_. With aname, the key is the name ({ tenantEmail: { tenant, email } }), so it must not clash with a field of the model. - The schema rejects two
@@uniqueover the same fields (in any order), two identical@@indexand a@@indexwith the same fields, in the same order, as a@@unique(its constraint already has that index). cyphra pushand migrations create them;cyphra pullreads composite uniqueness constraints, node keys and composite range indexes back as@@uniqueand@@index. They are supported on node models, not on relationships.
Defaults
@default(cuid()), @default(uuid()) (String), @default(now()) (DateTime, Date, LocalDateTime,
LocalTime, Time), or a literal matching the field type: @default("draft"), @default(0),
@default(1.5), @default(true), an enum value (@default(VIEWER)), JSON text on a Json field
(@default("[]")), ISO text on a temporal field (@default("09:00"), @default("PT45M")). Point
fields take no default.
The typed client applies them on create.
Validation rules
Rules say what a value must look like beyond its type. They live next to the field, so the schema stays the one place that defines your data:
node User {
id String @id @default(cuid())
email String @unique @email
name String @length(2, 40) @nonEmpty
handle String? @regex("^[a-z0-9_]+$", "i")
website String? @url
age Int? @min(13) @max(130)
born Date? @min("1900-01-01")
tags String[] @size(max: 10)
}| Rule | Fields | The value must be … |
|---|---|---|
@length(min, max) | String | from min to max characters long, counted in Unicode code points. |
@size(min, max) | lists (String[], Int[], …) | a list of min to max elements. |
@min(value), @max(value) | Int, Float, BigInt, DateTime, Date | at least / at most value, inclusive. |
@email | String | an email address (local@domain.tld). |
@url | String | an absolute http: or https: URL. |
@regex(pattern, flags) | String | a string the JavaScript regular expression matches. |
@nonEmpty | String, lists | a string with something other than whitespace, or a list with an element. |
- Arguments are positional or named:
@length(3, 20)is@length(min: 3, max: 20), and@length(max: 280)sets only a maximum.@sizeworks the same way. - Bounds are inclusive. On
Int/Float/BigIntthey are numbers (@min(-1.5),@max(9223372036854775807)); onDateTimeandDatethey are ISO 8601 strings (@min("2020-01-01"),@max("2100-01-01T00:00:00Z")). @regexuses JavaScript syntax and matches anywhere in the string: anchor it with^…$to match the whole value. A backslash is written\\inside a.cyphrastring (@regex("^\\d+$")). The optional flags are amongi,m,sandu.- Absent and
nullvalues break no rule (use a required type to demand a value). A list that is not given on create is stored empty, so@nonEmptyor@size(1, …)on a list makes it required in practice. - Checked at schema time: a rule on a type it does not fit (
@minon aString,@lengthon a list), a wrong argument (@length(-1),@min(1.5)on anInt),minabovemax, a regex that does not compile and a@defaultthat breaks the field’s rules are validation errors incyphra validateand in the editor.
The typed client checks the rules on every write (create,
createMany, update, updateMany, upsert, nested create, $edge properties) before it
sends anything to Neo4j, and reports every broken rule at once. cyphra validate --verbose lists
the rules of the schema, and the generated types show them in each field’s doc comment. Rules
need no DDL: cyphra migrate dev notes rule changes without a step, and existing data is not
re-checked. They are enforced by the Cyphra client only: raw Cypher writes skip them.
Relationships
A relation field lives in the node you read it from (user.posts) and names the edge type with
@out(TYPE) (edges going out of this node) or @in(TYPE) (edges coming in). The target type
gives the cardinality: Post[] is to-many, User? an optional to-one, User a required to-one.
node User {
id String @id
posts Post[] @out(AUTHORED) // (user)-[:AUTHORED]->(post)
}
node Post {
id String @id
title String
author User? @in(AUTHORED) // the same edges, read from the post
}
relationship AUTHORED { // only when the edge has properties
at DateTime @default(now())
}- The type is a symbol, defined once.
AUTHOREDis the Neo4j relationship type as written (UPPER_SNAKE by convention). Arelationship AUTHORED { … }block types the properties of every:AUTHOREDedge ($edgein the client); without a block the edge has no properties. - One side is enough.
User.postsalone givesuser.postsin the client and writes the edges; addPost.authoronly if you also read the relation from the post. The two sides are the same edges: write either one. - Options go in the same call:
posts Post[] @out(AUTHORED, onDelete: Cascade)(see onDelete rules). - Self-relationships use the same type on both sides:
following User[] @out(FOLLOWS)andfollowers User[] @in(FOLLOWS). - The target can be a node, an interface or a union.
Edge or node?
An edge can carry properties (at, role, weight), but not relationships of its own: nothing
can point at an :AUTHORED edge. When the thing you are modelling needs its own relations (an
Order with line items and a shipping address, a Membership that has an approver, a Review
that others can like), make it a node with an edge to each side:
node Membership {
id String @id @default(cuid())
role String
user User @in(HAS_MEMBERSHIP)
team Team @out(MEMBERSHIP_IN)
approver User? @in(APPROVED)
}Keep it an edge while it only describes the link between two nodes.
Validation
cyphra validate and cyphra generate (and the editor) check relation fields:
- A pair with the same direction on both sides is an error.
posts Post[] @out(AUTHORED)onUserandauthor User? @out(AUTHORED)onPostdescribe two different sets of edges (User → PostandPost → User); one of them is meant to be@in(AUTHORED). Both directions stay allowed when each side has its inverse too. - A
relationshipblock that no field uses is an error: usually a misspelled type, on the block or on the fields. - Nearly identical types are a warning (
AUTHOREDandAUTHORD, orFOLLOWSandFollows: one or two characters apart, or differing only in case). They are different types to the database, so a typo silently creates unrelated edges.
The @relationship syntax
The older form keeps working, and resolves to the same model and the same generated client:
node User {
id String @id
posts Post[] @relationship(type: "AUTHORED", direction: OUT)
}direction defaults to OUT. It is also how to write a type that is not an identifier
(@relationship(type: "HAS-TAG", direction: OUT)). A field uses one form: @out(…) together
with @relationship(…) (or @out with @in) is an error. To move a schema to @out / @in, run
cyphra format --codemod (the editor offers the same as a quick fix, field by field); plain
cyphra format keeps the syntax you wrote and only says how many fields it would rewrite.
Long-form relationship blocks
A block can also name its type and ends, and be named differently from its type:
relationship Wrote {
type "AUTHORED"
from User
to Post
at DateTime @default(now())
}It types the :AUTHORED edges from a User to a Post only (an end may be an interface or a
union), and the client calls the model Wrote. Use it when one type links different pairs of
nodes with different properties (one long-form block per pair), or when the type is not an
identifier. The short form relationship AUTHORED { … } types every :AUTHORED edge: its ends
are those of the fields (if the fields link unrelated pairs, User → Post and Team → Post,
it is an error; point them at a shared interface or union, or use long-form blocks). A type has
either one short-form block or long-form ones, not both. Fields with @out / @in and fields
with @relationship match both forms.
onDelete rules
onDelete says what deleting a node does to the nodes a relation field links it to. The rule
belongs to the field’s own model: on User.sessions it means “when a User is deleted, its
sessions are …”.
node User {
id String @id @default(cuid())
sessions Session[] @out(HAS_SESSION, onDelete: Cascade)
invoices Invoice[] @out(BILLED, onDelete: Restrict)
reviews Post[] @out(REVIEWED) // SetNull
}
node Session {
id String @id @default(cuid())
user User @in(HAS_SESSION)
}| Rule | Deleting a User … |
|---|---|
Cascade | deletes its sessions too, applying the sessions’ own rules (chains and cycles are fine). |
Restrict | fails with a RestrictError while the user still has invoices; nothing is deleted. |
SetNull | the default: the REVIEWED edges are removed and the posts stay, with no reviewer. |
- Rules apply to
deleteanddeleteManyof the typed client, in the same transaction as the delete. A rule is allowed on to-one and to-many fields,OUTorIN. - Each side of a relation has its own rule, for deletes of its own model:
Session.userabove keeps the default, so deleting a session never touches its user. PuttingonDelete: Cascadeon both sides is allowed and deletes the whole connected group, whichever end you delete. - Two fields of one model on the same edges (same type, direction and target) must agree; different rules are a validation error.
- Rules need no DDL:
cyphra migrate devnotes rule changes but generates no step for them. They are enforced by the Cyphra client only: a raw CypherDETACH DELETEignores them.
Interfaces and multiple labels
A node often belongs to several kinds at once: an employee and a customer are both people. Declare
the shared part as an interface and let nodes implement it:
interface Person {
id String @id @default(cuid())
email String @unique
name String
manager Person? @in(MANAGES)
@@fulltext([name])
}
node Employee implements Person {
salary Int @default(0)
}
node Customer implements Person {
tier String @default("free")
}-
Labels. An interface is a label named like it. A node carries its own label and the label of every interface it implements: Cyphra writes an
Employeeas(:Employee:Person)and matches it on both labels. An interface is abstract: it can be queried (db.person.findMany()returns every employee and customer) but never created. -
Inherited fields.
node X implements A, Bgets every field ofA, then ofB, before its own fields: scalars, relations, and their decorators.Employeeabove hasid,email,name,managerandsalary. Model attributes of the node can name inherited fields (@@unique([email, salary])). -
The body of an interface is the body of a node: scalar and relation fields,
@@unique,@@indexand@@fulltext. Relations can target an interface (manager Person?,members Person[]), and arelationship { … }model can name one infrom/to. -
Constraints and indexes are created once, on the label that declares them.
@uniqueonPerson.emailis one constraint,Person_email_unique, on:Person: an email is unique across employees and customers. Implementations get no copy. An inherited@@uniquestays a unique key of the implementation, and an inherited@@fulltextor@vectorIndexcan be searched from the implementation (db.employee.search(…)keeps the nodes labelled:Employee). -
Extra labels. An interface without fields is just a label that its implementations carry:
interface Archivable {} node Document implements Archivable { id String @id }
Interfaces extending interfaces
An interface can extend other interfaces: it inherits their fields, and its implementations carry every label up the chain.
interface Staff extends Person {
badge String @unique
team Team? @out(MEMBER_OF)
}
interface Contact extends Person {
phone String?
}
node Engineer implements Staff, Contact {
level Int @default(1)
}- An
Engineeris written as(:Engineer:Staff:Person:Contact).db.staffreturns engineers (and any otherStaffimplementation),db.personreturns everything belowPerson. - Fields come first from the interfaces, in order (
StaffinheritsPerson’s fields before its own). A field reached twice through two interfaces extending the same one (Person.emailviaStaffandContact, a “diamond”) is inherited once. - Constraints and indexes stay on the label that declares them:
Person_email_uniquecovers everyStaffandContactnode;Staff_badge_uniqueis on:Staff. - A node
implementsinterfaces and an interfaceextendsthem:interface X implements Yandnode X extends Yare errors.
Validation
These are validation errors: implementing or extending something that is not an interface (or the
same one twice), an interface extending itself (directly or through others), redeclaring an
inherited field, two interfaces declaring the same field (unless one inherits it from the other),
and more than one @id across a node and its interfaces.
Migrations add the interface labels to existing nodes when a
node starts implementing an interface (or one of its interfaces starts extending another), and
cyphra pull recognizes shared labels as interfaces, including chains of
labels as interfaces extending interfaces.
Not planned
- Narrowing an inherited field on an implementation (an optional
Person.biorequired onEmployee, or an enum field restricted to some values). An update through the interface (db.person.updateMany({ data: { bio: null } })) would have to check every node against its implementation’s version of the field, so the schema could not guarantee it. Declare the field on each implementation instead of on the interface. - Interfaces in
@cyphra/graphql.@neo4j/graphqlv7 interfaces add no label (aMovieimplementingProductionis stored as(:Movie)), so they have no exact Cyphra equivalent. The importer maps one to a Cyphra interface when its implementations also carry its name in@node(labels), or when you accept to add the label (--add-interface-labels).
Models that share nothing (the hits of a search box, the target of a polymorphic relation) are a union rather than an interface.
Unions
A union groups node models that share no field and no label:
union SearchHit = Post | User | Comment
node Board {
id String @id @default(cuid())
items SearchHit[] @out(SHOWS, onDelete: Cascade)
}
node Pin {
id String @id @default(cuid())
subject SearchHit? @out(PINS)
}- A type, not a label. Nothing is written for a union: a
Poststays(:Post). A union is matched by a label predicate over its members (WHERE n:Post OR n:User OR n:Comment), so adding or removing one needs no migration and creates no constraint or index. - Relation targets. Relation fields can target a union (
items SearchHit[],subject SearchHit?), withonDeleterules like any relation:Cascadedeletes each related node with the rules of the model it is. - Querying.
db.searchHitreads every member (findMany,findFirst,count), results discriminated by__typename. There is no unique key and no field to filter on, so filters and per-member loads go through__typenameand$on. - Members are
nodemodels or interfaces, listed once, with an optional leading|when the list spans lines (union SearchHit =then| Poston the next lines). Another union, an enum or a relationship model is a validation error, and so is a node listed twice (directly and through an interface it implements, or through two interfaces). - Interface members.
union Party = Person | Team, withinterface Person, stands for every node implementingPerson(today’s and future ones): it is matched by the interface’s label (WHERE n:Person OR n:Team), results are the implementations (__typenameis"Employee","Customer"or"Team", never"Person"), and writes and$onmay namePersonto address every implementation at once (see the client). - Typed edges. A
relationship { … }model may name a union infromorto: one edge model for every member, used by the relation to the union and by the members’ inverse fields. Relationship property constraints and indexes are per relationship type, so the DDL is the same as for a node end.
node Board {
id String @id @default(cuid())
picks SearchHit[] @out(PICKS)
}
relationship Pick {
type "PICKS"
from Board
to SearchHit
rank Int @default(0)
}cyphra pullcannot infer unions (a union adds no label): it keeps one relation per target label; declare the union by hand. The GraphQL importer reports@neo4j/graphqlunions as not converted yet.- It works the same on Memgraph and FalkorDB: label predicates are plain openCypher.
Dynamic labels
Graphs often use labels as flags that come and go on single nodes: :Archived, :Featured,
:Deleted. Declare the ones a model may carry with @@labels([…]):
node Post {
id String @id @default(cuid())
title String
@@labels([Archived, Featured])
}- Typed and checked. The client adds, removes and filters on them
(
data: { $labels: { add: ["Archived"] } },where: { $labels: { has: "Featured" } }), typed as"Archived" | "Featured". A label that is not in the list is aCyphraValidationErrorbefore anything runs: label names in the generated Cypher always come from the schema, never from a value. - Not part of the model.
db.postmatches every:Post, with or without the flags; a flag is never required. A dynamic label cannot be the label of a node or an interface (a node carrying it would also be that model): useimplementsfor labels every node of the model carries. - Shared names. Several models may declare the same label (
:Archivedon posts and users). On an interface,@@labelsapplies to every implementation too, anddb.<interface>can filter and write them; an implementation can declare more of its own. - No DDL.
@@labelscreates no constraint or index, and migrations need no step to add one. Label lookups (MATCH (n:Archived)) use Neo4j’s default token lookup index. To index a property of flagged nodes, index it on the flag’s label (an index covers one label) in a hand-written migration:CREATE INDEX Archived_archivedAt IF NOT EXISTS FOR (n:Archived) ON (n.archivedAt). Uniqueness among flagged nodes only cannot be declared either; a constraint on:Archivedwould also cover the other models declaring it. - It works the same on Memgraph and FalkorDB: plain
SET n:Label/REMOVE n:Labeland label predicates.
cyphra pull recognizes labels found on some nodes of a model only, with no
property or constraint of their own, as dynamic labels.
Decorators
@id, @unique, @vectorIndex(…) (on Vector(N) fields, see above), @@fulltext([…]), @@unique([…]), @@index([…]) and @@labels([…]) (model attributes, see above), @index (Neo4j 5+ range index, or a point index on a Point / CartesianPoint field: on nodes via (n:Label), on rich relationships via ()-[r:TYPE]-()), @default(…), @out(…) / @in(…) (and the older @relationship(…), see Relationships), and the validation rules @length, @size,
@min, @max, @email, @url, @regex and @nonEmpty. On nodes, you cannot combine @index with @id or @unique on the same field (those constraints already imply an index). On relationship models, @unique maps to a relationship property uniqueness constraint (Neo4j 5.7+); @id is not allowed on relationship fields.
Programmatic API
parseSchema, parseSchemaFile and printSchemaDocument are exported from cyphra (or
@cyphra/schema). parseSchemaFile(path) loads a UTF-8 .cyphra file from disk (Node.js).
The parser produces an AST used by cyphra push, cyphra generate, and programmatic APIs. Use printSchemaDocument from @cyphra/schema (or cyphra schema print) to emit a canonical .cyphra text for diffs and reviews—comments are not preserved. To reformat a schema and keep its comments, use formatSchema (or cyphra format). For editor support (VS Code, Neovim, Helix), see Editor.