Reputation: 23
I want to get all the nodes which are not connected to the given set of nodes. Suppose I've 5 nodes A,B,C,D,E. Now A->B->C are connected with the :Is_Friend
relationship. Now I want all the nodes which are not connected to A (i.e D and E).
I tried this query but it's not working
MATCH (a:Friend{name:"A"})-[:Is_Friend_Of*]->(b:Friend)
MATCH (c:Friend)
WHERE NOT (c)-[:Is_Friend_Of]->(b)
RETURN c
Upvotes: 2
Views: 2975
Reputation: 1
Try this query:
match(a:Friend {name: "A"})-[:Is_Friend_Of*]-(b)
with collect(distinct b) as all_connected_to_a
match(n:Friend) where not n in all_connected_to_a return n;
It firstly gets a uniqued collection of all nodes connected to (a:Friend {name: "A"})
(including node a, because the pattern -[:Is-Friend_Of*]-
is not directional).
Then it returns all nodes which are not in that collection i.e. they are not connected to (a:Friend {name: "A"})
through relationship of type :Is_Friend_Of
.
Upvotes: 0
Reputation: 11216
Thi query should do what you want it to, however, I would caution that depending on the size of the number of unmatched friends in your database you could get a lot of matches.
// match the single longest chain of friends in a :Is_Friend_Of relationship
// starting with 'A' that is possible
MATCH path=(a:Friend {name:"A"})-[:Is_Friend_Of*]->(b:Friend)
WHERE NOT (b)-[:Is_Friend_Of*]->()
WITH path
// then find the other friends that aren't in that path
MATCH (c:Friend)
WHERE NOT c IN nodes(path)
RETURN c
Upvotes: 2