You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
Now that you can read data with MATCH and WHERE, it is time to learn how to create, update, and delete data in Neo4j using Cypher.
The CREATE clause adds new nodes and relationships to the graph:
CREATE (p:Person {name: "Alice", age: 30})
RETURN p
CREATE (a:Person {name: "Alice", age: 30})
CREATE (b:Person {name: "Bob", age: 25})
RETURN a, b
MATCH (a:Person {name: "Alice"})
MATCH (b:Person {name: "Bob"})
CREATE (a)-[:FRIENDS_WITH {since: 2022}]->(b)
CREATE (a:Person {name: "Alice"})-[:WORKS_AT {role: "Engineer"}]->(c:Company {name: "Acme"})
RETURN a, c
Important:
CREATEalways creates new data. If a node with the same properties already exists, it will create a duplicate.
MERGE is the idempotent alternative to CREATE — it only creates data if it does not already exist:
MERGE (p:Person {name: "Alice"})
RETURN p
If a :Person node with name: "Alice" exists, it is returned. If not, it is created.
Execute different logic depending on whether the node was created or already existed:
MERGE (p:Person {name: "Alice"})
ON CREATE SET p.createdAt = datetime()
ON MATCH SET p.lastSeen = datetime()
RETURN p
MATCH (a:Person {name: "Alice"})
MATCH (b:Person {name: "Bob"})
MERGE (a)-[:FRIENDS_WITH]->(b)
Tip: Always
MERGEon the minimum set of properties that uniquely identify the node (typically a unique identifier or business key). Merging on too many properties can lead to unexpected duplicates.
The SET clause adds or updates properties on existing nodes and relationships:
MATCH (p:Person {name: "Alice"})
SET p.age = 31
RETURN p
MATCH (p:Person {name: "Alice"})
SET p.age = 31, p.email = "alice@example.com"
RETURN p
MATCH (p:Person {name: "Alice"})
SET p += {age: 31, city: "London"}
RETURN p
The += operator merges properties — existing properties not in the map are preserved.
MATCH (p:Person {name: "Alice"})
SET p:Employee
RETURN p
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.