Neo4j migrations: constraints and indexes as code
Neo4j has no table schema, but it has constraints, indexes and data that must change together. How Cyphra generates reviewable migrations from schema diffs.
“Neo4j is schemaless” is true and slightly misleading. There are no tables to create, and any node can hold any property. But a production graph still has a schema: the uniqueness constraints that stop two users from sharing an email, the indexes that keep lookups fast, and the assumptions your code makes about which properties exist. When those change, something has to change the database, in the same order on every environment.
This post explains how Cyphra treats that schema as code: where the constraints and indexes come from, how a migration is generated from a schema diff, and what happens to the data that is already there.
What a Neo4j schema actually contains
Without tables, the schema of a Neo4j database is mostly two kinds of objects:
- Constraints. A uniqueness constraint guarantees that no two nodes with a label share a
property value, for example
User.email. Neo4j backs each one with an index, so lookups on that property are fast too. - Indexes. A range index speeds up equality and range lookups on a property that does not need
to be unique, such as
User.name.
Everything else, the properties a node is expected to have, their types and their defaults, lives in application code. That split is the reason schema changes in Neo4j are easy to get subtly wrong: the DDL and the data rules are maintained in different places.
Decorators become DDL
In Cyphra, both live in the .cyphra schema. Three decorators map to Neo4j schema objects:
node User {
id String @id @default(cuid())
email String @unique
name String @index
posts Post[] @relationship(type: "AUTHORED", direction: OUT)
}
node Post {
id String @id @default(uuid())
title String
author User? @relationship(type: "AUTHORED", direction: IN)
}cyphra schema ddl prints what they mean, without touching a database. For the schema above, the
output is:
CREATE CONSTRAINT User_id_id IF NOT EXISTS FOR (n:`User`) REQUIRE n.`id` IS UNIQUE
CREATE CONSTRAINT User_email_unique IF NOT EXISTS FOR (n:`User`) REQUIRE n.`email` IS UNIQUE
CREATE CONSTRAINT Post_id_id IF NOT EXISTS FOR (n:`Post`) REQUIRE n.`id` IS UNIQUE
CREATE RANGE INDEX User_name_idx IF NOT EXISTS FOR (n:`User`) ON (n.`name`)@id and @unique become uniqueness constraints and @index becomes a range index. Names are
derived from the label and property, so they are stable across runs and between cyphra push and
migrations. On a node, you cannot put @index on a field that is already @id or @unique: the
constraint already implies an index. On a relationship { … } model, @unique becomes a
relationship property uniqueness constraint, which needs Neo4j 5.7 or later.
From schema diff to migration file
The workflow is three commands:
cyphra migrate dev --name add-roles # generate a migration from your changes, then apply it
cyphra migrate status # applied, pending, modified, or not yet captured
cyphra migrate deploy # CI / production: apply pending migrations onlycyphra migrate dev compares your current schema with migrations/schema.snapshot.json, the schema
as it was when the last migration was generated, and writes migrations/<timestamp>_<name>.mjs.
Generation needs no database and is deterministic, so the same schema change always produces the
same file. You commit both the migration and the updated snapshot, and the migration is reviewed in
a pull request like any other code.
Two flags help when you want to look before applying: cyphra migrate diff prints what would be
generated without writing anything, and --create-only writes the file without applying it, so you
can edit it first.
Data steps, not only DDL
Constraints are the easy half. The harder half is the data that already exists. Say you add two
fields to User:
role String @default("member")
handle String @uniqueExisting users have neither property. Creating the uniqueness constraint on handle would work,
since absent values are not compared, but every old user now breaks the assumption that handle is
required. Cyphra generates this migration for that change:
// 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",
);
},
});Three kinds of step appear here:
- Backfill.
rolehas a default, so existing nodes get it. The value is a parameter, not part of the query text. - Guard.
handleis required and has no default, so Cyphra cannot invent values. The migration counts the nodes that lack it and stops if there are any. - DDL. The new constraint is created with
IF NOT EXISTS.
When a guard fails, the fix is to add your own step above it, for example
SET n.handle = split(n.email, "@")[0], and run cyphra migrate deploy again.
The order is deliberate: obsolete constraints and indexes are dropped first, then data steps run, then new constraints and indexes are created. That way values are backfilled before a uniqueness constraint is created on them.
What Cyphra will not do for you
Some changes are destructive or ambiguous, and a generator should not guess:
- Removed fields and models produce
REMOVEandDETACH DELETEstatements that are written commented out. Deleting data is something you opt into in review. - Type changes and likely renames add a warning at the top of the file. A rename looks the same as a removal plus an addition, and only you know which one you meant.
For those cases you write the step by hand. cyphra migration:create <name> creates an empty
migration, and the db handle offers helpers for the common ones:
import { defineMigration } from "cyphra";
export default defineMigration({
name: "20261120090000_rename-name",
async up({ db }) {
await db.migrate.renameProperty({ label: "User", from: "name", to: "displayName" });
},
});There is also db.migrate.renameLabel, the parameterized db.run`…` tagged template, and
db.runInTransactionBatches for rewrites that are too large for one transaction.
Safe to re-run
Neo4j does not allow schema changes and data changes in the same transaction. So each step runs as
its own auto-commit statement, and a migration that fails halfway has already applied the steps
before the failure. Generated steps are written to be safe to run again: DDL uses IF NOT EXISTS
and IF EXISTS, and backfills only touch nodes WHERE … IS NULL. Keep hand-written steps
re-runnable in the same way.
Tracking and CI
Applied migrations are recorded in the database as (:__CyphraMigration { name, appliedAt, checksum })
nodes. cyphra migrate status compares them with the files on disk and reports:
- migrations that are pending,
- applied migrations whose file was modified afterwards (checksum mismatch),
- applied migrations whose file is missing,
- schema changes that are not captured in a migration yet.
It exits non-zero in all of those cases, so it can gate a CI job. A typical pipeline runs
cyphra migrate status on pull requests, so a schema change without its migration fails review, and
cyphra migrate deploy on release.
Existing databases
You do not need to start from an empty graph. cyphra pull reads labels, relationship types,
property types, constraints and indexes from a live database and writes a .cyphra schema. It is
read-only, and the result is a starting point to review: relation names are derived from
relationship types, and a property is marked required only if every node had it at pull time.
If a project used cyphra push before, which applies constraints and indexes directly and is handy
for prototyping, the first cyphra migrate dev re-creates the same objects with IF NOT EXISTS and
is safe to run. From then on, prefer migrations for any database that more than one person uses.
Further reading
- Migrations reference: every generated step and the
dbhelpers. - Schema DSL: decorators, defaults and relationship models.
- CLI:
cyphra dev,pull,pushandschema ddl. - Glossary: constraint, index, schema migration.