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.

Details


Author:
Andrew Bowman
Applicable versions:
3.1, 3.0, 2.3, 2.2
Keywords:
cypherneo4j-2.2neo4j-2.3neo4j-3.0neo4j-3.1UNION