Combine two cypher queries

87 Views Asked by At

Currently this is the data stored in the database

Org Name   Org ID
A            1
B            2
C            5
D            9  

I'm trying to combine these 2 queries:

MATCH (n:Org)
WHERE n.id in [1,2]
RETURN n.name as group1_name, n.id as group1_id

MATCH (n:Org)
WHERE n.id in [5,9]
RETURN n.name as group2_name, n.id as group2_id

I need the result to be shown like this:

group1_id   group1_name   group2_id   group1_name
1                A           5          C
2                B           9          D
1

There are 1 best solutions below

0
cybersam On BEST ANSWER

Assuming the two id lists are always the same size (in your example, 2), here is one approach (assuming you also want the id values sorted in ascending order):

MATCH (n:Org)
WHERE n.id in [1, 2]
WITH n ORDER BY n.id
WITH COLLECT(n) AS ns
MATCH (m:Org)
WHERE m.id in [5, 9]
WITH ns, m ORDER BY m.id
WITH ns, COLLECT(m) AS ms
UNWIND [i IN RANGE(0, SIZE(ns)-1) | {a: ns[i], b: ms[i]}] AS row
RETURN
  row.a.id as group1_id, row.a.name as group1_name,
  row.b.id as group2_id, row.b.name as group2_name

And here is a simpler approach:

WITH [1, 2] AS xs, [5, 9] AS ys
UNWIND RANGE(0, SIZE(xs)-1) AS i
MATCH (n:Org), (m:Org)
WHERE n.id = xs[i] AND m.id = ys[i]
RETURN n.id as group1_id, n.name as group1_name, m.id as group2_id, m.name as group2_name

And finally, if the xs and ys lists are passed to the query as parameters:

UNWIND RANGE(0, SIZE($xs)-1) AS i
MATCH (n:Org), (m:Org)
WHERE n.id = $xs[i].id AND m.id = $ys[i].y
RETURN n.id as group1_id, n.name as group1_name, m.id as group2_id, m.name as group2_name