Skip to Content
Migrations

Migrations

Neo4j is schemaless, so a Cyphra migration does two jobs: keep constraints and indexes in line with your schema, and fix up existing data when the schema changes (backfill new defaults, refuse to continue when a newly required field is missing, and so on).

Workflow

cyphra dev # local Neo4j in Docker, writes .env # edit schema.cyphra cyphra migrate dev --name add-roles # generate a migration from your changes, then apply it cyphra migrate status # applied / pending / modified migrations, and drift cyphra migrate deploy # CI / production: apply pending migrations only

cyphra migrate dev compares your schema with migrations/schema.snapshot.json (the schema as of the last generated migration) and writes migrations/<timestamp>_<name>.mjs. Generation needs no database and is deterministic, so the file can be reviewed like any other code. Commit both the migration and the snapshot.

  • cyphra migrate diff prints what would be generated, without writing anything.
  • cyphra migrate dev --create-only writes the migration without applying it, so you can edit it first.

What gets generated

Schema changeGenerated step
new @id / @unique / @indexCREATE CONSTRAINT / RANGE INDEX … IF NOT EXISTS
new @index on a Point / CartesianPointCREATE POINT INDEX … IF NOT EXISTS
removed or changed @id / @unique / @indexDROP CONSTRAINT / INDEX … IF EXISTS
new @vectorIndexCREATE VECTOR INDEX … IF NOT EXISTS … OPTIONS { indexConfig }
changed dimensions, similarity or index nameDROP INDEX … IF EXISTS, then CREATE VECTOR INDEX
new @@unique([a, b]) / @@index([a, b])CREATE CONSTRAINT … REQUIRE (n.a, n.b) IS UNIQUE / RANGE INDEX
changed fields or name of a @@unique / @@indexDROP CONSTRAINT / INDEX … IF EXISTS, then CREATE …
new @@fulltextCREATE FULLTEXT INDEX … IF NOT EXISTS … ON EACH [ … ]
changed fields, analyzer, consistency or nameDROP INDEX … IF EXISTS, then CREATE FULLTEXT INDEX
new field with a @default on an existing modelbackfill: MATCH (n:User) WHERE n.role IS NULL SET n.role = $value
field becomes required and has a defaultbackfill of the missing values
node starts / stops implementing an interfaceSET n:Person / REMOVE n:Person on its existing nodes
new required field without a defaultguard: the migration fails if any existing node lacks it
removed field / modelREMOVE / DETACH DELETE, commented out: you opt in
renamed relationship type (@out(A) → @out(B))the edges are recreated with the new type (and a review warning)
type change, or a likely renamea review warning at the top of the file

Steps run in this order: drop obsolete DDL → data steps → create new DDL, so values are backfilled before a uniqueness constraint is created on them. now() backfills with datetime() / date() / localdatetime() / localtime() / time() (by field type), a temporal literal with localtime($value), duration($value), … (so the property is a temporal value, not a string), and uuid() with randomUUID(). cuid() cannot be generated in Cypher, so it also falls back to randomUUID().

Example, after adding role String @default("member") and handle String @unique to User:

// Generated by `cyphra migrate dev`. Review it before applying to shared databases. import { defineMigration } from "cyphra"; export default defineMigration({ name: "20261118174710_add-roles", async up({ db }) { // Backfill User.role with its default on existing nodes. await db.execute("MATCH (n:`User`) WHERE n.`role` IS NULL SET n.`role` = $value", { value: "member", }); // User.handle is now required and has no default: make sure no existing node lacks it. { const [row] = await db.execute( "MATCH (n:`User`) WHERE n.`handle` IS NULL RETURN count(n) AS count", ); if (row && Number(row.count) > 0) { throw new Error("User.handle is required but some existing User nodes do not have it. …"); } } // Create constraint User_handle_unique. await db.execute( "CREATE CONSTRAINT User_handle_unique IF NOT EXISTS FOR (n:`User`) REQUIRE n.`handle` IS UNIQUE", ); }, });

When a guard fails, add your own step above it (for example SET n.handle = split(n.email, "@")[0]) and run cyphra migrate deploy again.

Steps run as separate auto-commit statements (Neo4j does not allow schema and data changes in one transaction). Generated steps are written to be safe to re-run after a failure (IF NOT EXISTS, WHERE … IS NULL); keep hand-written steps re-runnable too.

Point indexes

@index on a Point or CartesianPoint field creates a point index, which serves point.distance and point.withinBBox predicates (spatial queries). It is named like a range index:

