Merging nodes
To merge a single node with a label:Merging paths
Because MERGE either matches or creates a full path, it is easy to accidentally create duplicate nodes. For example, if we run the following query on our sample graph:On Match and On Create directives
Using ON MATCH and ON CREATE, MERGE can set properties differently depending on whether a pattern is matched or created. In this query, we’ll merge paths based on a list of properties and conditionally set a property when creating new entities:Frequently Asked Questions
What is the difference between CREATE and MERGE?
What is the difference between CREATE and MERGE?
CREATE always creates new entities. MERGE first checks if a matching pattern already exists; if found it binds to existing entities, otherwise it creates them. MERGE prevents duplicates.
How do I avoid creating duplicate nodes with MERGE?
How do I avoid creating duplicate nodes with MERGE?
Use separate MERGE clauses for each entity rather than merging a full path. For example:
MERGE (a {name: 'Alice'}) MERGE (b {name: 'Bob'}) MERGE (a)-[:KNOWS]->(b) ensures no duplicate nodes.What are ON CREATE SET and ON MATCH SET?
What are ON CREATE SET and ON MATCH SET?
These directives let you conditionally set properties depending on whether MERGE created a new entity or matched an existing one. For example,
ON CREATE SET n.created = timestamp() only runs when a new node is created.Can MERGE create relationships between previously matched nodes?
Can MERGE create relationships between previously matched nodes?
Yes. Use MATCH to bind existing nodes, then MERGE the relationship:
MATCH (a {name: 'Alice'}) MATCH (b {name: 'Bob'}) MERGE (a)-[:KNOWS]->(b). This creates the relationship only if it does not already exist.