Skip to Content

Upsert in Neo4j with MERGE

To upsert in Neo4j, MERGE the node on its unique key, then set properties with ON CREATE SET (only when the node is new) and ON MATCH SET (only when it already existed). Put a uniqueness constraint on the key, or concurrent upserts can create duplicates.

MERGE (u:User {email: $email}) ON CREATE SET u.id = randomUUID(), u.name = $name, u.loginCount = 1, u.createdAt = datetime() ON MATCH SET u.loginCount = u.loginCount + 1 RETURN u.email AS email, u.loginCount AS loginCount

Run it twice with the same $email: the first run creates the user with loginCount = 1, the second finds it and sets loginCount to 2. There is one User node either way.

How MERGE decides

MERGE looks for the whole pattern you give it. If it finds a match, it uses it; if not, it creates the whole pattern. Three consequences:

  • The properties inside MERGE (u:User {…}) are the lookup key. Keep only the unique key there and set everything else with ON CREATE SET, ON MATCH SET or a plain SET. If you write MERGE (u:User {email: $email, name: $name}) and the name changed, MERGE finds no match and tries to create a second user (which the constraint then rejects).
  • ON CREATE SET runs only when MERGE created the node, ON MATCH SET only when it found it. A plain SET after them runs in both cases.
  • A null key fails: MERGE (u:User {email: null}) is an error (“Cannot merge the following node because of null property value”), so validate input first.

MERGE vs CREATE covers the differences in more detail.

Back the key with a uniqueness constraint

CREATE CONSTRAINT user_email_unique IF NOT EXISTS FOR (u:User) REQUIRE u.email IS UNIQUE

The constraint is what makes MERGE safe when two requests upsert the same key at once. We sent ten concurrent MERGE statements for the same new email, each on its own connection, and repeated that 15 times on Neo4j 5.26 Community:

SetupResult
No constraint on the keyduplicates in every run: between 5 and 10 User nodes
Uniqueness constraint (key)always 1 node with loginCount = 10, and no statement failed

The constraint also creates an index on the key. EXPLAIN shows MERGE using it: the plan’s lookup step is NodeUniqueIndexSeek(Locking), an index seek that also locks the key, rather than a scan of every User node.

Upsert a relationship

Match both endpoints first, then MERGE only the relationship:

MATCH (a:User {email: $from}) MATCH (b:User {email: $to}) MERGE (a)-[f:FOLLOWS]->(b) ON CREATE SET f.since = datetime() RETURN f.since AS since

Running it again does not add a second FOLLOWS edge, and since keeps its first value. If either user does not exist, the query returns no rows and creates nothing. See Create a relationship between existing nodes.

Don’t MERGE a whole path

A common mistake is to upsert two nodes and their relationship in one pattern:

// Don't: MERGE matches or creates the whole path, nodes included MERGE (u:User {email: $email})-[:AUTHORED]->(p:Post {title: $title})

If the user exists but has no post with that title, the path does not match, so MERGE creates all of it, including a new User with the same email. With the constraint this fails with Neo.ClientError.Schema.ConstraintValidationFailed; without one you silently get a duplicate user. MERGE each node on its own key, then the relationship:

MERGE (u:User {email: $email}) MERGE (p:Post {id: $postId}) ON CREATE SET p.title = $title, p.published = false, p.createdAt = datetime() MERGE (u)-[:AUTHORED]->(p)

Upsert many rows with UNWIND

Send a list as one parameter and MERGE each row:

UNWIND $rows AS row MERGE (u:User {email: row.email}) ON CREATE SET u.id = randomUUID(), u.loginCount = 0, u.createdAt = datetime() SET u.name = row.name

With $rows = [{email: "alice@acme.io", name: "Alice B."}, {email: "carol@acme.io", name: "Carol"}], Alice is updated and Carol is created, in one statement and one transaction.

Upsert with Cyphra

The typed client has upsert, keyed on any @id or @unique field:

import { db } from "./db.js"; const user = await db.user.upsert({ where: { email: "alice@acme.io" }, create: { email: "alice@acme.io", name: "Alice", loginCount: 1 }, update: { loginCount: { increment: 1 } }, }); // user: { id: string; email: string; name: string | null; loginCount: number; createdAt: Date }

create is type-checked like db.user.create (required fields, defaults from the schema) and update like db.user.update, including number operations such as increment.

upsert compiles to one MERGE on the unique key from where, so it is the statement from the top of this page:

MERGE (n:User {email: $p0}) ON CREATE SET n += $p1 // create data, plus id and createdAt from the schema defaults ON MATCH SET n.loginCount = n.loginCount + $p2 RETURN elementId(n) AS id, n{.id, .email, .name, .loginCount, .createdAt} AS row

The key itself is never given a default: where: { id } with create omitting id creates the node with that id. If create sets the key, it must be the same value as in where.

Like any MERGE, upsert is only safe under concurrency with a uniqueness constraint on the key. Cyphra creates one for every @id and @unique field when you run cyphra push or apply a migration. With it, fifteen concurrent upserts of a new email (five runs) ended with one node, no errors and every increment applied. Without it, concurrent calls can still create duplicates.

Nested writes still work: upsert runs the MERGE first, then the relation writes of the branch it took (create or update), in the same write transaction. Extra conditions in where (beyond the key) are checked on an existing node before it is updated; if they do not match, nothing is written and upsert throws, since creating a second node would duplicate the key.

Last updated on