CREATE POINT INDEX Place_location_idx IF NOT EXISTS FOR (n:`Place`) ON (n.`location`)

Changing a field’s type to or from a point type drops the range index and creates the point index (or the reverse), under the same name. cyphra push and cyphra schema ddl emit the same statement, and cyphra pull maps a point index back to @index.

Vector indexes

A Vector(N) @vectorIndex(…) field becomes a vector index (Neo4j 5.15+), named like the field’s index (<Label>_<field>_vector unless name is set):

CREATE VECTOR INDEX Chunk_embedding_vector IF NOT EXISTS FOR (n:`Chunk`) ON n.`embedding` OPTIONS {indexConfig: {`vector.dimensions`: 1536, `vector.similarity_function`: 'cosine'}}

Neo4j cannot alter a vector index, so changing N, similarity or quantization drops the index first and creates the new one at the end of the migration. A dimension change also adds a review warning: existing embeddings keep their old length, and Neo4j leaves vectors of the wrong length out of the index, so re-embed them (in this migration or a backfill job) before relying on findSimilar.

A new index is built in the background. cyphra schema ddl prints the statement and cyphra push applies it directly. Wait for it to be ONLINE before querying it, for example in a test setup: CALL db.awaitIndexes(300).

Full-text indexes

A @@fulltext([…]) model attribute becomes a full-text index, with its analyzer and consistency in OPTIONS when the schema sets them:

CREATE FULLTEXT INDEX postSearch IF NOT EXISTS FOR (n:`Post`) ON EACH [n.`title`, n.`body`] OPTIONS {indexConfig: {`fulltext.analyzer`: 'english', `fulltext.eventually_consistent`: false}}

Neo4j cannot alter a full-text index either, so adding or removing a field, or changing analyzer, eventuallyConsistent or name, drops the index first and creates the new one at the end of the migration. Neo4j then indexes the existing nodes again in the background; like a vector index, wait for it to be ONLINE (CALL db.awaitIndexes(300)) before relying on search. cyphra schema ddl prints the statement and cyphra push applies it directly.

Composite constraints and indexes

A @@unique([a, b]) model attribute becomes a composite uniqueness constraint, a @@index([a, b]) a composite range index:

CREATE CONSTRAINT Account_providerId_accountId_unique IF NOT EXISTS FOR (n:`Account`) REQUIRE (n.`providerId`, n.`accountId`) IS UNIQUE CREATE RANGE INDEX Account_tenant_createdAt_idx IF NOT EXISTS FOR (n:`Account`) ON (n.`tenant`, n.`createdAt`)

Both work on Neo4j Community. Cyphra does not emit IS NODE KEY (uniqueness plus existence of every property), which Neo4j only supports on Enterprise Edition; make the fields required in the schema instead, which the client enforces on create. Changing the fields or the name drops the old constraint or index first and creates the new one at the end of the migration. Creating a uniqueness constraint fails if existing nodes already share a key: deduplicate them in a step before it. cyphra push and cyphra schema ddl emit the same statements, and cyphra pull maps composite uniqueness constraints (and node keys) back to @@unique and composite range indexes to @@index.

Interfaces and labels

When a node starts implementing an interface, its existing nodes get the interface label, before the interface’s constraints and indexes are created (so a uniqueness constraint on the interface checks every implementation):

MATCH (n:`Employee`) WHERE NOT n:`Person` SET n:`Person`

A node that stops implementing an interface loses the label (MATCH (n:Employee) WHERE n:Person REMOVE n:Person); removing an interface never deletes nodes. Inherited fields are fields of the implementation, so the usual backfills and guards run on its label when it starts implementing an interface; a new field of an interface is migrated once, on the interface’s label. Constraint names follow the declaring label: moving email @unique from Employee into interface Person drops Employee_email_unique and creates Person_email_unique.

With interfaces extending interfaces, a node gains or loses every label up the chain: when interface Staff starts extending Person, each Staff implementation gets a step adding :Person to its existing nodes.

Dynamic labels

Dynamic labels (@@labels([…])) create no constraint or index, so declaring one needs no step: the migration lists it under NOTES. Removing one from a model adds a commented-out destructive step that strips the label from existing nodes, for you to uncomment:

// Post no longer declares the dynamic label Featured. Uncomment to remove :Featured from existing Post nodes. // DESTRUCTIVE: uncomment to apply. // await db.execute("MATCH (n:`Post`) WHERE n:`Featured` REMOVE n:`Featured`");

