Use the result of Union as input for another match

Hi,

I am using UNION to combine the result of two queries into a single node list, which works as expected. However I would like to use this combined node set as input for the next match and I can't seem to get it right...

MATCH(n).....
RETURN n
UNION
MATCH(n).....
RETURN n
WITH n
MATCH(x)....->(n)
RETURN n, x;

Written as-is, it complains about the second RETURN not being at the end of the query.
If I omit it, the WITH part is interpreted as part of the second query.

Thank you in advance, Clemens

Try this structure:

Call () {
  MATCH(n).....
  RETURN n
  UNION
  MATCH(n).....
  RETURN n
{
WITH n
MATCH(x)....->(n)
RETURN n, x;
1 Like

Thank you very much - using call to actually introduce some kind of query hierarchy worked perfectly fine - I only had to omit the empty braces:

Call {
  MATCH(n).....
  RETURN n
  UNION
  MATCH(n).....
  RETURN n
}
WITH n
MATCH(x)....->(n)
RETURN n, x;
1 Like

I don't think you need the WITH n statement.

At that point in the query, n is the only variable in scope, so you are not dropping variables out of scope, you are not introducing a new variable, you are not adding reads after writes, you are not filtering aggregates, you are not sorting results, you are not applying limits or where clauses
-> You do not need WITH

If you want more info on the WITH statement, see docs for WITH clause.

Empty braces are the recommended syntax from version 5.23 onwards, not available in previous versions.