Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find shortest path between nodes with additional filter

Tags:

neo4j

cypher

I'm trying to model flights between airports on certain dates. So far my test graph looks like this:

graph

Finding shortest path between for example LTN and WAW is trivial with:

MATCH (f:Airport {code: "LTN"}), (t:Airport {code: "WAW"}), 
p = shortestPath((f)-[]-(t)) RETURN p

Which gives me:

enter image description here

But I have no idea how to get only paths with Flights that have relation FLIES_ON with given Date.

Link to Neo4j console

like image 703
rzajac Avatar asked Jan 20 '15 20:01

rzajac


1 Answers

Here's what I would do with your given model. The other commenters' queries don't seem right, as they use ANY() instead of ALL(). You specifically said you only want paths where all Flight nodes on the path are attached to a given Date node with a :FLIES_ON relationship:

MATCH (LTN:Airport {code:"LTN"}),
      (WAW:Airport {code:"WAW"}), 
      p =(LTN)-[:ROUTE*]-(WAW)
WHERE ALL(x IN FILTER(x IN NODES(p) WHERE x:Flight) 
          WHERE (x)<-[:FLIES_ON]-(:Date {date:"130114"}))
WITH p ORDER BY LENGTH(p) LIMIT 1
RETURN p

http://console.neo4j.org/r/xgz84y

like image 194
Nicole White Avatar answered Nov 04 '22 16:11

Nicole White