将大型数据集转换为缩减对象

Transforming large dataset into reduced object

我有一个快速增长的 rethink 数据库,我需要创建一些聚合查询来减轻客户端的负载。这是一个示例文档列表:

[
    {
        created_ts: 1424389239198,
        cost: 2,
        id: '12345678'
    },
    {
        created_ts: 1424389239198,
        cost: 2,
        id: '12345678'
    },
    {
        created_ts: 1424389239198,
        cost: 2,
        id: '12345678'
    }
]

我最终想要的是基于数据创建时间的成本聚合(created_ts 存储为纪元时间)。要从 created_ts 获取小时,我可以这样做:

r.epochTime(row('created_ts')).hours()

我需要数据,按一天中的小时数分组,看起来与此类似:

[
    {
        hour: 0,
        total_cost: 6
    },
    {
        hour: 1,
        total_cost: 10
    },
    {
        hour: 2,
        total_cost: 24
    }
]

该数据显示在“0”点(午夜)我的总成本为 6,在凌晨 1 点总成本为 10,等等。我只是得到它以便按小时分组但我不能'似乎无法像上面那样将其放入 "pretty" 对象中。任何帮助深表感谢。非常感谢 JavaScript 中的示例。谢谢!

您可以在 table 上使用 group,在成本上使用 sum,然后在结果上使用 map 以获得您想要的结构:

r.table('foo')
 .group(r.epochTime(r.row('created_ts').div(1000)).hours())
 .sum('cost')
 .ungroup()
 .map({hour: r.row('group'), total_cost: r.row('reduction')})

您可以像这样以分组数据的形式得到答案:

r.table('test').group(function(row) {
  return r.epochTime(row('created_ts')).hours();
}).sum('cost')

如果您想要您指定的确切格式,您可以这样做:

r.table('test').group(function(row) {
  return r.epochTime(row('created_ts')).hours();
}).sum('cost').ungroup().map(function(gr) {
  return {hour: gr('group'), cost: gr('reduction')}
})