'Getting document associated to maximum field value in ElasticSearch
I'm working with documents having three fields: deviceId (integer), timestamp (date) and channel (string). My final goal is to find, for each deviceId, the most recent document, and then aggregating these documents by channel.
Right now, I've successfully grabbed the latest timestamps by deviceId, but I'm struggling to capturing the channel field associated with the maximum timestamp of each deviceId. I'm thinking that I'm probably not solving this problem the right way. Is there any other way, or am I close to the solution?
The incomplete request:
GET /test/_search
{
"size": 0,
"aggs": {
"deviceId": {
"terms": {
"field": "deviceId"
},
"aggs": {
"time": {
"max": {
"field": "timestamp"
}
}
}
}
}
}
The example I'm working with:
PUT /test
{
"mappings":{
"properties": {
"deviceId" : { "type" : "integer" },
"timestamp": {"type" : "date"},
"channel": {"type": "text"}
}
}
}
POST test/_doc/1
{
"deviceId" : 456,
"timestamp" : "2022-03-24T11:00:00.000Z",
"channel" : "A"
}
POST test/_doc/2
{
"deviceId" : 456,
"timestamp" : "2022-03-24T12:00:00.000Z",
"channel" : "B"
}
POST test/_doc/3
{
"deviceId" : 123,
"timestamp" : "2022-03-24T11:00:00.000Z",
"channel" : "C"
}
POST test/_doc/4
{
"deviceId" : 123,
"timestamp" : "2022-03-24T12:00:00.000Z",
"channel" : "D"
}
POST test/_doc/5
{
"deviceId" : 123,
"timestamp" : "2022-03-24T13:00:00.000Z",
"channel" : "E"
}
Thanks in advance!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
