rethinkDB:​​按部分值分组

rethinkDB: group by partial value

我正在评估 phone 调用日志,我已将其导入 rethinkDB;文件看起来像这样:

{
    'date': '2015-01-02',
    'duration': 46,
    'cost': 0.25
    'type': 'outgoing'
}

我正在尝试检索一个月内所有通话期间的总和


我可以 "manually" 通过这个查询实现它:

r.table('CallLog').filter(r.row('date').match('2015-01-*')).sum('duration')

而且考虑到我只需要6个月的时间,在合理的时间内是完全可以做到的。但是,我宁愿想出一种在一个查询中完成它的方法。
我知道我可以对文档进行分组;例如按我可以做的呼叫类型总结所有呼叫的费用

r.table('CallLog').group('type').sum('cost')

我不知道的是 我如何按部分字段分组,在本例中是 date 字段的前 7 个字符。

有任何想法吗?感谢您的帮助。

您可以通过将匿名函数传递给 group 方法来按部分字段分组。任何时候你想从 group 函数中获得一些特殊的行为,想想匿名函数(lambda 函数)。

在这种情况下,您可以使用 match 方法传递一个正则表达式,该正则表达式将匹配一个包含 4 位短划线和 2 位数字的字符串 (\d{4}-\d{2})。

查询如下所示:

r.table('29969411')
  .group(function (row) {
    return row('date').match("\d{4}-\d{2}")
  }).sum('cost')

在 table 中输入以下条目:

{
    "cost": 0.25 ,
    "date":  "2015-02-02" ,
    "duration": 46 ,
    "id":  "1ff56fdd-9152-4729-baa4-c9736adbe54f" ,
    "type":  "outgoing"
}, {
    "cost": 0.25 ,
    "date":  "2015-03-02" ,
    "duration": 46 ,
    "id":  "74a453ec-531c-4fb0-a463-661b122d47df" ,
    "type":  "outgoing"
}, {
    "cost": 0.25 ,
    "date":  "2015-01-02" ,
    "duration": 46 ,
    "id":  "bfa9aa42-51c0-43ef-af3d-24de15ed6571" ,
    "type":  "outgoing"
}, {
    "cost": 0.25 ,
    "date":  "2015-01-99" ,
    "duration": 46 ,
    "id":  "c93ac248-f214-4649-a355-bfc814169456" ,
    "type":  "outgoing"
}

结果如下:

[
  {
    "group": {
    "end": 7 ,
    "groups": [ ],
    "start": 0 ,
    "str":  "2015-01"
  } ,
   "reduction": 0.5
  } ,
  {
    "group": {
    "end": 7 ,
    "groups": [ ],
    "start": 0 ,
    "str":  "2015-02"
  } ,
   "reduction": 0.25
  } ,
  {
    "group": {
    "end": 7 ,
    "groups": [ ],
    "start": 0 ,
    "str":  "2015-03"
  } ,
    "reduction": 0.25
  }
]

豪尔赫,谢谢你的回答;与此同时,我也找到了(在一些帮助下)另一个:

r.table('CallLog').group(r.row('date').match('.{7}')('str')).sum('cost')

结果如下:

[
    {
        "group":"2014-09",
        "reduction":214.8195
    },
    {
        "group":"2014-10",
        "reduction":20087.655200000074
    }
]