cancel
Showing results for 
Search instead for 
Did you mean: 

Head's Up! These forums are read-only. All users and content have migrated. Please join us at community.neo4j.com.

Post-UNION processing

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
WITH DISTINCT 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 apoc.cypher.run() to return UNION results from a subquery

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

CALL apoc.cypher.run('
 MATCH (movieOrPerson:Movie)
 RETURN movieOrPerson
 UNION
 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.

0 REPLIES 0