Search code examples
gremlintinkerpoptinkerpop3azure-cosmosdb-gremlinapi

longest path by weight in gremlin


i what will be the best query to get heaviest path b/w 2 nodes in a directed graph in gremlin?

*I do have multiple paths, and sometime longest path is not the heaviest.

where each edge (not node) has an integer attribute (weight). weight range is 0<= weight <=12

thanks.


Solution

  • In general, the sack step can be used for such calculations. Using the air-routes data set the query below finds the longest 3-hop routes between two airports using the dist property on the edges to calculate the weights. Notice that I limit my query to only find a certain number of results and use loops to specify a maximum depth I am interested in searching. Without such constraints queries like this can run for a very long time in a highly connected graph.

    gremlin>  g.withSack(0).
    ......1>    V('3').
    ......2>    repeat(outE().sack(sum).by('dist').inV().simplePath()).
    ......3>    until(has('code','AGR').or().loops().is(4)).
    ......4>    has('code','AGR').
    ......5>    limit(5).
    ......6>    order().
    ......7>      by(sack(),desc).
    ......8>    local(union(path().by('code').by('dist'),sack()).fold())
    
    ==>[[AUS,4901,LHR,4479,BOM,644,AGR],10024]
    ==>[[AUS,5294,FRA,4080,BOM,644,AGR],10018]
    ==>[[AUS,1520,JFK,7782,BOM,644,AGR],9946]
    ==>[[AUS,1500,EWR,7790,BOM,644,AGR],9934]
    ==>[[AUS,1357,YYZ,7758,BOM,644,AGR],9759]