Syl
Syl

Reputation: 1164

aggregate data and still use changefeed in rethinkDB

I'm enjoying learning reQL so far but I stumbled upon a problem.

This is the data that I have stored in a table called events

[{
  "date": "Tue Mar 17 2015 00:00:00 GMT+00:00" ,
  "id":  "00dacebd-b27e-49b5-be4b-42c2578db4bb" ,
  "event_name":  "View page" ,
  "total": 4 ,
  "unique": 4
},
{
  "date": "Mon Mar 16 2015 00:00:00 GMT+00:00" ,
  "id":  "09ac3579-960b-4a2b-95be-8e018d683494" ,
  "event_name":  "View page" ,
  "total": 68 ,
  "unique": 35
},
{
  "date": "Tue Mar 17 2015 00:00:00 GMT+00:00" ,
  "id":  "0bb01050-e93d-4845-94aa-b86b1198338d" ,
  "event_name":  "Click" ,
  "total": 17 ,
  "unique": 8
},
{
  "date": "Mon Mar 16 2015 00:00:00 GMT+00:00" ,
  "id":  "174dcf3e-7c77-47b6-a05d-b875c9f7e563" ,
  "event_name":  "Click" ,
  "total": 113 ,
  "unique": 35
}]

And I would like the end result to look like this

[{
  "date": "Mon Mar 16 2015 00:00:00 GMT+00:00",
  "Click": 113,
  "View Page": 68
},
{
  "date": "Tue Mar 17 2015 00:00:00 GMT+00:00",
  "Click": 17,
  "View Page": 4
}]

The closet I got was with this query:

r.table("events").orderBy({index: r.desc('date')}).group('date').map(function(event) {
  return r.object(event('repo_name'), event('unique'));
}).reduce(function(a, b) {
  return a.merge(b.keys().map(function(key) {
    return [key, a(key).default(0).add(b(key))];}).coerceTo('object'));
})

The results is:

[{
  "date": "Mon Mar 16 2015 00:00:00 GMT+00:00",
  "reduction": {
    "Click": 113,
    "View page": 68
  }
},
{
  "group": "Tue Mar 17 2015 00:00:00 GMT+00:00",
  "reduction": {
    "Click": 17,
    "View page": 4
  }
}]

However as you can see the events are nested under reduction and changefeeds won't work on this query either :(

Anyone can point me in the right direction?

Cheers,

Upvotes: 1

Views: 246

Answers (1)

mlucy
mlucy

Reputation: 5289

You can change the group/reduction format like this:

query.ungroup().map(function(row){
  return r.expr({date: row('group')}).merge(row('reduction'));
})

Unfortunately changefeeds on aggregations aren't supported as of 1.6, but that should be possible in 2.2 or 2.3 (so in a few months).

Upvotes: 3

Related Questions