I'm using Neo4j and trying to write a Cypher query for the following:
I have nodes labeled :Person and :Club.
A (:Person)-[:MEMBER_OF]->(:Club) relationship connects people to clubs.
I want to find all other clubs that the members of a specific club also belong to.
For example, if:
Alice and Bob are members of "Chess Club",
and Alice is also in "Hiking Club",
I want the query to return "Hiking Club".
Here's what I tried:
MATCH (p:Person)-[:MEMBER_OF]->(c:Club)
WHERE c.name = 'Chess Club'
WITH p
MATCH (p)-[:MEMBER_OF]->(other:Club)
WHERE other.name <> 'Chess Club'
RETURN DISTINCT other.name
But this returns nothing, even though I’ve confirmed some members of "Chess Club" are in other clubs too.
Try this:
MATCH (p:Person)-[:MEMBER_OF]->(c:Club)
with distinct p.name as pname, collect(distinct c.name) as clubs
return pname, size(clubs) as clubCount, clubs order by clubCount desc
I ran your query I got the 'Hiking Club' as the result
Here is my sample code to create the nodes.
merge (a:Person {name:'Alice'})
merge (a1:Person {name: 'Bob'})
merge (b:Club {name:'Chess Club'})
merge (b1:Club {name: 'Hiking Club'})
merge (a)-[:MEMBER_OF]->(b)
merge (a)-[:MEMBER_OF]->(b1)
merge (a1)-[:MEMBER_OF]->(b)
return a, a1, b, b1
I am not sure the solution is what you asked for. I thought you asked that 'for a specific gym', find the 'other gyms' that the members of the given gym are also a member of. In that case, your query should work. I found the correct solution with my test data and your query. I also wrote the query slightly different than you, as I feel it better explains what the intent is.
Note: In your version of the query, you have to specify the gym names are not equal in the second match. This is because you separated the two matches; therefore, the query will traverse the same MEMBER_OF relationship back to the same club. Putting the two match patterns in one line avoids this, as cypher will not traverse the same relationship multiple times when in the same match statement. You can see this if you place the two match patterns in the same match.