MERGE made a new Node
MERGE is a powerful and misunderstood component of the CYPHER toolbox.
Assume you have two :Person nodes each with a name property ('Adam' and 'Bob').You might assume that you could MERGE as follows to create a [:KNOWS] relationship:
MERGE (a:Person {name:'Adam'})-[r:KNOWS]->(b:Person {name:'Bob'});
and you'd be correct, it works perfectly
Always remember MERGE is based on matching the entire pattern in the statement.
Say you now want to set the age of Adam to 21 in the same statement. You might think it's as simple as
MERGE (a:Person {name:'Adam',age:21})-[r:KNOWS]->(b:Person {name:'Bob'});
will create 2 new Person nodes and a [:KNOWS] relationship. If there is a unique constraint on :Person (name) there will be errors thrown and no new nodes or relationships.
Why, the initial part of the MERGE 'looks' for a pattern match on the :Person node of name:'Adam' and age:21, it doesn't create a property. No match is found so the entire pattern is created.
It is more correct to break things down:
MERGE (a:Person {name:'Adam'})
MERGE (b:Person {name:'Bob'})
SET a.age = 21
MERGE (a)-[r:KNOWS]->(b);
As with most things programming related, Keep it Simple.
Comments
Post a Comment