Complex Match Statement

Can you confirm that if the city is part of a region, that only this pattern exists for it:

(country)<-[:REGION_OF]-(region)<-[:CITY_OF]-(city)
and not this pattern
(country)<-[:CITY_OF]-(city)

We basically want to make sure we don't count cities twice if both patterns exist for a city.

If that holds true, then we can do something like this, recognizing that only a 3-node path contains the region.

MATCH path = (country:Country)<-[:REGION_OF | CITY_OF*]-(city:City)
RETURN country.name as country, CASE WHEN length(path) = 2 THEN nodes(path)[1].name ELSE null END as region, city.name as city

EDIT
Whoops, I put the wrong length check in there, length is based on number of relationships, not nodes. Query fixed.

1 Like