【问题标题】:elasticsearch query aggs sorted max dateelasticsearch查询聚合排序最大日期
【发布时间】:2014-08-04 12:46:24
【问题描述】:

我有这样的数据:

Id    GroupId     UpdateDate
1    1                2013-11-15T12:00:00
2    1                2013-11-20T12:00:00
3    2                2013-12-01T12:00:00
4    2                2013-13-01T12:00:00
5    2                2013-11-01T12:00:00
6    3                2013-10-01T12:00:00

如何编写查询以将过滤/分组的列表返回到最大 UpdateDate foreach 组?最终列表按 UpdateDate 降序排序。

我期望这个输出:

Id    GroupId     UpdateDate
4    2                2013-13-01T12:00:00
2    1                2013-11-20T12:00:00
6    3                2013-10-01T12:00:00

谢谢你:)

【问题讨论】:

  • 弹性搜索可以吗?

标签: filter elasticsearch grouping aggregation


【解决方案1】:

是的,这可以通过 elasticsearch 实现,但数据将采用 JSON 格式,需要按照您上面显示的格式进行展平。这是我使用 Marvel Sense 的方法

批量加载数据:

POST myindex/mytype/_bulk
{"index":{}}
{"id":1,"GroupId":1,"UpdateDate":"2013-11-15T12:00:00"}
{"index":{}}
{"id":2,"GroupId":1,"UpdateDate":"2013-11-20T12:00:00"}
{"index":{}}
{"id":3,"GroupId":2,"UpdateDate":"2013-12-01T12:00:00"}
{"index":{}}
{"id":4,"GroupId":2,"UpdateDate":"2013-12-01T12:00:00"}
{"index":{}}
{"id":5,"GroupId":2,"UpdateDate":"2013-11-01T12:00:00"}
{"index":{}}
{"id":6,"GroupId":3,"UpdateDate":"2013-10-01T12:00:00"}

按组获取最大值:

GET myindex/mytype/_search?search_type=count
{
  "aggs": {
    "NAME": {
      "terms": {
        "field": "GroupId"
      },
      "aggs": {
        "NAME": {
          "max": {
            "field": "UpdateDate"
          }
        }
     }
    }
  }
}

输出:

{
...
   "aggregations": {
      "NAME": {
         "buckets": [
            {
               "key": 2,
               "doc_count": 3,
               "NAME": {
                 "value": 1385899200000
              }
           },
            {
               "key": 1,
               "doc_count": 2,
               "NAME": {
                  "value": 1384948800000
               }
            },
            {
               "key": 3,
               "doc_count": 1,
               "NAME": {
                  "value": 1380628800000
               }
            }
         ]
      }
   }
...
}

最大日期作为 Linux 时间返回,需要转换回可读的日期格式。

【讨论】:

  • 如果您想按聚合值排序,请添加到术语中:"terms": {"field": "GroupId", "order": {"NAME": "desc"}}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-16
  • 1970-01-01
  • 2017-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多