Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 30 ยท Cypher and Graph Modeling

Cypher: MERGE, SET, DELETE and constraints

Change a Neo4j graph safely with Cypher: idempotent MERGE, SET and REMOVE, DELETE versus DETACH DELETE, plus uniqueness constraints and indexes.

Reading a graph is only half of working with it. Real applications import data twice, retry requests, rename people and remove accounts. This lesson covers the Cypher clauses that change data: MERGE for "find it or create it", SET and REMOVE for properties and labels, DELETE and DETACH DELETE for removal, and constraints and indexes that keep the graph clean and fast.

Neo4j cannot run on this site, so the Cypher below is read-only, shown with the behaviour documented for Neo4j 5; it was not executed here. The JavaScript stand-ins implement a miniature in-memory graph with the same rules (idempotent merge, refusal to delete connected nodes, uniqueness checks) so that you can watch each rule happen. They are models, not Neo4j's engine. If MATCH and patterns are new to you, start with Cypher: MATCH, CREATE and patterns.

MERGE: find it or create it

CREATE always creates. MERGE first looks for the whole pattern; if it exists, it binds to it, otherwise it creates it:

CYPHER
MERGE (p:Person {email: '[email protected]'})
ON CREATE SET p.created = datetime(), p.name = 'Ada'
ON MATCH  SET p.lastSeen = datetime()
RETURN p;

Run this ten times and you still have one Ada. ON CREATE SET runs only when the node was just created; ON MATCH SET runs only when it already existed. That makes MERGE the right clause for imports and for any request a client might retry (compare the idempotence discussion in Lightweight transactions, batches and counters).

A common mistake is merging on too many properties:

CYPHER
-- Risky: if Ada's name changes, this no longer matches and creates a duplicate
MERGE (p:Person {email: '[email protected]', name: 'Ada L.'})

-- Better: merge on the identifying key, set the rest afterwards
MERGE (p:Person {email: '[email protected]'})
SET   p.name = 'Ada L.'

MERGE matches all the properties you write in the pattern. Put only the identity in the pattern and use SET for everything else.

MERGE also works on relationships, and the safe habit is to merge the two nodes first and then the relationship between the bound variables:

CYPHER
MERGE (a:Person {email: '[email protected]'})
MERGE (c:Company {name: 'Acme'})
MERGE (a)-[w:WORKS_AT]->(c)
ON CREATE SET w.since = 2019;

Merging a whole path in one go, like MERGE (:Person {email: 'x'})-[:WORKS_AT]->(:Company {name: 'Acme'}), creates everything in the path if any part is missing, including a second copy of nodes that already exist.

JS MERGE is idempotent, CREATE is not

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Three CREATEs give three nodes; three MERGEs give one node whose ON MATCH property was refreshed on the second and third runs.

SET and REMOVE

CYPHER
MATCH (p:Person {email: '[email protected]'})
SET p.title = 'Countess',          // set or overwrite one property
    p += {city: 'London', age: 36} // add or overwrite several, keep the rest
RETURN p;

MATCH (p:Person {email: '[email protected]'})
SET p:Mathematician               // add a label
REMOVE p.age, p:Mathematician;    // remove a property and a label

MATCH (p:Person {email: '[email protected]'})
SET p.title = null;               // setting null also removes the property
  • SET p.x = value writes one property. SET p += {map} merges a map into the existing properties. SET p = {map} replaces all properties, so use it deliberately.
  • Labels are added with SET p:Label and removed with REMOVE p:Label.
  • Relationships have properties too: SET r.since = 2020.

DELETE and DETACH DELETE

Neo4j protects you from leaving dangling relationships. DELETE refuses to remove a node that still has relationships:

CYPHER
MATCH (p:Person {email: '[email protected]'})
DELETE p;
-- Error: Cannot delete node<...>, because it still has relationships.
-- To delete this node, you must first delete its relationships.

MATCH (p:Person {email: '[email protected]'})
DETACH DELETE p;       -- deletes the relationships, then the node

Delete one relationship by matching it with a variable: MATCH ()-[r:KNOWS]->() DELETE r. To empty a small test database you can run MATCH (n) DETACH DELETE n, but on large graphs that should be done in batches, because it is a single huge transaction.

flowchart LR
    A["DELETE node"] --> B{"Has relationships?"}
    B -->|"yes"| E["Error: delete them first"]
    B -->|"no"| D["Node removed"]
    F["DETACH DELETE node"] --> G["Remove all relationships"] --> D

DELETE protects the graph from dangling relationships; DETACH DELETE removes them for you.

JS DELETE versus DETACH DELETE

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Constraints and indexes

MERGE is only as safe as the lookup is fast and unambiguous. Two concurrent MERGEs for the same new email can, without a constraint, both find nothing and both create the node. A uniqueness constraint closes that gap and also gives you an index:

CYPHER
CREATE CONSTRAINT person_email_unique IF NOT EXISTS
FOR (p:Person) REQUIRE p.email IS UNIQUE;

CREATE CONSTRAINT person_has_name IF NOT EXISTS
FOR (p:Person) REQUIRE p.name IS NOT NULL;   -- property existence (Enterprise Edition)

CREATE INDEX person_name_idx IF NOT EXISTS
FOR (p:Person) ON (p.name);

SHOW CONSTRAINTS;
SHOW INDEXES;

With the constraint in place, a second node with the same email fails with a constraint violation instead of silently creating a duplicate. Property-existence and key constraints are Enterprise Edition features; uniqueness constraints are available in Community Edition. A constraint that conflicts with existing data cannot be created until you clean the data first.

Indexes speed up lookups by label and property, which matters for the first MATCH of every query (the next chapters return to this in Query performance: indexes, EXPLAIN and PROFILE). Create indexes for the properties you search by, not for every property: each index slows writes a little and uses space.

JS A uniqueness constraint rejects duplicates

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second Ada is rejected and the data stays consistent. In Neo4j the check is made by the index behind the constraint, so it is fast and also safe under concurrency.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You run MERGE (p:Person {email: '[email protected]'}) five times. How many Person nodes with that email exist?

    MERGE looks for the pattern first and only creates it when nothing matches, so repeated runs are idempotent.
  2. 2. Why should the MERGE pattern contain only the identifying properties?

    Every property in the MERGE pattern must match. Merge on the key and use SET (or ON CREATE / ON MATCH) for the rest.
  3. 3. What does DELETE do to a node that still has relationships?

    Plain DELETE refuses to leave dangling relationships. DETACH DELETE removes the relationships first.
  4. 4. Which statement makes e-mail addresses unique among Person nodes?

    A uniqueness constraint rejects duplicates and also creates the index used to look values up. A plain index only speeds up lookups.

Summary

  • MERGE finds or creates a pattern and is safe to repeat; merge on the identity, then SET the rest, with ON CREATE and ON MATCH for the differences.
  • SET p.x, SET p += {map} and SET p:Label change data; REMOVE and SET p.x = null take properties away; SET p = {map} replaces everything.
  • DELETE refuses connected nodes; DETACH DELETE removes relationships and the node, and should be batched on large graphs.
  • Uniqueness constraints stop duplicates even under concurrency; indexes speed lookups. Create them for the properties you match on.
  • The stand-ins model these rules in memory; the Cypher was not run here.

Next: Paths, aggregation and WITH.