4

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.

Falmarri
  • 47,727
  • 41
  • 151
  • 191

2 Answers2

3
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
Michael Hunger
  • 41,339
  • 3
  • 57
  • 80
0

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
ean5533
  • 8,884
  • 3
  • 40
  • 64