graphtitangremlintinkerpop

How to propagate a value in a TinkerPop graph


How would I 'propagate' a value through a TinkerPop graph? i.e. given a value of a property on one vertex, I want to 'move' that value along an edge to another vertex, or set of vertices.

Example, given this simple graph of 3 vertices and 2 edges connecting them:

gremlin> graph = TinkerGraph.open()
==>tinkergraph[vertices:0 edges:0]
gremlin> g = graph.traversal()
==>graphtraversalsource[tinkergraph[vertices:0 edges:0], standard]
gremlin> a = g.addV('name','a','amount', 100).next()
==>v[0]
gremlin> b = g.addV('name','b','amount', 0).next()
==>v[3]
gremlin> c = g.addV('name','c','amount', 0).next()
==>v[6]
gremlin> a.addEdge('drain', b, 'factor', 0.5)
==>e[9][0-drain->3]
gremlin> b.addEdge('drain', c, 'factor', 0.1)
==>e[10][3-drain->6]
gremlin> 

I wish to run some kind of operation on this graph such that the amount in a gets copied to b multiplied by the factor in the edge connecting them. E.g. b['amount'] would equal 50. Then propagated further c['amount'] would equal 5.

Ideally I'd like to know a single statement that could propagate the value all the way down the chain in one go, but also a statement that might propagate it to just the first adjacent vertex then on second invocation would propagate it to the next vertex, etc.

Is this something that can be accomplished simply in Gremlin, or do I need some other part of TinkerPop?


Solution

  • I managed to do this using Gremlin sacks:

    gremlin> g.withSack(a.value('amount')).
               V(a).repeat(outE('drain').sack(mult).by('factor').
                           inV().property('amount', sack())).
                    until(__.outE('drain').count().is(0)).iterate()
    gremlin> g.V().valueMap()
    ==>[amount:[100],name:[a]]
    ==>[amount:[50.0],name:[b]]
    ==>[amount:[5.00],name:[c]]
    

    I initialized the "sack value" equal to the "amount" in vertex "a" and begin the traversal there iteratively traversing out on the "drain" edges where we multiply (i.e. mult) the value in the sack by the "factor" property on the "drain" edges. The sack then gets assigned to the next vertex via the property() step.

    Note that you could control the "drain" (i.e. how far down the chain you'd like to go) with the appropriate looping semantics on repeat. Right now it uses until() "there are no more outgoing edges". But you might also terminate just ones step away as follows:

    gremlin> g.withSack(a.value('amount')).
               V(a).repeat(outE('drain').sack(mult).by('factor').
                           inV().property('amount', sack())).
                    times(1).iterate()
    gremlin> g.V().valueMap()
    ==>[amount:[100],name:[a]]
    ==>[amount:[50.0],name:[b]]
    ==>[amount:[0],name:[c]]