Gremlin:在一行代码中根据两个计数计算除法

Gremlin: Calculate division of based on two counts in one line of code

我有两个计数,计算如下:

1)g.V().hasLabel('brand').where(__.inE('client_brand').count().is(gt(0)) ).count()

2)g.V().hasLabel('brand').count()

并且我想要得到一行代码,结果是第一个计数除以第二个。

这是一种方法:

g.V().hasLabel('brand').
  fold().as('a','b').
  math('a/b').
    by(unfold().where(inE('client_brand')).count())
    by(unfold().count())

请注意,我将第一次遍历简化为 .where(inE('client_brand')).count(),因为您只关心计算至少有一条边,没有必要计算所有边并进行比较。

您还可以union()喜欢:

g.V().hasLabel('brand').
  union(where(inE('client_brand')).count(),
        count())
  fold().as('a','b').
  math('a/b').
    by(limit(local,1))
    by(tail(local))

虽然第一个更容易 read/follow,但我想第二个更好,因为它只存储两个计数的列表,而第一个存储所有 "brand" 我猜这会占用更多内存。

Daniel Kuppitz 提供的另一种方式以一种有趣的方式使用 groupCount()

g.V().hasLabel('brand').
  groupCount().
    by(choose(inE('client_brand'),
                constant('a'),
                constant('b'))).
  math('a/(a+b)')

以下使用 sack() 步骤的解决方案说明了为什么我们有 math() 步骤:

g.V().hasLabel('brand').
  groupCount().
    by(choose(inE('client_brand'),
                constant('a'),
                constant('b'))).
  sack(assign).
    by(coalesce(select('a'), constant(0))).
  sack(mult).
    by(constant(1.0)). /* we need a double */
  sack(div).
    by(select(values).sum(local)).
  sack()

如果你可以使用 lambda,那么:

g.V().hasLabel('brand').
  union(where(inE('client_brand')).count(),
        count())
  fold().
  map{ it.get()[0]/it.get()[1]} 

这对我有用:

g.V().limit(1).project('client_brand_count','total_brands')
.by(g.V().hasLabel('brand')
.where(__.inE('client_brand').count().is(gt(0))).count())
.by(g.V().hasLabel('brand').count())
.map{it.get().values()[0] / it.get().values()[1]}
.project('brand_client_pct')