问题
How can I write a query that gets nodes that have relationships to ALL nodes of a set. For example:
START n=node:people("username:*"),
g=node:groups("groupname:A groupname:B")
MATCH n-[:M]->g
RETURN n
This returns users that have relationships to A or B. But I want users that have relationships to A and B. I can't figure out how to do it though.
Edit:
I need to do this for an arbitrary number of groups, not just A and B. And the reason I'm using index syntax is that this is from user input, so it could be this:
START n=node:people("username:*"),
g=node:groups("groupname:*")
MATCH n-[:M]->g
RETURN n
And I would need to return users that have the M relationship with ALL groups.
回答1:
START n=node:people("username:*"),
g=node:groups("groupname:*")
with n, collect(g) as groups
MATCH n-[:M]->ug
with n, collect(ug) as user_groups
where ALL(g in groups WHERE g in user_groups)
RETURN n
it might even work like this (should be faster)
START n=node:people("username:*"),
g=node:groups("groupname:*")
with n, collect(g) as groups
MATCH n-[:M]->ug
WHERE ug in groups
with n, count(*) as found, length(groups) as group_count
WHERE found = group_count
RETURN n
回答2:
Separate groups A and B into distinct variables and then ensure each match exists individually.
START n=node:people("username:*"),
gA=node:groups("groupname:A"),
gB=node:groups("groupname:B")
MATCH n-[:M]->gA, n-[:M]->gB
RETURN n
来源:https://stackoverflow.com/questions/15979677/neo4j-match-multiple-relationships