cancel
Showing results for 
Search instead for 
Did you mean: 

Merge when either property1 is the same OR when property2 is the same

MPasadu
Node Link

I am trying to basically write a cypher that will use merge with an or condition:

pseudo imaginary code:

if node exists with property id != 0 and (id == 1 or path == "c:\hello")
then set id=1, path="d:\bye", otherProperties="x"
else create node with id=1, path=path="d:\bye", otherProperties="x"

The or is what is making problems for me when using merge (n:Node {id:x, path:y}). Since a merge will always create a new node when one property is different. In my case it should merge the existing node when either id or path are equal.

I came up with the following cypher (which has errors):

optional match (n:Node)
where 
    n.id <> '0'
    and
    (n.id = '1'
    or
    n.path = "c:\\hello")
with n
CALL apoc.do.when(n = null, 'create (n2:Node {id:1, path:"c:\\bye", otherProperties="x"})','set n.id=1, path="c:\bye", otherProperties=x',{n:n}) yield value 
with value as ignored
return ignored

What is the correct way to do it?

1 ACCEPTED SOLUTION

Maybe something like this before you go into apoc.do.when?

OPTIONAL MATCH (n1:Node {})
WITH n1
OPTIONAL MATCH (n2:Node{})
WITH [n1,n2] as arr
unwind arr as nodes
WITH nodes
CALL apoc.do.when(count(nodes) = 0 //create a new node...

View solution in original post

3 REPLIES 3

lju
Neo4j
Neo4j

Hi!

Not sure if I've understood correctly, but we do recommend if you're going to use MERGE, you will get more predictable results if you MERGE only on the unique property (which I assume is id in this case) and then use either ON CREATE SET or ON MATCH SET to then create/update any additional properties.

MPasadu
Node Link

It's like an edge case. Because the node basically has two unqiue properties: id or(exclusive) path.
So there can't be nodes that have a duplicate path or id. That's why I can't use 'merge'.

If there is a node that already has the id, please match it.
If there is a node that already has the path, please match it.
If both are unique create a new node.

Maybe something like this before you go into apoc.do.when?

OPTIONAL MATCH (n1:Node {})
WITH n1
OPTIONAL MATCH (n2:Node{})
WITH [n1,n2] as arr
unwind arr as nodes
WITH nodes
CALL apoc.do.when(count(nodes) = 0 //create a new node...

Nodes 2022
Nodes
NODES 2022, Neo4j Online Education Summit

On November 16 and 17 for 24 hours across all timezones, you’ll learn about best practices for beginners and experts alike.