aSoler
aSoler

Reputation: 145

Neo4j filtering nodes with only one type of relationship

I'm new with neo4j and I'm stuck in this exercise. I have to find the names and cities of the students who only have friends in their city. The graph is something like this: enter image description here

The name of the relationship is "FRIEND_OF", and the color represents the city.

Thanks so much.

Upvotes: 0

Views: 611

Answers (1)

Christophe Willemsen
Christophe Willemsen

Reputation: 20185

As the city property is stored on the node, you can add a WHERE clause :

MATCH (user:User)
MATCH (user)-[:FRIEND_OF]-(friend)
WHERE user.city = friend.city
RETURN user.name, collect(distinct(friend)) as friends

EDIT If you want to return users where all his friends lives in the same city, try this one :

MATCH (user:User)-[:FRIEND_OF]->(friend)
WITH user, collect(friend) AS friends
WHERE ALL (x IN friends 
           WHERE x.city = user.city)
RETURN user

Upvotes: 2

Related Questions