Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all Routes between two nodes neo4j

Tags:

neo4j

cypher

I'm working on a project where I have to deal with graphs... I'm using a graph to get routes by bus and bike between two stops.

The fact is,all my relationship contains the time needed to go from the start point of the relationship and the end.

In order to get the shortest path between to node, I'm using the shortest path function of cypher. But something, the shortest path is not the fastest....

Is there a way to get all paths between two nodes not linked by a relationship?

Thanks

EDIT:

In fact I change my graph, to make it easier. So I still have all my nodes. Now the relationship type correspond to the time needed to go from a node to another.

The shortestPath function of cypher give the path which contains less relationship. I would like that it returns the path where the addition of all Type (the time) is the smallest.. Is that possible?

Thanks

like image 892
Guillaume le Floch Avatar asked Feb 11 '13 14:02

Guillaume le Floch


2 Answers

In cypher, to get all paths between two nodes not linked by a relationship, and sort by a total in a weight, you can use the reduce function introduced in 1.9:

start a=node(...), b=node(...) // get your start nodes
match p=a-[r*2..5]->b // match paths (best to provide maximum lengths to prevent queries from running away)
where not(a-->b) // where a is not directly connected to b
with p, relationships(p) as rcoll // just for readability, alias rcoll
return p, reduce(totalTime=0, x in rcoll: totalTime + x.time) as totalTime
order by totalTime

You can throw a limit 1 at the end, if you need only the shortest.

like image 174
Eve Freeman Avatar answered Sep 23 '22 12:09

Eve Freeman


You can use the Dijkstra/Astar algorithm, which seems to be a perfect fit for you. Take a look at http://api.neo4j.org/1.8.1/org/neo4j/graphalgo/GraphAlgoFactory.html

Unfortunately you cannot use those from Cypher.

like image 43
Mattias Finné Avatar answered Sep 26 '22 12:09

Mattias Finné