condit
condit

Reputation: 10962

Grouping UNIONed Cypher Results

I have a cypher query like this that works fine:

MATCH path = (start)-[]-(some)-[]-(path)-[]-(end)
RETURN start, end, path
UNION
MATCH path = (start)-[]-(some)-[]-(other)-[]-(path)-[]-(end)
RETURN start, end, path

The only problem is that in some cases the same start and end nodes may match both patterns resulting in duplicates (with respect to start and end). Is there a cypher way to

RETURN DISTINCT start, end, COLLECT(path)

for the result of a UNION? Something like a SQL subquery?

Upvotes: 1

Views: 52

Answers (1)

Martin Preusse
Martin Preusse

Reputation: 9369

I think you can't collect over multiple RETURN in a UNION. There is an open issue on GitHub requesting something similar: https://github.com/neo4j/neo4j/issues/2725

If start and end matter, you could MATCH them first and then try to MATCH the different paths:

MATCH (start), (end)
// try to match the different paths
OPTIONAL MATCH path_a = (start)-[]-(some)-[]-(path)-[]-(end)
OPTIONAL MATCH path_b = (start)-[]-(some)-[]-(other)-[]-(path)-[]-(end)
RETURN DISTINCT start, end, path_a, path_b

Not sure if that would work in you case, but it would give you one result row for each pair of start/end.

Upvotes: 2

Related Questions