SET¶
The SET clause is used to update properties on nodes and relationships.
Set Node Properties¶
Set Single Property¶
Set Multiple Properties¶
Set from Map¶
Warning: This replaces ALL properties!
Set with += (Add Properties)¶
This preserves existing properties and adds/updates specified ones.
Set Relationship Properties¶
MATCH (a:User)-[r:KNOWS]->(b:User)
WHERE a.name = 'Alice' AND b.name = 'Bob'
SET r.strength = 0.9, r.updated = datetime()
RETURN r
Add Labels¶
Add Single Label¶
Add Multiple Labels¶
Set with Parameters¶
Python example:
graph.query("""
MATCH (u:User {name: $name})
SET u.age = $age
RETURN u
""", {
'name': 'Alice',
'age': 29
})
Conditional Set¶
Set Based on Condition¶
MATCH (u:User)
SET u.status = CASE
WHEN u.age < 18 THEN 'minor'
WHEN u.age >= 65 THEN 'senior'
ELSE 'adult'
END
Set If Property Exists¶
Increment/Decrement¶
Increment Counter¶
Decrement Value¶
Set from Expressions¶
Computed Values¶
String Operations¶
Date/Time Operations¶
MATCH (u:User)
SET u.lastLogin = datetime(),
u.sessionExpiry = datetime() + duration('PT1H')
RETURN u
Set All Properties¶
Copy all properties from one node to another:
MATCH (source:User {name: 'Alice'}),
(target:User {name: 'Bob'})
SET target = properties(source)
RETURN target
Set NULL (Remove Property)¶
Or use REMOVE:
Bulk Updates¶
Update All Matching Nodes¶
Update with UNWIND¶
UNWIND [
{name: 'Alice', age: 29},
{name: 'Bob', age: 33}
] AS update
MATCH (u:User {name: update.name})
SET u.age = update.age
Common Patterns¶
Update or Create Timestamp¶
MATCH (u:User {name: 'Alice'})
SET u.updated = datetime()
SET u.created = coalesce(u.created, datetime())
RETURN u
Increment View Counter¶
MATCH (p:Post {id: $postId})
SET p.views = coalesce(p.views, 0) + 1,
p.lastViewed = datetime()
RETURN p
Toggle Boolean¶
Add to Array¶
Update Based on Relationship¶
MATCH (u:User)-[:POSTED]->(p:Post)
WITH u, count(p) AS postCount
SET u.totalPosts = postCount
RETURN u
Normalize Data¶
MATCH (u:User)
SET u.email = toLower(trim(u.email)),
u.name = trim(u.name)
WHERE u.email IS NOT NULL
RETURN count(u) AS normalized
Set Default Values¶
SET with CREATE¶
SET with MERGE¶
MERGE (u:User {email: $email})
ON CREATE SET
u.name = $name,
u.created = datetime()
ON MATCH SET
u.lastSeen = datetime()
RETURN u
Performance Tips¶
-
Batch Updates
-
Use += for Partial Updates
-
Index Updated Properties
-
Minimize Property Writes
Common Mistakes¶
Overwriting All Properties¶
// WRONG: Removes all other properties
MATCH (u:User {name: 'Alice'})
SET u = {age: 29} // name is now gone!
// CORRECT: Use +=
MATCH (u:User {name: 'Alice'})
SET u += {age: 29} // name is preserved
Not Handling NULL¶
// WRONG: Error if credits is NULL
SET u.credits = u.credits + 10
// CORRECT: Handle NULL
SET u.credits = coalesce(u.credits, 0) + 10
Next Steps¶
- Create data with CREATE
- Delete data with DELETE
- Match patterns with MATCH
- Read Cypher Introduction