SAB
SAB

Reputation: 175

Neo4j - apoc.algo.dijkstra - shortest path from a to b, but via c, d, e etc

Hi I am experimenting with routing using neo4j but I am struggling with adapting apoc.algo.dijkstra. I don’t just want to go from A to B, but actually go from A to B via C, whilst taking into account a weighting on the link.

The A-B query is...

MATCH  (startNode:road_node {id:'59030214550942348742a27d'}), (endNode:road_node {id:'59030215550942348742a610'})
call apoc.algo.dijkstra(startNode, endNode, 'ROADLINK', 'min_travel_time') YIELD path, weight
return path, weight/60

I tried a few ways of including a via c but can't get it to work... for example

MATCH  (startNode:road_node {id:'59030214550942348742a27d'}), (endNode:road_node {id:'59030215550942348742a610'})
call apoc.algo.dijkstra(startNode, endNode, 'ROADLINK', 'min_travel_time') 
with path, weight
MATCH (startNode)-[*]-(via:road_node {id:'59030215550942348742a666'})-[*]-(endNode)
return path, weight

Any ideas or suggestions on how to route from A to B via C, whilst taking into a count a weighting on the links, would be very helpful.

Upvotes: 0

Views: 1371

Answers (1)

cybersam
cybersam

Reputation: 67044

You can just invoke the Dijkstra algorithm twice, using via as the end node in the first invocation, and then as the start node in the second. The result will have 2 sub-paths and 2 sub-weights (divided by 60).

MATCH (start:road_node {id:'59030214550942348742a27d'}), (end:road_node {id:'59030215550942348742a610'}), (via:road_node {id:'59030215550942348742a666'})
CALL apoc.algo.dijkstra(start, via, 'ROADLINK', 'min_travel_time') YIELD path, weight
WITH end, via, path AS p1, weight/60 AS w1
CALL apoc.algo.dijkstra(via, end, 'ROADLINK', 'min_travel_time') YIELD path, weight
return p1, path AS p2, w1, weight/60 AS w2;

Upvotes: 2

Related Questions