Rethinkdb 在一个查询中执行多个 avg

Rethinkdb execute multiple avg in one query

我的评论 table 包含多个数字列。我想计算一个查询中所有列的平均值。

所以如果 table 看起来像:

{ 
   foo : 2,
   bar : 5,
   foobar : 10
},
{
   foo : 4,
   bar : 3,
   foobar : 12
}

然后我想在一个查询中获取每一列的平均值。我知道我能做到:

r.table('stats' ).avg( 'foo' )

在每一列上,但我想在一个查询中执行此操作并映射到一个对象中。

关于如何做到这一点有什么想法吗?

您可以使用 map with reduce(如果 table 中的每条记录都包含所有 3 个字段):

r.table("stats").map(function(row){
  return {foo : row("foo"), bar : row("bar") , foobar : row("foobar"), count : 1};
}).reduce(function(left, right){
  return {foo : left("foo").add(right("foo")), bar : left("bar").add(right("bar")), foobar : left("foobar").add(right("foobar")), count : left("count").add(right("count"))};
}).do(function (res) {
  return {
    foo: res('foo').div(res("count")),
    bar: res('bar').div(res("count")),
    foobar: res('foobar').div(res("count"))
  };
})

如果record不能有所有字段,可以在map操作中对每个字段分开count,然后在do中根据字段使用。