Skip to content

Instantly share code, notes, and snippets.

@peterneubauer
Forked from mebibou/simple-map
Last active December 21, 2015 06:59
Show Gist options
  • Save peterneubauer/6268488 to your computer and use it in GitHub Desktop.
Save peterneubauer/6268488 to your computer and use it in GitHub Desktop.

Tracing bus lines with neo4j

The setup

This is a simple bus map, containing one line line1 and line2 and line3, set as a property on the connecting releationships between bus stops.

CREATE (s1:Stop:Line1:Line2 { name:"First Stop" })
CREATE (s2:Stop:Line1 { name:"Second Stop" })
CREATE (s3:Stop:Line1 { name:"Third Stop" })
CREATE (s4:Stop:Line1 { name:"Fourth Stop" })
CREATE (s5:Stop:Line1 { name:"Fifth Stop" })
CREATE (s6:Stop:Line1 { name:"Sixth Stop" })
CREATE (s7:Stop:Line1:Line3 { name:"Seventh Stop" })
CREATE (s8:Stop:Line2 { name:"Eigth Stop" })
CREATE (s9:Stop:Line3 { name:"Nineth Stop" })
CREATE (s1)-[:STOPS_STOPS { lineId:1 }]->(s2)
CREATE (s2)-[:STOPS_STOPS { lineId:1 }]->(s3)
CREATE (s3)-[:STOPS_STOPS { lineId:1 }]->(s4)
CREATE (s1)-[:STOPS_STOPS { lineId:1 }]->(s4)
CREATE (s4)-[:STOPS_STOPS { lineId:1 }]->(s5)
CREATE (s4)-[:STOPS_STOPS { lineId:1 }]->(s6)
CREATE (s6)-[:STOPS_STOPS { lineId:1 }]->(s7)
CREATE (s8)-[:STOPS_STOPS { lineId:2 }]->(s1)
CREATE (s7)-[:STOPS_STOPS { lineId:3 }]->(s9)

Find the start and end points for line1

START stop = node(*)
MATCH line=(s1:Stop:Line1)-[r:STOPS_STOPS*]->(s2:Stop:Line1),
      (:Stop:Line1)-[before?:STOP_STOPS]->(s1),
      (s2)-[after?:STOP_STOPS]->(:Stop:Line1)
WHERE ALL (n IN nodes(line) WHERE n:Stop:Line1) AND before IS NULL AND after IS NULL
RETURN s1, s2, length(line) AS length
ORDER BY length DESC

Find all the stops for Line 1 to create a map

Here, all the stops that make up the line should be found in order to create a map in a way that lists the longest paths first.

MATCH line=(stop1)-[r:STOPS_STOPS*]->(stop2)
WHERE ALL (rel IN RELATIONSHIPS(line)
           WHERE rel.lineId=1)
RETURN line, length(line) AS length
ORDER BY length DESC

console

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment