0
votes

I'm new to Neo4j and Cypher. I have a large graph of people related by friendship and I would like to get all of the paths starting from 1 person but stopping at a friend from another state. I need to show the first friend from the other state but none of his/her friends. Basically, I want the path to end when it find a node who's related friend is not from the specified state. Any help would be greatly appreciated.

Jack {st:'MI'}<-[Friend]-Jill {st:'MI'}<-[Friend]-John {st:'OH'}<-[Friend]-Tim {st:'OH'}

Query should only return Jack, Jill and John. Not Tim.

Edit/Addition

John <-[Friend]-Joan {st:'MI'}

Joan should also not be returned in the query.

Thanks!

1

1 Answers

0
votes

How about something like this. Match all of the friend that are in the same state and then take the end of that path and match all of the friends next to the end that are from a different state.

MATCH path=(start:Person {name: 'Jack'})<-[:FRIEND*]-(end:Person)
WHERE end.st = start.st
AND all(p in nodes(path) where p.st = start.st)
WITH path, end
RETURN nodes(path), [(end)<-[:FRIEND]-(other:Person) WHERE other.st <> end.st | other]  as other_state

This query will only return the rows where there are other_state nodes.

MATCH path=(start:Person {name: 'Joe'})<-[:FRIEND*..10]-(end:Person)
WHERE end.st = start.st
AND all(p in nodes(path) where p.st = start.st)
WITH nodes(path) as same_state, [(end)<-[:FRIEND]-(other:Person) WHERE other.st <> end.st | other]  as other_state
WHERE size(other_state) > 0
RETURN same_state, other_state

Changed so would accommodate the John, Joan and Tim use case

MATCH path=(start:Person {name: 'John'})-[:FRIEND*0..]-(end:Person)
WHERE end.st = start.st
AND all(p in nodes(path) where p.st = start.st)
WITH nodes(path) as same_state, [(end)-[:FRIEND]-(other:Person) WHERE other.st <> end.st | other]  as other_state
WHERE size(other_state) > 0
RETURN same_state, other_state