Skip to Content
Schema

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 [].

TypeNeo4j propertyTypeScript
StringSTRINGstring
IntINTEGERnumber (safe integers only)
BigIntINTEGERbigint (full 64-bit range)
FloatFLOATnumber
BooleanBOOLEANboolean
DateTimeZONED DATETIMEDate
DateDATEDate
JsonSTRING (JSON)JsonValue
an enum nameSTRINGthe enum’s union of values
Vector(N)LIST<FLOAT>number[] (see below)
LocalDateTimeLOCAL DATETIMELocalDateTime: ISO text, "2024-05-01T10:30:00"
LocalTimeLOCAL TIMELocalTime: ISO text, "10:30:00"
TimeZONED TIMETime: ISO text with offset, "10:30:00+02:00"
DurationDURATIONDuration: ISO text, "P1DT2H30M"
PointPOINT (WGS-84)Point: { longitude, latitude, height? }
CartesianPointPOINT (Cartesian)CartesianPoint: { x, y, z? }
  • BigInt holds 64-bit integers (counters, external ids) from -2^63 to 2^63-1, read and written as JS bigint with no precision loss. Int uses the same Neo4j type but reads as a JS number, and throws on a value beyond Number.MAX_SAFE_INTEGER. BigInt fields sort, filter with lt / gt / in and aggregate like numbers: _sum is a bigint, _avg a number. @default(0) and @default(9223372036854775807) keep every digit.
  • Json holds any JSON value (object, array, string, number, boolean). It is stored as its JSON text, a string property: writes JSON.stringify the value, reads parse it back. A Json? set to null removes the property, so a JSON null cannot be stored apart from “absent”. Json fields filter on null, { 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, @unique or @index. Json[] is not supported: use a Json holding 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") }
TypeHoldsExample valueSorts, lt / gt, _min / _max
LocalDateTimea date and wall-clock time, no time zone"2024-05-01T10:30:00"yes
LocalTimea wall-clock time, no time zone"10:30:00", "08:15:30.5"yes
Timea time of day with a UTC offset"10:30:00+02:00", "10:30:00Z"yes (by the UTC instant)
Durationan 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 Date stops at milliseconds, and a Date for a value without a time zone invites time-zone bugs), and need no runtime dependency. Values come back in the form of the Temporal API’s toString(), so Temporal.PlainTime.from(shop.opens) or Temporal.Duration.from(shop.delivery) work where Temporal is available.
  • Typed strings. cyphra generate types these fields with template literal types exported from cyphra (LocalTime is `${number}:${number}${string}`, Duration is `P${string}`), so a literal of the wrong shape is a compile error. A string from elsewhere (a request body) needs a cast, opens: body.opens as LocalTime; Cyphra validates it on write either way and throws a CyphraValidationError for text that is not valid ISO 8601.
  • No time-zone conversion. LocalDateTime and LocalTime are stored exactly as written. A Time keeps 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 with equals.
  • 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 with equals, not, in and notIn only, and do not sort or aggregate with _min / _max.
  • Defaults. @default(now()) works on LocalDateTime, LocalTime and Time: the current UTC wall-clock time (Time at offset Z), the same as Cypher’s localdatetime() / 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? }
  • Point is a WGS-84 geographic point: { longitude, latitude } in degrees, with an optional height in meters (a 3D point). CartesianPoint is a point in a plane or space: { x, y }, or { x, y, z }, in your own units. Both are Neo4j POINT values (SRID 4326 / 4979 and 7203 / 9157), and the JS types Point and CartesianPoint are exported from cyphra. Two types instead of one type with a CRS option keep the field’s JS shape fixed, and match @neo4j/graphql’s Point and CartesianPoint.
  • 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 null in Neo4j, so they never match a distance filter.
  • @index on a point field creates a POINT index (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 generate emits 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 are equals, not, in and notIn, typed to the enum (list fields take has, hasSome, hasEvery, isEmpty); enum fields sort as strings.
  • Migrations. Enums need no DDL. cyphra migrate warns 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 pull cannot tell an enum, a Json or a BigInt from a String / Int property: 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>, typed number[] in the client (number[] | null when optional). Writes check the length: [0.1, 0.2] on a Vector(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: similarity defaults to cosine and name to <Label>_<field>_vector. quantization sets vector.quantization.enabled (Neo4j 5.23+; when left out, Neo4j’s default applies, which is on: smaller index, slightly approximate scores).
  • cyphra push and migrations create the index with CREATE 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 String or String[] 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_fulltext above). 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: "…" sets fulltext.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, cjk and the language analyzers (english, french, german, spanish and 30 others, which stem words and drop stop words). The list is exported as FULLTEXT_ANALYZERS.
  • eventuallyConsistent: true | false sets fulltext.eventually_consistent (default false). 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 push and migrations create the index with CREATE 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 left null) is not constrained. Cyphra does not create a NODE 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 Json and no Vector(N) fields, none listed twice. For one field, use @unique or @index on 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 @@unique is also a key for findUnique, upsert, connect and the other operations that take a unique where: { providerId_accountId: { providerId, accountId } }, the fields joined by _. With a name, the key is the name ({ tenantEmail: { tenant, email } }), so it must not clash with a field of the model.
  • The schema rejects two @@unique over the same fields (in any order), two identical @@index and a @@index with the same fields, in the same order, as a @@unique (its constraint already has that index).
  • cyphra push and migrations create them; cyphra pull reads composite uniqueness constraints, node keys and composite range indexes back as @@unique and @@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) }
