Union
This page describes how to create UNION clauses with the Cypher®.Union class.
Create a union between multiple queries by passing multiple clauses to the Cypher®.Union class to combine them.
Note that all clauses must be different instances, as Cypher® Builder clauses cannot be reused:
const returnVar = new Cypher.Variable();
const n1 = new Cypher.Node();
const query1 = new Cypher.Match(new Cypher.Pattern(n1, { labels: ["Movie"] })).return([n1, returnVar]);
const n2 = new Cypher.Node();
const query2 = new Cypher.Match(new Cypher.Pattern(n2, { labels: ["Movie"] })).return([n2, returnVar]);
const n3 = new Cypher.Node();
const query3 = new Cypher.Match(new Cypher.Pattern(n3, { labels: ["Movie"] })).return([n3, returnVar]);
const unionQuery = new Cypher.Union(query1, query2, query3);
This generates the following UNION clause:
MATCH (this0:Movie)
RETURN this0 AS var1
UNION
MATCH (this2:Movie)
RETURN this2 AS var1
UNION
MATCH (this3:Movie)
RETURN this3 AS var1
Note that this example uses the extra variable returnVar to make sure that all the queries return the same variable name.
Union all
Unions remove duplicates by default.
To keep all results, use the .all() method to create a UNION ALL clause instead:
const returnVar = new Cypher.Variable();
const n1 = new Cypher.Node();
const query1 = new Cypher.Match(new Cypher.Pattern(n1, { labels: ["Movie"] })).return([n1, returnVar]);
const n2 = new Cypher.Node();
const query2 = new Cypher.Match(new Cypher.Pattern(n2, { labels: ["Movie"] })).return([n2, returnVar]);
const n3 = new Cypher.Node();
const query3 = new Cypher.Match(new Cypher.Pattern(n3, { labels: ["Movie"] })).return([n3, returnVar]);
const unionQuery = new Cypher.Union(query1, query2, query3).all();
This generates the following UNION clause:
MATCH (this0:Movie)
RETURN this0 AS var1
UNION ALL
MATCH (this2:Movie)
RETURN this2 AS var1
UNION ALL
MATCH (this3:Movie)
RETURN this3 AS var1