Skip to Content

Create a relationship between existing nodes

MATCH both nodes first, then CREATE the relationship between the variables you matched. Use MERGE instead of CREATE if the relationship should exist only once:

MATCH (a:User {email: $from}) MATCH (b:User {email: $to}) CREATE (a)-[f:FOLLOWS {since: datetime()}]->(b) RETURN count(f) AS created

created is 1 when both users exist. When either one does not, MATCH finds no rows, nothing is created, and created is 0. Cypher does not raise an error for that, so check the result.

Only once: MERGE 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

Run it twice and there is still one FOLLOWS relationship. CREATE would have made two: Neo4j allows any number of relationships of the same type between the same nodes. If a user is missing, this query returns no rows. More in MERGE vs CREATE.

Don’t put labels and properties in the CREATE pattern

// Don't: this creates two NEW users, it does not find the existing ones CREATE (a:User {email: $from})-[:FOLLOWS]->(b:User {email: $to})

A label or property map inside CREATE describes a node to create. Only bare variables bound by MATCH ((a), (b)) refer to existing nodes. With a uniqueness constraint on email the statement above fails with ConstraintValidationFailed; without one it creates duplicates.

Write one MATCH per node, as above. MATCH (a:User {email: $from}), (b:User {email: $to}) also works, but a comma between unrelated patterns makes Neo4j warn about a cartesian product.

Many relationships at once

Pass the pairs as a list parameter:

UNWIND $pairs AS pair MATCH (a:User {email: pair.from}) MATCH (b:User {email: pair.to}) MERGE (a)-[:FOLLOWS]->(b)

Pairs whose nodes do not exist are skipped silently, like the single version.

By internal id

If you only have Neo4j’s internal ids, use elementId() (Neo4j 5; id() is deprecated):

MATCH (a), (b) WHERE elementId(a) = $fromId AND elementId(b) = $toId MERGE (a)-[:FOLLOWS]->(b)

Element ids can be reused after a node is deleted, so prefer your own unique key (id, email) for anything you store.

In Cyphra

Relationships are fields in the schema (following User[] @relationship(type: "FOLLOWS")), and connect links existing nodes by any @id / @unique field. Edge properties declared in a relationship { … } model go in $edge:

import { db } from "./db.js"; await db.user.update({ where: { email: "alice@acme.io" }, data: { following: { connect: { email: "bob@acme.io", $edge: { since: new Date() } } } }, }); const alice = await db.user.findUnique({ where: { email: "alice@acme.io" }, include: { following: true }, }); // alice.following: (User & { $edge: { since: Date | null } })[]

Unlike the Cypher version, a missing target is an error: connect throws NotFoundError (connect: no User matches {"email":"nobody@acme.io"}.). The update runs in one transaction, so other changes in the same call (say, a new name) are rolled back too.

connect runs the MERGE version above, so it is idempotent: connecting the same pair again keeps one FOLLOWS relationship. In our test, ten concurrent connect calls for the same pair also left exactly one. For a typed edge, $edge and the schema defaults (here since, if it has @default(now())) are set when the relationship is created; on an existing one, only the $edge properties you pass are updated, so a repeat connect without $edge keeps the original since. On a to-one relation (author User?), connect replaces the existing edge, and the same holds from the other side: user.posts → connect on a post that has another author moves it. Either way the old AUTHORED edge is deleted in the same statement as the MERGE, with the post locked, so concurrent author changes still leave one author.

So “follow, but only once” needs no extra code:

async function follow(from: string, to: string) { await db.user.update({ where: { email: from }, data: { following: { connect: { email: to } } }, }); }

If you need several relationships of the same type between one pair, use CREATE through db.$cypher.

Before Cyphra 0.3, connect used CREATE, so calling it twice left two edges. To find pairs that were linked more than once, and keep one edge per pair:

MATCH (a:User)-[r:FOLLOWS]->(b:User) WITH a, b, collect(r) AS rels WHERE size(rels) > 1 UNWIND tail(rels) AS extra DELETE extra

You can also link while creating: db.post.create({ data: { title, author: { connect: { email } } } }). To remove a relationship but keep both nodes, use disconnect (see Delete a node and its relationships).

Last updated on