RuleFieldsThe value must be …
@length(min, max)Stringfrom 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, Dateat least / at most value, inclusive.
@emailStringan email address (local@domain.tld).
@urlStringan absolute http: or https: URL.
@regex(pattern, flags)Stringa string the JavaScript regular expression matches.
@nonEmptyString, listsa 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. @size works the same way.
  • Bounds are inclusive. On Int / Float / BigInt they are numbers (@min(-1.5), @max(9223372036854775807)); on DateTime and Date they are ISO 8601 strings (@min("2020-01-01"), @max("2100-01-01T00:00:00Z")).
  • @regex uses JavaScript syntax and matches anywhere in the string: anchor it with ^…$ to match the whole value. A backslash is written \\ inside a .cyphra string (@regex("^\\d+$")). The optional flags are among i, m, s and u.
  • Absent and null values break no rule (use a required type to demand a value). A list that is not given on create is stored empty, so @nonEmpty or @size(1, …) on a list makes it required in practice.
  • Checked at schema time: a rule on a type it does not fit (@min on a String, @length on a list), a wrong argument (@length(-1), @min(1.5) on an Int), min above max, a regex that does not compile and a @default that breaks the field’s rules are validation errors in cyphra validate and 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. AUTHORED is the Neo4j relationship type as written (UPPER_SNAKE by convention). A relationship AUTHORED { … } block types the properties of every :AUTHORED edge ($edge in the client); without a block the edge has no properties.
  • One side is enough. User.posts alone gives user.posts in the client and writes the edges; add Post.author only 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) and followers 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) on User and author User? @out(AUTHORED) on Post describe two different sets of edges (User → Post and Post → User); one of them is meant to be @in(AUTHORED). Both directions stay allowed when each side has its inverse too.
  • A relationship block that no field uses is an error: usually a misspelled type, on the block or on the fields.
  • Nearly identical types are a warning (AUTHORED and AUTHORD, or FOLLOWS and Follows: 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) }
RuleDeleting a User …
Cascadedeletes its sessions too, applying the sessions’ own rules (chains and cycles are fine).
Restrictfails with a RestrictError while the user still has invoices; nothing is deleted.
SetNullthe default: the REVIEWED edges are removed and the posts stay, with no reviewer.
  • Rules apply to delete and deleteMany of the typed client, in the same transaction as the delete. A rule is allowed on to-one and to-many fields, OUT or IN.
  • Each side of a relation has its own rule, for deletes of its own model: Session.user above keeps the default, so deleting a session never touches its user. Putting onDelete: Cascade on 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 dev notes rule changes but generates no step for them. They are enforced by the Cyphra client only: a raw Cypher DETACH DELETE ignores 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 Employee as (: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, B gets every field of A, then of B, before its own fields: scalars, relations, and their decorators. Employee above has id, email, name, manager and salary. 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, @@index and @@fulltext. Relations can target an interface (manager Person?, members Person[]), and a relationship { … } model can name one in from / to.

  • Constraints and indexes are created once, on the label that declares them. @unique on Person.email is one constraint, Person_email_unique, on :Person: an email is unique across employees and customers. Implementations get no copy. An inherited @@unique stays a unique key of the implementation, and an inherited @@fulltext or @vectorIndex can 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 Engineer is written as (:Engineer:Staff:Person:Contact). db.staff returns engineers (and any other Staff implementation), db.person returns everything below Person.
  • Fields come first from the interfaces, in order (Staff inherits Person’s fields before its own). A field reached twice through two interfaces extending the same one (Person.email via Staff and Contact, a “diamond”) is inherited once.
  • Constraints and indexes stay on the label that declares them: Person_email_unique covers every Staff and Contact node; Staff_badge_unique is on :Staff.
  • A node implements interfaces and an interface extends them: interface X implements Y and node X extends Y are 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.bio required on Employee, 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/graphql v7 interfaces add no label (a Movie implementing Production is 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 Post stays (: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?), with onDelete rules like any relation: Cascade deletes each related node with the rules of the model it is.
  • Querying. db.searchHit reads 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 __typename and $on.
  • Members are node models or interfaces, listed once, with an optional leading | when the list spans lines (union SearchHit = then | Post on 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, with interface Person, stands for every node implementing Person (today’s and future ones): it is matched by the interface’s label (WHERE n:Person OR n:Team), results are the implementations (__typename is "Employee", "Customer" or "Team", never "Person"), and writes and $on may name Person to address every implementation at once (see the client).
  • Typed edges. A relationship { … } model may name a union in from or to: 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 pull cannot infer unions (a union adds no label): it keeps one relation per target label; declare the union by hand. The GraphQL importer reports @neo4j/graphql unions 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 a CyphraValidationError before anything runs: label names in the generated Cypher always come from the schema, never from a value.
  • Not part of the model. db.post matches 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): use implements for labels every node of the model carries.
  • Shared names. Several models may declare the same label (:Archived on posts and users). On an interface, @@labels applies to every implementation too, and db.<interface> can filter and write them; an implementation can declare more of its own.
  • No DDL. @@labels creates 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 :Archived would also cover the other models declaring it.
  • It works the same on Memgraph and FalkorDB: plain SET n:Label / REMOVE n:Label and 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.

Last updated on