0

I have nodes with labels a, b, c, d and I want to search a node "node1" only from label "a" and label "b". If "node1" is found then return that node else create a node with label "a".

I tried to do like this:

Merge(n {id: "node1"})
on create set n:a
return n

The only problem in this is that it will search from labels from "a", "b", "c", "d" and it's very time consuming.

In short it's a ALLNODESCAN and I want to search only from labels "a" and "b".

1 Answers1

0

MERGE can't do this for multiple labels.

While you could use OPTIONAL MATCHes and then do your MERGE using the FOREACH hack for conditional execution (in the case that there is no node with that id for labels :A or :B), you won't be able to get a variable on the MERGEd node from within the FOREACH.

It may be better to use APOC conditional procedures to help here:

OPTIONAL MATCH (n:A {id: "node1"})
OPTIONAL MATCH (m:B {id: "node1"})
WITH coalesce(n, m) as node // returns first non-null value
CALL apoc.do.when(node is null, "MERGE (n:A {id:'node1'}) RETURN n", '', {}) YIELD value
RETURN coalesce(node, value.n) as n
InverseFalcon
  • 29,576
  • 4
  • 38
  • 51