Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rethinkdb execute multiple avg in one query

I have a review table with multiple number columns. I would like to count he avg of all columns in one query.

So if the table looks like:

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

then i would like to get the avg for each column in one query. I know I can do:

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

on each column but I would like to do this in just one query and map into into just one object.

Any ideas on how to do this?

like image 543
John Avatar asked Mar 22 '26 00:03

John


1 Answers

You can use map with reduce (if every record in table has all 3 fields):

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"))
  };
})

If record can have not all fields, you can separate count in map operation for each field, and then in do use it depending on field.

like image 188
Suvitruf - Andrei Apanasik Avatar answered Mar 26 '26 15:03

Suvitruf - Andrei Apanasik