Q&A

# Search paths where all nodes are in a relationship with same node

+1
−0

Using the below graph as an example: I am trying to determine all Persons which are_sons of Persons all born in the same country.

Is there an elegant way to achieve this with Cypher?

Why should this post be closed?

I'm having a hard time understanding exactly what you want from your query. Can you detail it in some sort of pseudocode instead of a sentence? (For example, do any of the nodes in this example graph match your query criteria? If ‘Ann’ is a match, is it because all of her parents which have a birth country have the same birth country? Or is it because all of her non-adoptive parents have the same birth country? Or is it that she has at least two parents with the same birth country?) r~~‭ 3 days ago

What I want is for Ann to be returned because all her Parents are from the USA. The reason why I introduced "adoptive" parents is because: 1- This is an example (I'm not actually working with a Graph with parents ;) ) 2 - I wanted to make it clear that you do not know how many parents a person has -> so has not to accept "counting 2" strategies. Maybe I should have a picked a complete abstract example. Guilherme Costa‭ 3 days ago

So should Steve be linked to USA in the graph then? r~~‭ 3 days ago

Of course... Really sorry about that. Updated the picture Guilherme Costa‭ 3 days ago

+2
−0

Something like this query should work for you:

``````MATCH (a:Person)-[:IS_SON]->()-[:WAS_BORN]->(b:Country)
WITH a, count(DISTINCT b) AS birthplaces
WHERE birthplaces = 1
RETURN a
``````

Note that this query would return people who have parents with unknown birthplaces, since those paths won't be included in the `MATCH` clause. If you have that case in your database and want to exclude it, then I think you lose a little elegance:

``````MATCH (a:Person)-[:IS_SON]->(p:Person)
OPTIONAL MATCH (p)-[:WAS_BORN]->(b:Country)
WITH a, count(p) AS parents, count(b) AS birthplaces, count(DISTINCT b) as distinct_birthplaces
WHERE parents = birthplaces AND distinct_birthplaces = 1
RETURN a
``````