A label that moves from @@labels to implements (every node of the model now carries it) gets the usual step adding it to existing nodes instead.

Unions

A union adds no label, constraint or index, so declaring, changing or removing one generates no step (and is not read as a renamed model).

Relationship types

A relationship type cannot be changed in place in Neo4j, so renaming one in the schema needs a data migration. When a relation field keeps its name, target and direction but its type changes (posts Post[] @out(AUTHORED) becomes @out(WROTE), in either syntax, from one side or both), the migration recreates the existing edges between those two models with the new type and the same properties, and lists the rename under REVIEW:

// Rename the :AUTHORED edges from User to Post to :WROTE (User.posts, Post.author). await db.execute( "MATCH (a:`User`)-[r:`AUTHORED`]->(b:`Post`) CREATE (a)-[n:`WROTE`]->(b) SET n = properties(r) DELETE r", );

Only the edges between the field’s models move: :AUTHORED edges between other nodes stay. A relationship AUTHORED { … } block renamed with its type gets the usual constraint and index steps (drop the old names, create the new ones after the edges moved). Like a renamed field, a type that disappears while another appears, with the fields renamed too, only gets a warning: move the edges yourself with db.migrate.renameRelationshipType({ from, to }) if it is a rename. Changing only the syntax (@relationship(type: "AUTHORED", direction: OUT) to @out(AUTHORED)) changes nothing in the database and generates no step.

Writing migrations by hand

cyphra migration:create <name> creates an empty migration. The db handle offers:

  • db.run`…${value}`: a parameterized tagged template.
  • db.execute(text, params?): trusted Cypher text, for DDL that cannot be parameterized. It returns rows as plain objects.
  • db.runInTransactionBatches({ inner, batchSize, params }): wraps inner in CALL { … } IN TRANSACTIONS OF … ROWS for large rewrites.
  • db.migrate.renameLabel({ from, to }) and db.migrate.renameProperty({ label, from, to }).
  • db.migrate.renameRelationshipType({ from, to, startLabel?, endLabel? }): recreates the from edges (between nodes with those labels, when given) as to edges with the same properties.
import { defineMigration } from "cyphra"; export default defineMigration({ name: "20261120090000_rename-name", async up({ db }) { await db.migrate.renameProperty({ label: "User", from: "name", to: "displayName" }); }, });

Reset a development database

cyphra migrate reset starts a local database over from your migrations:

cyphra migrate reset # asks for confirmation cyphra migrate reset --yes # no prompt (scripts, local CI) cyphra migrate reset --skip-seed

It runs against the database from NEO4J_URI (and NEO4J_DATABASE when set) and:

  1. drops every constraint, then every index: range, text, point, vector and full-text. The LOOKUP indexes Neo4j creates by default are kept;
  2. deletes all nodes and relationships, in batches of 10,000 (CALL { … } IN TRANSACTIONS). This also removes the __CyphraMigration records;
  3. applies every migration in migrations/, in order;
  4. runs the seed command from cyphra.json, unless --skip-seed is passed or no seed is configured. A failing seed makes the command exit with its code.

