Take the 2-minute tour ×

I'd like to traverse my weighted graph from a starting node to a certain depth and print the traversal nodes and cumulative weight.

For instance, in a graph like this: A--1--B--2--C--1--D, A--1--B--1--F--1--G starting node A with depth 3 should return the following: A,B,F,G,cost:3

I had some progress using the following code but it does not calculate the weight of the paths:


How can I write it to calculate the cost and traversal list of the path also?

Thanks in advance...

share|improve this question
add comment

2 Answers

I think you can to .path, see http://gremlindocs.com/#transform/path and calculate from there.

share|improve this answer
add comment

I tried not to modify the front of your Gremlin too much and calculate from the end of your path expression. Maybe there's a better way to approach this, but here's what I have using the toy graph:

gremlin> g = TinkerGraphFactory.createTinkerGraph()
==>tinkergraph[vertices:6 edges:6]
gremlin> g.v(1).outE.inV.loop(2){it.loops<3}{true}.path 
==>[v[1], e[7][1-knows->2], v[2]]
==>[v[1], e[8][1-knows->4], v[4]]
==>[v[1], e[9][1-created->3], v[3]]
==>[v[1], e[8][1-knows->4], v[4], e[10][4-created->5], v[5]]
==>[v[1], e[8][1-knows->4], v[4], e[11][4-created->3], v[3]]

So note the inclusion of the outE.inV so that the edge appears in the path. Then I add a second closure to the path to get the weight out of the edge:

gremlin> g.v(1).outE.inV.loop(2){it.loops<3}{true}.path{it.name}{it.weight}
==>[marko, 0.5, vadas]
==>[marko, 1.0, josh]
==>[marko, 0.4, lop]
==>[marko, 1.0, josh, 1.0, ripple]
==>[marko, 1.0, josh, 0.4, lop]

Then it's just a bunch of Groovy JDK to manipulate that output into a summed weight:

gremlin> g.v(1).outE.inV.loop(2){it.loops<3}{true}.path{it.name}{it.weight}.transform{it.toList().split{i->"${i}".isNumber()}}.collect{[it[0].sum(),it[1]]}
==>[0.5, [marko, vadas]]
==>[1.0, [marko, josh]]
==>[0.4, [marko, lop]]
==>[2.0, [marko, josh, ripple]]
==>[1.4000000059604645, [marko, josh, lop]]

so, I tack in a transform (as Peter suggested), split the list of items into those that are weights and those that are names (just by checking if the value "isNumber"...you might need a different approach) and then I run a map function over that to sum() the collection of weights and return the collection of names.

share|improve this answer
Great! It works!.. Thank you very much. –  Hako Mar 8 '13 at 17:16
add comment

Your Answer


