Gongotar
Gongotar

Reputation: 43

Cypher return a node with the given neighbors

I'm trying to write a query in Cypher which is able to find a single node with the label :CONVERSATION having the given neighbor nodes. The neighbor nodes are users with the label :USER and a property called "username". In the query a list of "username"s is given and a desired is to find a conversation node which has as its neighbor all the users with the username in the given list. I have tried some queries but they don't return what I want. Is there anyone who has any idea how the query may look like?

Upvotes: 1

Views: 1187

Answers (1)

Christophe Willemsen
Christophe Willemsen

Reputation: 20185

Assuming you are passing the given usernames as a {users} parameters and the relationship between your users and the conversations is named IN_CONVERSATION :

MATCH (c:Conversation)
WHERE ALL( x IN {users} WHERE (:User {name:x} )-[:IN_CONVERSATION]->(c) )
RETURN c

If you want to test the query by passing the usernames in the neo4j browser for eg, you can simulate the parameters with WITH :

WITH ["adam","john","sally"] AS users
MATCH (c:Conversation)
WHERE ALL( x IN users WHERE (:User {name:x} )-[:IN_CONVERSATION]->(c) )
RETURN c

Another solution is to match first the users also :

MATCH (u:User) WHERE u.name IN {users}
MATCH (c:Conversation)
WHERE ALL( x IN collect(u) WHERE (x)-[:IN_CONVERSATION]->(c) )
RETURN c

Upvotes: 4

Related Questions