Without --yes (or -y) it asks before deleting anything, and refuses to run when the shell is not interactive. It also refuses databases that do not look local, even with --yes:

  • local: localhost and *.localhost, loopback addresses (127.x.x.x, ::1), 0.0.0.0, host.docker.internal, and host names without a dot (Docker or Compose service names such as neo4j), over bolt:// or neo4j://;
  • not local: encrypted schemes (neo4j+s://, bolt+s://, +ssc), Neo4j Aura hosts (*.databases.neo4j.io), any other host name with a dot, and private or public IP addresses.

--force skips both the prompt and this check. Never use it in a script that could point at a shared database.

Tracking

Applied migrations are recorded as (:__CyphraMigration { name, appliedAt, checksum }), where checksum is the SHA-256 of the migration file. cyphra migrate status reports migrations that are pending, applied files that were modified after being applied (checksum mismatch), applied migrations whose file is missing, schema changes not yet captured in a migration, and drift.

Drift detection

A database drifts when its constraints or indexes are changed outside migrations: an index created by hand in Neo4j Browser, a constraint dropped during an incident, a vector index recreated with other dimensions. cyphra migrate status compares the database with what the applied migrations created:

$ cyphra migrate status Migrations (migrations): applied 20261121194402_init Drift (database vs the applied migrations): extra index manual_idx: RANGE index on (:User {name}) missing constraint User_email_unique: UNIQUE constraint on (:User {email}) changed index Doc_embedding_vector: dimensions: 3 → 4; similarity: cosine → euclidean (expected → actual) 3 drift issue(s). Capture intended changes in a migration (`cyphra migration:create`) or revert them in the database; in development, `cyphra migrate reset` rebuilds the database from the migrations.
  • extra: in the database, not created by any applied migration.
  • missing: created by a migration, no longer in the database.
  • changed: present on both sides with a different definition: labels or relationship type, properties (and their order), index type (RANGE, POINT, TEXT, VECTOR, FULLTEXT), constraint type, vector dimensions, similarity and quantization, full-text analyzer and eventual consistency. An object found under another name with the same definition is reported as a name change.

How the expected state is built. The applied migrations are replayed, in the order they were applied: each up() runs against a recording db handle that sends nothing to the database, and the CREATE / DROP constraint and index statements it issues are applied to an in-memory model (IF NOT EXISTS is a no-op when the object already exists, as in Neo4j). Pending migrations are not part of it: they are listed as pending. The actual state comes from SHOW CONSTRAINTS and SHOW INDEXES, so the check is read-only and does not scan data.

Replaying migrations answers “has the database drifted from the migrations?”. Whether the schema has changes no migration captures yet is a separate question that needs no database: cyphra migrate diff. With --schema, migrate status compares the database with the constraints and indexes schema.cyphra implies instead (what cyphra push creates), for projects that use push rather than migrations.

Ignored on both sides: the LOOKUP token indexes Neo4j creates by default, indexes that back a constraint (the constraint is compared instead), and Cyphra’s own cyphra_migration_name_unique constraint on __CyphraMigration. Neo4j settings Cyphra does not set (HNSW parameters, index providers, quantization when the migration leaves it to Neo4j’s default) are not compared.

Limits of the replay: a migration that computes DDL from data it reads (rows from db.execute) gets no rows during the replay, and DDL that is not a Neo4j 5 CREATE / DROP statement Cyphra recognizes is listed as a warning and left out. A migration that was edited after it was applied is replayed from its current file, with a warning.

cyphra migrate dev runs the same check before it generates a migration, and warns when the database has drifted: the new migration only covers schema changes, so in development run cyphra migrate reset to rebuild the database from the migrations.

Exit codes and JSON

Exit codeMeaning
0In sync: every migration applied, nothing uncaptured, no drift
1Something needs attention: drift, pending / modified / missing migrations, uncaptured changes
2The check could not run (no connection, invalid cyphra.json, unreadable migration)

--json prints one JSON document on stdout (warnings still go to stderr), with the same exit code:

{ "inSync": false, "migrations": [{ "name": "20261121194402_init", "state": "applied" }], "uncapturedChanges": 0, "drift": { "expected": "migrations", "extra": [ { "name": "manual_idx", "kind": "index", "type": "RANGE", "entityType": "NODE", "labelsOrTypes": ["User"], "properties": ["name"], "options": {} } ], "missing": [], "changed": [] }, "warnings": [] }

state is applied, pending, modified or missing. Each changed entry has expected, actual and differences (for example "dimensions: 3 → 4", expected → actual).

In CI

Run it after migrate deploy, so pending migrations are applied first and any remaining difference is drift:

# .github/workflows/deploy.yml - name: Apply migrations run: npx cyphra migrate deploy env: NEO4J_URI: ${{ secrets.NEO4J_URI }} NEO4J_USERNAME: ${{ secrets.NEO4J_USERNAME }} NEO4J_PASSWORD: ${{ secrets.NEO4J_PASSWORD }} - name: Check for schema drift run: npx cyphra migrate status env: NEO4J_URI: ${{ secrets.NEO4J_URI }} NEO4J_USERNAME: ${{ secrets.NEO4J_USERNAME }} NEO4J_PASSWORD: ${{ secrets.NEO4J_PASSWORD }}

The step fails on drift (exit 1) and on a connection error (exit 2). To report without failing the job, use npx cyphra migrate status --json > drift.json || true and upload drift.json as an artifact.

Existing databases

  • cyphra pull writes a .cyphra schema from a live database (see CLI).
  • On a project that already used cyphra push, the first migrate dev re-creates the same constraints with IF NOT EXISTS, so it is safe to run.
  • cyphra push still applies constraints and indexes directly, which is handy for prototyping. Prefer migrations for anything shared.

Relationship property uniqueness (@unique in a relationship { … } model) requires Neo4j 5.7+.

Last updated on