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.
答案 0 :(得分:0)
我首先在version_number
上聚合,然后使用按降序indexDate
排序的top_hits
子聚合,并返回该存储桶的第一个文档的ID。
{
"size": 0,
"aggs": {
"by_version": {
"terms": {
"field": "version_number"
},
"aggs": {
"max_date": {
"top_hits": {
"size": 1,
"sort": {
"indexDate": "desc"
},
"_source": [
"id"
]
}
}
}
}
}
}