Search code examples
neo4jcypher

Combining two results in cypher


I am trying to combine the result of two MATCH statements. for example like this

MATCH (a)-[:connection]-(b:labelB)
WHERE a.id IN $selection
WITH COLLECT(a) + COLLECT(b) AS selection

However, the issue with this is that it produces a list of type List<node> instead of node. This is an issue because it does not enable another MATCH statement using selection. Meaning this would not be possible as a continuation to the query:

MATCH (selection)-[]-(c)
RETURN c

This behavior can be achieved by a UNION but it seems to behave unexpectedly when using the result of the first MATCH in the second MATCH.

MATCH (a)
WHERE a.id IN $selection
RETURN a AS selection
UNION
MATCH (a)-[]-(b)
RETURN b AS selection

How can I combine two Nodes into a single value?


Solution

  • You can use UNWIND which is similar to a WHILE looping in sql.

    MATCH (a)-[:connection]-(b:labelB)
    WHERE a.id IN $selection
    WITH COLLECT(a) + COLLECT(b) AS selections
    UNWIND selections as selection
    MATCH (selection)-[]-(c)
    RETURN c