Post-UNION processing


(Andrew Bowman) #1

Cypher currently does not allow further processing of UNION results, since RETURN is required in all queries of the union. There are a couple ways around this.

Combine collections, then UNWIND back to rows and apply DISTINCT

MATCH (m:Movie)
WITH collect(m) AS movies
MATCH (p:Person)
WITH movies + collect(p) AS moviesAndPeople
UNWIND moviesAndPeople AS movieOrPerson
#### ..

DISTINCT isn't really needed in the above query, but it will be needed if it's possible for a result to be present in multiple collections being combined, provided you want distinct values.

Use to return UNION results from a subquery

In Neo4j 3.0.x and newer, using APOC Procedures, you can use to execute a UNION within a subquery, and return its results.

 MATCH (movieOrPerson:Movie)
 RETURN movieOrPerson
 MATCH (movieOrPerson:Person)
 RETURN movieOrPerson',
 {}) yield value
WITH value.movieOrPerson as movieOrPerson
#### ..

Remember that procedure calls are executed per-row, so using this approach when multiple rows already exist may lead to unintended and unexpected results.