【问题标题】:rethinkDB: group by partial valuerethinkDB:​​按部分值分组
【发布时间】:2015-05-01 04:19:01
【问题描述】:

我正在评估已导入 rethinkDB 的电话记录;文件如下所示:

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

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


我可以用这个查询“手动”实现它:

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

鉴于我只需要 6 个月,绝对有可能在合理的时间内完成。但是,我宁愿想办法在一个查询中做到这一点。
我知道我可以对文档进行分组;例如按呼叫类型总结所有呼叫的费用,我可以做

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

我不知道的是我如何按部分字段分组,在这种情况下是 date 字段的前 7 个字符。

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

【问题讨论】:

    标签: rethinkdb


    【解决方案1】:

    您可以通过将匿名函数传递给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')
    

    在表格中给出以下条目:

    {
        "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
      }
    ]
    

    【讨论】:

      【解决方案2】:

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

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

      给出以下结果:

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

      【讨论】:

      • 是的!这基本上是相同的想法。我的正则表达式更具体一些。这可能是也可能不是你想要的。
      • 如果您或我提供的答案回答了您的问题,请务必标记为“已解决”,以便稍后访问此问题的人清楚!
      • 你说得对,我过滤的方式非常适合我的特定数据,我现在可以确定“日期”字段的布局为 yyyy-mm-dd;您的正则表达式解决方案更“通用”
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多