Return the top k hits from each bucket after aggregation?

I'd like the top k hits from each index to be returned, I'm using the following query:

GET /index-*/_search
{
  "query": {
    "multi_match": {
      "query": "word1 word2",
      "type": "phrase",
      "fields": ["field1", "field2]
    }
  },
  "aggs": {
    "byindex": {
      "terms": {
        "field": "_index",
        "size" : 3
      }
    },
    "aggs": {
      "top_hits": {
        "size": 1
      }
    }
  }
} 

similar to this thread, but I'm given the top hit from all buckets rather than from each bucket. What's wrong with my query?

For this, your top_hits agg should be under byindex agg like this:

 "aggs": {
    "byindex": {
      "terms": {
        "field": "_index",
        "size": 3
      },
      "aggs": {
        "my_top_hits": {
          "top_hits": {
            "size": 1
          }
        }
      }
    }
  }

Makes sense for it to be nested inside. Works, thanks!!!

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.