10
votes

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

2
Are you required to use Cypher? I can think of some gremlin scripts that will print this out that should be pretty neat looking.Nicholas
In fact I'm using nodeJs.. And I have a library to query my neo4j graph that allow me to do some cypher query ... and not gremlin query...Guillaume le Floch

2 Answers

11
votes

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.

4
votes

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.