MERGE
either matches existing nodes and binds them, or it creates new data and binds that. For example, you can
search for a user node by id, and if the node does not already exist in the database, it will create it.
MERGE
is not only used for single nodes - just like MATCH
, if multiple nodes match, they will all be
bound to the identifier.
The following graph is used for the examples below:
Merging a single node with a given label.
Query.
merge (robert:Critic) RETURN robert, labels(robert)
Because there are no nodes labeled Critic in the database, a new node is created.
Merging a single node with properties where not all matches any existing node.
Query.
merge (charlie {name:'Charlie Sheen', age:10}) RETURN charlie
A new node with the name Charlie Sheen will be created since not all properties matched the existing Charlie Sheen node.
Merging a single node with both label and property matching an existing node.
Query.
merge (michael:Person {name:'Michael Douglas'}) RETURN michael
Michael Douglas will be matched and returned
Merge a node and set properties if the node needs to be created.
Query.
merge (keanu:Person {name:'Keanu Reeves'}) on CREATE keanu SET keanu.created = timestamp() RETURN keanu
Creates the Keanu node, and sets a timestamp on creation time.
Result
keanu |
---|
1 row |
Nodes created: 1 |
Properties set: 2 |
Labels added: 1 |
|
Merging nodes and setting properties on found nodes.
Query.
merge (person:Person) on MATCH person SET person.found = true RETURN person
Finds all the :Person nodes, sets a property on them, and returns them.
Result
person |
---|
5 rows |
Properties set: 5 |
|
|
|
|
|
Merge a node and set properties if the node needs to be created.
Query.
merge (keanu:Person {name:'Keanu Reeves'}) on CREATE keanu SET keanu.created = timestamp() on MATCH keanu SET keanu.lastSeen = timestamp() RETURN keanu
Creates the Keanu node, and sets a timestamp on creation time. If Keanu already existed, a different property would be set
Result
keanu |
---|
1 row |
Nodes created: 1 |
Properties set: 2 |
Labels added: 1 |
|
Copyright © 2013 Neo Technology