0

I'm traversing a graph and need to obtain all leaf nodes sorted by an order property present on the edges.

I was only able to get the leaf vertices ordered by the last edge with the following query: g.V('n1').repeat(out()).emit().order().by(inE().values('order'))

Graph Example

In this example I wish I could get something like [n3, n4, n5, n3] or a map with the accumulated order for every vertice ([n3: 1.1, n3: 3, n4: 1.2, n5: 2])

1 Answers1

0

Your picture was nice but when asking questions about Gremlin it is best to add a small sample data script like this one:

g.addV().property(id,'n1').as('n1').
  addV().property(id,'n2').as('n2').
  addV().property(id,'n3').as('n3').
  addV().property(id,'n4').as('n4').
  addV().property(id,'n5').as('n5').
  addV().property(id,'n6').as('n6').
  addE('next').from('n1').to('n3').property('order',3).
  addE('next').from('n1').to('n2').property('order',1).
  addE('next').from('n1').to('n6').property('order',2).
  addE('next').from('n2').to('n3').property('order',1).
  addE('next').from('n2').to('n4').property('order',2).
  addE('next').from('n2').to('n5').property('order',3)

I opted to provide an answer that gives a "map with the accumulated order for ever vertex" - well, not quite a "map" because the "n3" key would not be able to be used twice. It returns pairs where the first item is the leaf vertex and the second item is a list of the "order" values traversed along the way:

gremlin> g.V('n1').
......1>   repeat(outE().inV()).
......2>     emit(__.not(outE())).
......3>   path().
......4>   map(union(tail(local,1), 
......5>             unfold().values('order').fold()).
......6>       fold())
==>[v[n3],[3]]
==>[v[n6],[2]]
==>[v[n3],[1,1]]
==>[v[n4],[1,2]]
==>[v[n5],[1,3]]

You can see I provided a condition to emit() to only produce the leaf vertices. I then transform the path() traversed using a map() which grabs the leaf vertex with tail(local,1)) for the first item in the pair and then unfolds the Path for "order" values for the second item in the pair.

stephen mallette
  • 45,298
  • 5
  • 67
  • 135