Given 3 expressions, cypher to pick unique node matching

31 views Asked by At

I have lot of nodes with properties/attributes: p1, p2, p3, p4, p5 etc;

Give an array of 3 regular expressions:

exp1 -> p1 = 1
exp2 -> p2 = 2 OR p3 = 3
exp3 -> p4 = 4 AND p5 = 5

Each expression match could result with 0, 1, or more nodes.

Can you help in writing single cypher query to pick the unique node, if any of the above expressions could matching with exactly one node?

Return null, if all given expressions match with more than 1 node OR no nodes.


What I tried?

Right now, I am using this query and wrote application code to check if any of the collection contains unique/only one node:

Optional MATCH (n1) WHERE n1.p1=1 WITH COLLECT(n1) as c1
Optional MATCH (n2) WHERE (n2.p2=2 OR n2.p3=3 ) WITH c1,COLLECT(n2) as c2
Optional MATCH (n3) WHERE (n3.p4=4 AND n3.p5=5 ) WITH c0,c1,COLLECT(n2) as c3
RETURN c1,c2,c3

What I want?

Rather than returning collections, If any of collection contains exactly 1 node, return it OR return null.

1

There are 1 answers

0
cybersam On

Here is a fairly efficient query:

OPTIONAL MATCH (n1) WHERE n1.p1=1
WITH n1 LIMIT 2
WITH COLLECT (n1) AS n1s
WITH CASE WHEN SIZE(n1s) = 1 THEN n1s[0] END AS n1

OPTIONAL MATCH (n2) WHERE n2.p2=2 OR n2.p3=3
WITH n1, n2 LIMIT 2
WITH n1, COLLECT (n2) AS n2s
WITH n1, CASE WHEN SIZE(n2s) = 1 THEN n2s[0] END AS n2

OPTIONAL MATCH (n3) WHERE n3.p4=4 AND n3.p5=5
WITH n1, n2, n3 LIMIT 2
WITH n1, n2, COLLECT (n3) AS n3s
WITH n1, n2, CASE WHEN SIZE(n3s) = 1 THEN n3s[0] END AS n3

RETURN n1, n2, n3

For each WHERE test it:

  • Stops looking for more nodes as soon as it finds 2 nodes,
  • Determines if a single node was found,
  • Assigns either the single node or NULL to the appropriate variable.