1
votes

I have a Neo4j graph where each node is a person. Each person has two properties: Name and City. And the relationships are: friend_of and love.

I'm trying to get the nodes that have friends ONLY in their same city (A live in Paris, B in Paris, C in Madrid, D in Madrid, A-[friend_of]->B, B-[friend_of]->C a A-[friend_of]->C, D-[friend_of]->C I only need to get A and D because their friends live in their same city and only there) and order them by City first and then by Name.

I have tried the following:

MATCH (n)-[r:FRIEND_OF]-(n1) WHERE (n.City = n1.City) RETURN n,n1 ORDER BY n.City, n.Name

That gives me the nodes wanted, but some of them are wrong too (they have friends in other cities).

Thank you!

2
I fail to understand how B can be part of the output you expect. B (in Paris) is friend with someone (C) from a different city (Madrid). Can you detail a bit more what it is you exactly want?fbiville
You are right i made a mistake typing, the output expected is only D because is the only one who his friends live and only live in the same city than him. I hace corrected it now.carlos
Oh by the way when someone is friend of other, that means there is a biridectional relationship (A friend of B, B friend of A)carlos

2 Answers

2
votes

Based on the following neo4j console http://console.neo4j.org/r/5c2n8h, this query returns you only D as wanted :

MATCH (user:User)-[:FRIEND_OF]-(friend)
WITH user, collect(friend) AS friends
WHERE ALL (f IN friends WHERE f.City = user.City)
RETURN user
ORDER BY user.City, user.name
1
votes

Try this:

MATCH (u:User {name:"carlos"})-[:FRIEND_OF]-(f:User) 
WITH u, collect(f) as friends
WHERE ALL(f in friends WHERE f.City = u.City)
UNWIND friends as friend
RETURN friend
ORDER BY friend.City, friend.Name