Reputation: 30035
I index events similar to the ones below:
{
"time": "2015-10-01",
"kind": "A"
},
{
"time": "2015-10-02",
"kind": "B"
},
{
"time": "2015-10-15",
"kind": "A"
},
{
"time": "2015-10-16",
"kind": "B"
}
In other words, these are timed events of several kinds (A
and B
in the example above). It is guaranteed that there cannot be two or more events of the same kind
with the same time
.
I am looking for a query which would retrieve the latest (time
closest to "now") events for each kind. For the example above these would be the lat two ones.
Up to now, I was forcing the _id
to have the value of kind
, which automatically kept a set of unique events (the events are indexed with time, so the one with the date of 2015-10-16
is guaranteed to be indexed after the one from an earlier 2015-10-02
). This of course does not keep the history of events, something I am now interested in.
Upvotes: 1
Views: 220
Reputation: 52368
How about this query:
{
"size": 0,
"aggs": {
"unique_kind": {
"terms": {
"field": "kind",
"size": 10
},
"aggs": {
"max_date": {
"max": {
"field": "time"
}
},
"1st": {
"top_hits": {
"size": 1,
"sort": [{"time":"desc"}]
}
}
}
}
}
}
Upvotes: 1