MERGE
ensures that a pattern exists in the graph. Either the pattern already exists, or parts of it need to be
created.
MERGE
either matches existing nodes and binds them, or it creates new data and binds that. It’s like a combination
of MATCH
and CREATE
that additionally allows you to specify what happens if the data was matched or created.
For example, you can specify that the graph must contain a node for a user with a certain name. If there isn’t a node with the correct name, a new node will be created and its name property set.
As with MATCH
, MERGE
can match multiple occurrences of a pattern. If there are multiple matches, they will all be
passed on to later stages of the query.
The last part of MERGE
is the ON CREATE
and ON MATCH
. These allow a query to express additional changes to the
properties of a node or relationship, depending on if the element was MATCH
ed in the database or if it was CREATE
d.
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 properties match 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
The query creates the Keanu node, and sets a timestamp on creation time. If Keanu already existed, a different property would have been set.
Result
keanu |
---|
1 row |
Nodes created: 1 |
Properties set: 2 |
Labels added: 1 |
|
Copyright © 2013 Neo Technology