orestisf
orestisf

Reputation: 353

Cypher query: how to filter a MATCH based on a previous result?

I'm working with a graph model that looks like the one below (source). enter image description here

I want to find all domestic flights for a particular country, that is flights that have both a DESTINATION and SOURCE flight in an airport that belongs to that country. This is the Cypher query I'm working on:

MATCH (cr:Country {name:'Italy'})<-[:EXIST]-(ct:City)<-[:IS_IN]-(ai:Airport)
WITH ai
MATCH (ai)-[:DESTINATION|:SOURCE]-(f:Flight)-[:OF]-(ar:Airline)
WITH ar as airline, count(distinct(f)) as flights
ORDER BY flights DESC
RETURN airline.name, flights
LIMIT 10

The problem with the above query is that it will also return flights with a DESTINATION or SOURCE that is not in Italy. Can you help me to rephrase the query to get the correct results?

Upvotes: 1

Views: 316

Answers (1)

nimrod serok
nimrod serok

Reputation: 16033

Your query is allowing the SOURCE OR the DESTINATION to be in Italy. You want both of them to be in Italy. One option is something like:

MATCH (:Country {name:'Italy'})<-[:EXIST]-(:City)<-[:IS_IN]-(:Airport)-[:SOURCE]-(f:Flight)-[:DESTINATION]-(:Airport)-[:IS_IN]->(:City)-[:EXIST]->(:Country {name:'Italy'})
WITH distinct(f) as flights
MATCH (flights)-[:OF]-(ar:Airline)
WITH ar as airline, count(flights) as flights
ORDER BY flights DESC
RETURN airline.name, flights
LIMIT 10

Upvotes: 3

Related Questions