cancel
Showing results for 
Search instead for 
Did you mean: 

How to merge results neo4j

djole_nikolic_p
Node Clone

Hello people,
I have maybe silly question but regardless..
The query is the following:

MATCH (c:Category)<-[:CATEGORY_PERMISSION]-(p:Permission)
OPTIONAL MATCH (c)<-[:CATEGORY_STRUCTURE]-(child:Category)<-[:CATEGORY_PERMISSION]-(p2:Permission)
RETURN p, p2

I get category and its permissions, then I get children of the category and its permissions.
I want to merge them together when returning and only get distinct values so I have all permissions flattened.

1 ACCEPTED SOLUTION

anthapu
Graph Fellow

If you have apoc plugin installed this is a simple task

MATCH (c:Category)<-[:CATEGORY_PERMISSION]-(p:Permission)
OPTIONAL MATCH (c)<-[:CATEGORY_STRUCTURE]-(child:Category)<-[:CATEGORY_PERMISSION]-(p2:Permission)
WITH collect(p) as firstList, collect(p2) as secondlist
WITH apoc.coll.union(firstList, secondlist) as permissions
UNWIND permissions as permission
RETURN permission

Here I am using unwind to make sure you get permission object as return entity rather than a list.

If you can handle the list you can return the permissions value itself.

View solution in original post

2 REPLIES 2

anthapu
Graph Fellow

If you have apoc plugin installed this is a simple task

MATCH (c:Category)<-[:CATEGORY_PERMISSION]-(p:Permission)
OPTIONAL MATCH (c)<-[:CATEGORY_STRUCTURE]-(child:Category)<-[:CATEGORY_PERMISSION]-(p2:Permission)
WITH collect(p) as firstList, collect(p2) as secondlist
WITH apoc.coll.union(firstList, secondlist) as permissions
UNWIND permissions as permission
RETURN permission

Here I am using unwind to make sure you get permission object as return entity rather than a list.

If you can handle the list you can return the permissions value itself.

What I could do is also

collect(p) + collect(p2) as all
UNWIND all as single
RETURN distinct single

But I guess union is cleaner since it removes distincts
Thanks a lot