MERGE, SET and DELETE

Neo4j · Essentials · 12 min

Idempotent writes and safe deletes are essential for any import script or application.

MERGE is "match or create": it looks for the whole pattern and creates it only if it does not exist. Combine it with ON CREATE SET and ON MATCH SET to set properties depending on which happened.

The key rule: MERGE matches the entire pattern. MERGE (a:Person {name:'Ann'})-[:FOLLOWS]->(b:Person {name:'Bob'}) will create both nodes again if that exact path is missing, even if Ann and Bob exist. The safe idiom is to MERGE nodes on their key first, then MERGE the relationship between the bound variables.

Merge on the identifying property only, MERGE (p:Person {email: $email}), and set the rest with SET; merging on many properties creates a new node whenever any of them differs.

Changing data:

  • SET p.age = 35, SET p += {age: 35, city: 'Yerevan'} (merge a map), SET p:Admin (add a label)
  • REMOVE p.age, REMOVE p:Admin; setting a property to null also removes it

Deleting: DELETE r removes a relationship. A node can only be deleted once it has no relationships, so use DETACH DELETE n to remove a node together with its relationships. MATCH (n) DETACH DELETE n empties the database; for big graphs do it in batches.

Example

// idempotent: run it twice, the graph stays the same
MERGE (a:Person {name: 'Ann'})
  ON CREATE SET a.created = datetime()
  ON MATCH  SET a.lastSeen = datetime()
MERGE (d:Person {name: 'Dan'})
MERGE (a)-[:FOLLOWS]->(d);            // relationship merged between bound nodes

MATCH (p:Person {name: 'Dan'})
SET p += {born: 1999, city: 'Yerevan'}, p:Employee
REMOVE p.city;

MATCH (p:Person {name: 'Dan'})
DETACH DELETE p;                      // also deletes Ann-[:FOLLOWS]->Dan

Remember

  • MERGE matches the whole pattern or creates all of it
  • MERGE nodes by key first, then MERGE relationships between variables
  • SET/REMOVE change properties and labels; += merges a map
  • DETACH DELETE removes a node with its relationships

Watch out for

  • MERGE on a full path with unbound nodes, creating duplicate Ann and Bob nodes when the relationship is new.

Check yourself

  1. Why does DELETE n fail for a node that has relationships?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: neo4j.com/docs/cypher-manual/current/clauses/merge/