Rahul Patel
Rahul Patel

Reputation: 53

How to find shortest path between nodes on a directed graph in neo4j?

Using graph algorithms extension and the inbuilt shortest-path search in neo4j does not look at the direction of the relationships as long as 2 nodes are connected. Is there a way to query the graph db to include the directionality of the relationships connecting nodes, or would you have to code dijikstra's from scratch without leveraging neo4j and its graph algorithm library capabilities?

I'm currently using a query structured in this fashion:

MATCH (start:Db_Nodes{uid:"xxx"}),(end:Db_Nodes{uid:"yyy"}) CALL algo.shortestPath.stream(start, end, "weight") YIELD nodeId, cost MATCH (node) WHERE id(node) = nodeId RETURN node

Upvotes: 0

Views: 448

Answers (1)

cybersam
cybersam

Reputation: 66989

The APOC procedure apoc.algo.dijkstra should work for you.

For instance, if you want the shortest weighted path with only outgoing relationships from start to end (regardless of relationship type):

MATCH (start:Db_Nodes{uid:"xxx"}), (end:Db_Nodes{uid:"yyy"})
CALL apoc.algo.dijkstra(start, end, '>', 'weight') YIELD path, weight AS totalWeight
RETURN path, totalWeight;

Upvotes: 1

Related Questions