【问题标题】:Finding the median in gremlin在 gremlin 中找到中位数
【发布时间】:2022-01-09 19:21:59
【问题描述】:

我想通过以下查询找到某个分组的中位数:

g.V().
  groupCount().
    by('someProp').
  order(local).
    by(values, asc).
  sideEffect(unfold().
    count().as('size').
    math('size/2').store('middle')).
    unfold().
    select(values).
  skip(select('middle')).limit(1)

但我很难在跳过中使用“中间”变量。 完成此类查询的“gremlin”方式是什么?

【问题讨论】:

  • 这是一个有趣的问题。我不确定我以前是否考虑过这个用例。我最初的想法是,也许indexgroup 的某种组合可以用来创建一个可以按数字选择的组。但是,math 步骤将产生双精度结果,这是一个复杂的问题,因此 `sack 可能是一种替代方法。我会考虑一下这个。
  • 经过一番思考,我在下面添加了一个答案,希望能满足您的需求。

标签: gremlin


【解决方案1】:

使用这个测试图

g.addV('Person').property(id,'p1').property('age',28).
  addV('Person').property(id,'p2').property('age',36).
  addV('Person').property(id,'p3').property('age',22).
  addV('Person').property(id,'p4').property('age',55).
  addV('Person').property(id,'p5').property('age',22).
  addV('Person').property(id,'p6').property('age',28).
  addV('Person').property(id,'p7').property('age',28).
  addV('Person').property(id,'p8').property('age',63)  

groupCount 产生

gremlin> g.V().
......1>   groupCount().
......2>     by('age').
......3>   order(local).
......4>     by(values, asc)

==>[36:1,55:1,63:1,22:2,28:3]   

从那里我们可以使用与原始问题类似的计算,但使用 sack 作为计算将产生整数结果。

gremlin> g.V().
......1>   groupCount().
......2>     by('age').
......3>   order(local).
......4>     by(values, asc).
......5>   sack(assign).by(count(local)).
......6>   sack(div).by(constant(2)).sack()

==>2 

从那里我们可以索引排序的地图

gremlin> g.V().
......1>   groupCount().
......2>     by('age').
......3>   order(local).
......4>     by(values, asc).
......5>   sack(assign).by(count(local)).
......6>   sack(div).by(constant(2)).
......7>   index().
......8>   unfold().as('a')
==>[36=1,0]
==>[55=1,1]
==>[63=1,2]
==>[22=2,3]
==>[28=3,4]    

剩下的就是只选择与我们计算出的sack 值匹配的项目。

gremlin> g.V().
......1>   groupCount().
......2>     by('age').
......3>   order(local).
......4>     by(values, asc).
......5>   sack(assign).by(count(local)).
......6>   sack(div).by(constant(2)).
......7>   index().
......8>   unfold().as('a').
......9>   where(eq('a')).
.....10>     by(sack()).
.....11>     by(tail(local))  

==>[63=1,2]  

我们还可以更进一步,从最终结果中删除索引。

gremlin> g.V().
......1>   groupCount().
......2>     by('age').
......3>   order(local).
......4>     by(values, asc).
......5>   sack(assign).by(count(local)).
......6>   sack(div).by(constant(2)).
......7>   index().
......8>   unfold().as('a').
......9>   where(eq('a')).
.....10>     by(sack()).
.....11>     by(tail(local)).
.....12> limit(local,1)

==>63=1    

【讨论】:

  • 谢谢! @Kelvin Lawrence
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-08
  • 2021-06-04
  • 1970-01-01
相关资源
最近更新 更多