2
votes

Sample query
The following query returns me the count of a label say "Asset " for a particular id (0) has >>>
g.V().hasId(0).repeat(out()).emit().hasLabel('Asset').count()

But I need to find the count for all the nodes that are present in the graph with a condition as above.

I am able to do it individually but my requirement is to get the count for all the nodes that has that label say 'Asset'.

So I am expecting some thing like

{ v[0]:2
      {v[1]:1}
           {v[2]:1}
}
where v[1] and v[2] has a node under them with a label say "Asset" respectively, making the overall count v[0] =2 .

1

1 Answers

2
votes

There's a few ways you could do it. It's maybe a little weird, but you could use group()

g.V().
  group().
    by().
    by(repeat(out()).emit().hasLabel('Asset').count())

or you could do it with select() and then you don't build a big Map in memory:

g.V().as('v').
  map(repeat(out()).emit().hasLabel('Asset').count()).as('count').
  select('v','count')

if you want to maintain hierarchy you could use tree():

g.V(0).
  repeat(out()).emit().
  tree().
    by(project('v','count').
         by().
         by(repeat(out()).emit().hasLabel('Asset')).select(values))

Basically you get a tree from vertex 0 and then apply a project() over that to build that structure per vertex in the tree. I had a different way to do it using union but I found a possible bug and had to come up with a different method (actually Gremlin Guru, Daniel Kuppitz, came up with the above approach). I think the use of project is more natural and readable so definitely the better way. Of course as Mr. Kuppitz pointed out, with project you create an unnecessary Map (which you just get rid of with select(values)). The use of union would be better in that sense.