Tom
Tom

Reputation: 21

ElasticSearch get documents with max value after group by

We want to create a search query for ElastichSearch to

Question

When launching the query below I get buckets for each attestationIdentification, with the max value of attestationIdentification in theMax.

However, is it possible to get the documents immediately? Like with some kind of top_hits? Or do I really have to launch another search using these results?

Also, is it possible to do this using NEST.ElasticSearch?

Simple example data:

{
 "attestationIdentification" : 1,
 "attestationSituationNbr" : 20
},

{
 "attestationIdentification" : 1,
 "attestationSituationNbr" : 21
},

{
 "attestationIdentification" : 2,
 "attestationSituationNbr" : 30
}

My Query

{
  "aggs": {
    "yourGroup": {
      "terms": {
        "field": "attestationIdentification",
        "size": 10
      },
      "aggs": {
        "theMax": {
          "max": {
            "field": "attestationSituationNbr"
          }
        }
      }
    }
  }
}

Result

The result is the max value for each group, however, I would like to get the documents with this max value:

...
"aggregations": {
   "yourGroup": {
     "doc_count_error_upper_bound": 0,
     "sum_other_doc_count": 0,
     "buckets": [
       {
         "key": 1,
         "doc_count": 4,
         "theMax": { "value": 21 }
       },
       {
         "key": 2,
         "doc_count": 2,
         "theMax": { "value": 30 }
       }
    ...

Upvotes: 2

Views: 3414

Answers (1)

Richa
Richa

Reputation: 7649

Use top_hits like:

{
  "size": 0, 
  "aggs": {
    "yourGroup": {
      "terms": {
        "field": "attestationIdentification",
        "size": 10
      },
      "aggs": {
        "theMax": {
          "top_hits": {
            "size": "1",
            "sort": {
              "attestationSituationNbr": {
                "order": "desc"
              }
            }
          }
        }
      }
    }
  }
}

Upvotes: 2

Related Questions