Reputation: 5597
I have three types of nodes:
(:Meal), (:User), (:Dish)
With relationships:
(:Meal)<-[:JOIN]-(:User), (:Meal)<-[:ORDERED]-(:Dish)
Now I want to fetch the information of meal in one query. I want to get result like this:
id: 1
name: xxx,
users: [1,2,3,4],
dishes: [23,42,42]
where users and dishes fields contains the ids of those users and dishes.
I tried:
MATCH (meal:Meal)
OPTIONAL MATCH (meal)<-[:JOIN]-(user:User)
OPTIONAL MATCH (meal)<-[:ORDERED]-(dish:Dish)
RETURN id(meal), meal.name, COLLECT(ID(user)), COLLECT(ID(dish))
However, this query will generate a lot duplication of users and dishes. If there are N users and M dishes, it will match N*M user-dish pairs.
I do realize that I can use DISTINCT to remove duplication. However, I am not sure about the efficiency of such query.
Is there any better way?
Upvotes: 2
Views: 122
Reputation: 39925
Try to separate the different parts of your query using WITH
:
MATCH (meal:Meal)
OPTIONAL MATCH (meal)<-[:JOIN]-(user:User)
WITH meal, collect(ID(user)) as users
OPTIONAL MATCH (meal)<-[:ORDERED]-(dish:Dish)
RETURN id(meal), meal.name, users, COLLECT(ID(dish)) as dishes
Upvotes: 2