elasticsearch按ID字段分组,并在日期字段上执行最大值 [英] elasticsearch group by ID field and perform max on date field

查看:654
本文介绍了elasticsearch按ID字段分组,并在日期字段上执行最大值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的索引具有如下所述的数据。

My index has data as mentioned below.

Id    version_number groupId   indexDate
1    v1                 1    2016-11-15T12:00:00
2    v1                 2    2016-11-20T12:00:00
3    v2                 2    2016-12-01T12:00:00
4    v1                 3    2016-13-01T12:00:00
5    v1                 4    2016-11-01T12:00:00
6    v2                 4    2016-13-01T12:00:00
7    v1                 5    2016-14-01T12:00:00

如何用Java编写Elasticsearch查询。如果我按日期2016-13-01T12:00:00进行搜索,我希望每个groupId都能看到indexDate小于或等于搜索日期的最新版本?

How can i write a elasticsearch query in java. If i search by date 2016-13-01T12:00:00 i expect to see the latest version per groupId which has indexDate less than or equal to the date searched?

预期输出:

Id    version_number   groupId   indexDate
1    v1                  1       2016-13-01T12:00:00
2    v2                  2       2016-11-20T12:00:00
6    v3                  3       2016-10-01T12:00:00
7    v2                  4       2016-10-01T12:00:00 

我没有在Elasticsearch的日期字段中看到最大函数来实现这一点。

I dont see a max function on date field in elasticsearch to achieve this.

推荐答案

我将首先在 version_number 上进行汇总,然后使用 top_hits 子聚合按降序 indexDate 排序并返回该存储桶的第一个文档的ID。

I would first aggregate on version_numberand then use a top_hits sub-aggregation sorted on descending indexDate and returning the id of the first document of that bucket.

{
  "size": 0,
  "aggs": {
    "by_version": {
      "terms": {
        "field": "version_number"
      },
      "aggs": {
        "max_date": {
          "top_hits": {
            "size": 1,
            "sort": {
              "indexDate": "desc"
            },
            "_source": [
              "id"
            ]
          }
        }
      }
    }
  }
}

这篇关于elasticsearch按ID字段分组,并在日期字段上执行最大值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