RethinkDB组并与子数组合并为单个doc

时间:2016-02-15 21:13:45

标签: mapreduce grouping rethinkdb

使用子数组分组合并每次减少为单个文档的最佳方法?

r.expr([
  {id: 1, foo: 1, bar: 2, date: r.time(2016, 1, 1, 'Z')},
  {id: 1, foo: 4, bar: 1, date: r.time(2016, 1, 3, 'Z')},
  {id: 1, foo: 10, bar: 0, date: r.time(2016, 1, 2, 'Z')},

  {id: 2, foo: 5, bar: 3, date: r.time(2016, 1, 1, 'Z')},
  {id: 2, foo: 3, bar: 6, date: r.time(2016, 1, 2, 'Z')}
]).group('id').orderBy('date').map(function(d){
   return d
     .without('foo', 'bar', 'date')
     .merge({stats: [d.pluck('foo', 'bar', 'date')]})
 }).reduce(function(left, right){
   return left .without('stats').merge({
       stats: left('stats').append(right('stats')(0))
     })
 }).ungroup().map(function(g){
   return g('reduction')
 })

输出:

[
  {
    "id": 1 ,
    "stats": [
      {
        "foo": 1, "bar": 2 , "date": Fri Jan 01 2016 00:00:00 GMT+00:00 
      },
      {
        "foo": 10, "bar": 0 , "date": Sat Jan 02 2016 00:00:00 GMT+00:00 
      } ,
      {
        "foo": 4, "bar": 1 , "date": Sun Jan 03 2016 00:00:00 GMT+00:00 
      }
    ]
  },
  {
    "id": 2 ,
    "stats": [
      {
        "foo": 5, "bar": 3, "date": Fri Jan 01 2016 00:00:00 GMT+00:00
      } ,
      {
        "foo": 3, "bar": 6, "date": Sat Jan 02 2016 00:00:00 GMT+00:00
      }
    ]
  }
]

1 个答案:

答案 0 :(得分:1)

这应该有效:

r.expr([
  {id: 1, foo: 1, bar: 2, date: r.time(2016, 1, 1, 'Z')},
  {id: 1, foo: 4, bar: 1, date: r.time(2016, 1, 3, 'Z')},
  {id: 1, foo: 10, bar: 0, date: r.time(2016, 1, 2, 'Z')},

  {id: 2, foo: 5, bar: 3, date: r.time(2016, 1, 1, 'Z')},
  {id: 2, foo: 3, bar: 6, date: r.time(2016, 1, 2, 'Z')}
]).group('id')
  .orderBy('date')
  .without('id')
  .ungroup()
  .map(rec => { return { id : rec('group'), stats : rec('reduction') }; } )