简体   繁体   中英

Cypher query to reach a terminal node

I have the following data structure for a bus service. A city node has many buses to other city node which again has many buses to other city node.

Bus and city are uniquely identified by their id.

(a:city)-[r:To]->(b:City)->[r:To]->(c:City)-[r:To]->(d:City)

Node City has properties:cityId(int) relationship To has prop:busId(int),arrivalTime(int).

Question:

Given a cityId and a busId how to write a cypher query to get the route of the bus ie all city from start to destination sorted by the arrivalTime.

The cityId provided above ensures that the bus starts from that city.

My Guess

Match (a:City)-[r:To*]->(b:City) where a.cityId=cityid and r.busId=busId return r,b. order by r.arrivalTime

I think that this will give you what you want (requires Neo4j 2.0.1 or later).

MATCH (c:City)-[legs:TO*]->(terminus)
WHERE c.cityId = { cityId } 
      AND ALL (leg IN legs WHERE leg.busId = { busId })
      AND NOT (terminus)-[:TO {busId: { busId }}]->()
RETURN [leg IN legs | 
        {city: endNode(leg).cityId, arrival: leg.arrivalTime}] 
       AS stops

Three things to note here.

  • When handling the legs we need to use collection operations because of the variable length paths.
  • Given a leg, we can extract information about the city it ends in with the endnode() function.
  • We use a negated pattern to identify the terminus of the route, otherwise we get a result for each possible path length.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM