user1132809
user1132809

Reputation: 45

Retrieve friends of node A's friends

Here is a simple social map. I am looking for friends of node 'A's friends.

CREATE (pa:Person { name: "A", from: "Sweden", learn: "surfing" }),
(pb:Person { name: "B", from: "London", title: "author" }),
(pc:Person { name: "C", from: "Paris" }),
(pd:Person { name: "D", from: "Pune" }),
(pe:Person { name: "E", from: "Bangalore" }),
(pf:Person { name: "F", from: "Chicago" }),
(pg:Person { name: "G", from: "Sudney" }),
(pa)-[:KNOWS {since: 2001}]->(pb),
(pa)-[:KNOWS {rating: 5}]->(pc),
(pa)-[:KNOWS]->(pd),
(pb)-[:KNOWS]->(pd),
(pb)-[:KNOWS]->(pe),
(pb)-[:KNOWS]->(pf),
(pc)-[:KNOWS]->(pd),
(pd)-[:KNOWS]->(pa),
(pd)-[:KNOWS]->(pg)

I ran following query.

MATCH (m:Person)-[:KNOWS]->(n:Person)-[:KNOWS]->(o:Person)
WHERE m.name="A"
return o;

It returns A, D, E, F, G

I was expecting to see only E, F, G nodes.

Can you please help, what is wrong here?

Upvotes: 1

Views: 64

Answers (1)

Kristjan Liiva
Kristjan Liiva

Reputation: 9559

It returns A, because A-[:KNOWS]->D-[:KNOWS]->A
It returns D, because A-[:KNOWS]->B-[:KNOWS]->D

You need to specify that m <> n <> o and m should not know o.

MATCH (m:Person)-[:KNOWS]->(n:Person)-[:KNOWS]->(o:Person) 
WHERE m.name="A" AND m<>o AND NOT (m)-[:KNOWS]->(o)
RETURN DISTINCT o;

See this: http://console.neo4j.org/r/8i2vvu

Upvotes: 1

Related Questions