elasticsearch group by ID field and perform max on date field

风流意气都作罢 提交于 2019-12-23 05:27:53

问题


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

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?

output expected:

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 

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


回答1:


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


来源:https://stackoverflow.com/questions/36781397/elasticsearch-group-by-id-field-and-perform-max-on-date-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!