# Neo4j Features and Practical Usage
♻️ "Create it if missing, update it if present." Idempotent writes that never produce duplicate nodes—no matter how many times you replay an event stream—come down to a single `MERGE`.
🏷️ Title: CREATE / MERGE / SET / DELETE
🔗 URL:
📘 Overview
`MERGE` is an upsert clause: it matches and binds an existing pattern, or creates and binds it if absent. It fuses `MATCH` and `CREATE` so you can branch on whether the data existed beforehand. It is essential for making daily batches and stream ingestion idempotent.
⚙️ How It Works
・All-or-nothing: `MERGE` operates on the whole pattern—either everything matches or everything is created. It never partially reuses an existing pattern. To mix matching and creating, decompose into multiple `MERGE` clauses.
・`ON CREATE SET` / `ON MATCH SET`: property assignments that run only on create or only on match—handy for creation timestamps or access counters. Both can coexist.
・Merging relationships: at least one endpoint node must already be bound. An undirected `-[r:KNOWS]-` is tried both ways before creating left-to-right.
・Constraints: a uniqueness constraint gives `MERGE` conflict detection and prevents duplicates. For performance, creating an index on the label/property is strongly recommended (without it, every merge scans all nodes).
🛠️ Practical Usage
Idempotent upsert over an event stream:
```cypher
MERGE (u:User {id: row.userId})
MERGE (p:Page {url: row.url})
MERGE (u)-[v:VIEWED]->(p)
ON CREATE SET v.count = 1
ON MATCH SET v.count = v.count + 1
```
A standard pattern for creating derived nodes without duplicates:
```cypher
MATCH (person:Person)
MERGE (loc:Location {name: person.bornIn})
MERGE (person)-[r:BORN_IN]->(loc)
ON CREATE SET r.createdAt = timestamp()
```
💡 Use Cases
・Ingesting clickstream/IoT events, deduplicating the same user and page while accumulating counts.
・An ingestion layer where multiple pipelines write master data without ever doubling up entities.
⚠️ Caveats
・Always pair `MERGE` keys with a uniqueness constraint. Without one, concurrent runs can briefly create duplicates (constraints guarantee only eventual consistency).
・`MERGE` rejects `null` property values. Do conditional assignment with a later `SET`.
・You cannot cross-reference a node being created within the same `MERGE`. Match it first, or split into a `SET`.
・`DELETE` fails on a node that still has relationships; use `DETACH DELETE`.
#
Neo4j# #
Cypher#