Search code examples
gremlingraph-databases

Gremlin: recursive summation


Given a simple MLM set of data:

g.addV('user').property('id', 1).as('1')
  addV('user').property('id', 2).as('2').
  addV('user').property('id', 3).as('3').
  addV('user').property('id', 4).as('4').
  addV('user').property('id', 5).as('5').
  addV('user').property('id', 6).as('6').
  addV('user').property('id', 7).as('7').
  addV('point').property('value', 5).as('p1')
  addV('point').property('value', 5).as('p2').
  addV('point').property('value', 5).as('p3').
  addV('point').property('value', 5).as('p4').
  addV('point').property('value', 5).as('p5').
  addV('point').property('value', 5).as('p6').
  addV('point').property('value', 5).as('p7').
  addE('sponsors').from('1').to('2').
  addE('sponsors').from('1').to('3').
  addE('sponsors').from('1').to('4').
  addE('sponsors').from('2').to('5').
  addE('sponsors').from('3').to('6').
  addE('sponsors').from('4').to('7').
  addE('hasPoints').from('1').to('p1').
  addE('hasPoints').from('2').to('p2').
  addE('hasPoints').from('3').to('p3').
  addE('hasPoints').from('4').to('p4').
  addE('hasPoints').from('5').to('p5').
  addE('hasPoints').from('6').to('p6').
  addE('hasPoints').from('7').to('p7').
  iterate()

How can I produce the following JSON:

{
  "1": x,
  "2": y,
  "3": z,
  ...
}

Where 1/2/3 are the user IDs, and x/y/z are the summation of the user's points and all his sponsored users' points (i.e. user1's points would be the sum of all users recursively under him - u2 + u3 + u4 + u5 + u6 + u7, and same of user2/3/4 etc).


Solution

  • You can achieve this by grouping the users by id and the sum of the points values

    g.V().hasLabel('user')
      group().by(id).
        by(repeat(out()).
          emit(hasLabel('point')).values('value').sum())
    

    example: https://gremlify.com/6j