Created
October 13, 2012 13:17
-
-
Save tommorris/3884600 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.neo4j.graphdb.{Direction,DynamicRelationshipType,GraphDatabaseService,Node,Relationship,RelationshipType,Transaction} | |
import org.neo4j.kernel.Traversal | |
import org.neo4j.graphalgo.GraphAlgoFactory | |
import org.neo4j.graphdb.factory.GraphDatabaseFactory | |
import scala.collection.JavaConversions._ | |
def orderedListToRelation[T](lst: List[T]): List[Pair[T, T]] = { | |
val p = new scala.collection.mutable.ArrayBuffer[Pair[T, T]]() | |
for (i <- 1 to lst.size - 1) | |
p += Pair(lst(i - 1), lst(i)) | |
p.toList | |
} | |
val graph = new GraphDatabaseFactory().newEmbeddedDatabase("target/neo4j-hello-db") | |
val tx = graph.beginTx() | |
val stations = List("Ore", "Hastings", "St Leonards Warrior Square", "West St Leonards", "Crowhurst", "Battle", "Robertsbridge", "Etchingham", "Stonegate", "Wadhurst", "Frant", "Tunbridge Wells", "High Brooms", "Tonbridge", "Hildenborough", "Sevenoaks", "Orpington", "London Bridge") | |
val stationNodes = tubeStations.map { item => | |
val node = graph.createNode() | |
node.setProperty("name", item) | |
node | |
} | |
val rel = DynamicRelationshipType.withName("connects") | |
orderedListToRelation(stationNodes).foreach { pair => | |
pair._1.createRelationshipTo(pair._2, rel) | |
pair._2.createRelationshipTo(pair._1, rel) | |
} | |
tx.success() | |
def pathBetweenStations(graph: GraphDatabaseService, start: Node, end: Node): List[Node] = { | |
val rel = DynamicRelationshipType.withName("connects") | |
val shortestPathFinder = GraphAlgoFactory.shortestPath(Traversal.expanderForTypes(rel, Direction.BOTH), 1000) | |
shortestPathFinder.findSinglePath(stationNodes.first, stationNodes.last).nodes.toList | |
} | |
def pathBetweenStationsById(graph: GraphDatabaseService, start: Int, end: Int): List[Node] = { | |
pathBetweenStations(graph, graph.getNodeById(start), graph.getNodeById(end)) | |
} | |
val shortestPath = pathBetweenStationsById(graph, 1, 36) | |
shortestPath.nodes().toList.foreach(station => println(station.getProperty("name"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment