Sovos
Sovos

Reputation: 3390

neo4j cypher: stacking results with UNION and WITH

I'm doing a query like

MATCH (a)
WHERE id(a) = {id}

WITH a

MATCH (a)-->(x:x)-->(b:b)

WITH a, x, b

MATCH (a)-->(y:y)-->(b:b)

WITH a, x, y, b

MATCH (b)-->(c:c)

RETURN collect(a), collect(x), collect(y), collect(b), collect(c)

what I want here is to have the b from MATCH (a)-->(y:y)-->(b:b) to be composed of the ones from that line and the ones from the previous MATCH (a)-->(x:x)-->(b:b). The problem I'm having with UNION is that its picky about the number and kind of nodes to be passed on the next query, and I'm having trouble understanding how to make it all go together.

What other solution could I use to merge these nodes during the query or just before returning them? (Or if should I do it with UNION then how to do it that way...)

(Of course the query up there could be done in other better ways. My real one can't. That is just meant to give a visual example of what I'm looking to do.)

Much obliged!

Upvotes: 1

Views: 2529

Answers (2)

Sovos
Sovos

Reputation: 3390

The best solution I could come up in the end was something like this

MATCH (a)-->(x:x)-->(b1:b)-->(c1:c)
WHERE id(a) = {id} AND NOT (a)-->(:y)-->(b1)

WITH a, collect(x) as xs, collect(DISTINCT b1) as b1s, collect(c1) as c1s

MATCH (a)-->(y:y)-->(b2:b)-->(c2:c)

RETURN a, xs, collect(y), (b1s + collect(b2)), c1s + collect(c2)

Upvotes: 0

cybersam
cybersam

Reputation: 66957

This simplified query might suit your needs.

I took out all the collect() function calls, as it is not clear that you really need to aggregate anything. For example, there will only be a single 'a' node, so aggregating the 'a's does not make sense.

Please be aware that every row of the result will be for a node labelled either 'x' or 'y'. But, since every row has to have both the x and y values -- every row will have a null value for one of them.

START a=node({id})
MATCH (a)-->(x:x)-->(b:b)-->(c:c)
RETURN a, x, null AS y, b, c
UNION 
MATCH (a)-->(y:y)-->(b:b)-->(c:c)
RETURN a, null AS x, y, b, c

Upvotes: 2

Related Questions