如何使用RethinkDb在一个时间跨度内找到每天字段的最小值?

时间:2018-03-10 19:38:43

标签: rethinkdb

我有一个天气传感器读数数据库。测量的项目之一是天空温度'。我想在一两个月内找到每天的最低天气温度。

我尝试的第一件事是:

r.db('Weather').table('TAO_SkyNet', {readMode:'outdated'})
  .group(r.row('time').dayOfYear(),{index:'time'})
  .min('sky')

我认为这可能有用,除了它是一个大型数据库并且查询在300秒后超时。很公平,我真的不希望数据回到开始时间。几周就可以了。所以我试图限制这样检查的记录:

r.db('Weather').table('TAO_SkyNet', {readMode:'outdated'})
  .between(r.time(2018,3,1,'Z'), r.now())
  .group(r.row('time').dayOfYear(),{index:'time'})
  .min('sky')

..我得到......

e: Expected type TABLE but found TABLE_SLICE:
SELECTION ON table(TAO_SkyNet) in:
r.db("Weather").table("TAO_SkyNet", {"readMode": "outdated"}).between(r.time(2018, 3, 1, "Z"), r.now()).group(r.row("time").dayOfYear(), {"index": "time"}).min("sky")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 

所以,我被困在这里。如何对表的子集进行分组?

1 个答案:

答案 0 :(得分:1)

between返回一个表切片,表切片不支持索引。

  

table.between(lowerKey,upperKey [,options])→table_slice

顺便说一下,between对索引本身进行操作。 从{index:'time'}子句中移除group后(如果TAO_SkyNet time为主键):

r.db('Weather')
    .table('TAO_SkyNet', {readMode: 'outdated'})
    .between(r.time(2018, 3, 1, 'Z'), r.now())
    .group(r.row('time').dayOfYear())
    .min('sky')

或将index选项移至between子句(如果TAO_SkyNettime作为其辅助键)

r.db('Weather')
    .table('TAO_SkyNet', {readMode: 'outdated'})
    .between(r.time(2018, 3, 1, 'Z'), r.now(), {index: 'time'})
    .group(r.row('time').dayOfYear())
    .min('sky')

它应该可以正常工作。 测试数据集:

r.db('Weather').table('TAO_SkyNet').insert([
    // day 1
    {time: r.time(2018, 3, 1,  0, 0, 0, 'Z'), sky: 10},
    {time: r.time(2018, 3, 1,  8, 0, 0, 'Z'), sky: 4}, // min
    {time: r.time(2018, 3, 1, 16, 0, 0, 'Z'), sky: 7},
    // day 2
    {time: r.time(2018, 3, 2,  0, 0, 0, 'Z'), sky: 2}, // min
    {time: r.time(2018, 3, 2,  8, 0, 0, 'Z'), sky: 4},
    {time: r.time(2018, 3, 2, 16, 0, 0, 'Z'), sky: 9},
    // day 3
    {time: r.time(2018, 3, 3,  0, 0, 0, 'Z'), sky: 7},
    {time: r.time(2018, 3, 3,  8, 0, 0, 'Z'), sky: 7},
    {time: r.time(2018, 3, 3, 16, 0, 0, 'Z'), sky: 1} // min
]);

查询结果:

[{
    "group": 60,
    "reduction": {"sky": 4, "time": Thu Mar 01 2018 08:00:00 GMT+00:00}
},
{
    "group": 61,
    "reduction": {"sky": 2, "time": Fri Mar 02 2018 00:00:00 GMT+00:00}
},
{
    "group": 62,
    "reduction": {"sky": 1, "time": Sat Mar 03 2018 16:00:00 GMT+00:00}
}]