# Top N documents from top\_hits, rather than top N per bucket

**URL:** <https://discuss.elastic.co/t/top-n-documents-from-top-hits-rather-than-top-n-per-bucket/42624>\
**Category:** Elasticsearch\
**Created:** [February 24, 2016, 5:25pm UTC](https://discuss.elastic.co/t/top-n-documents-from-top-hits-rather-than-top-n-per-bucket/42624 "2016-02-24T17:25:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Matt\_Preston](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/matt_preston/32/1626_2.png) [@Matt\_Preston](https://discuss.elastic.co/u/Matt_Preston)\
**Post date:** [February 24, 2016, 5:25pm UTC](https://discuss.elastic.co/t/top-n-documents-from-top-hits-rather-than-top-n-per-bucket/42624/1 "2016-02-24T17:25:37Z")

</div>

I'm using a top\_hits aggregation for a field collapsing. e.g.

```
"aggregations": {
    "top-groups" : {
      "terms": {
        "field": "group-field",
        "size": 10,
        "order": {
          "max_score": "desc"
        }
      },
      "aggregations": {
        "top_hit": {
          "top_hits": {
            "size": 5
          }
        },
        "max_score": {
          "max": {
            "script": "_score"
          }
        }
      }  
    }
  }

```

The only way to specify the number of results returned is by using the size attributes of the term and top\_hit aggregations. The above example will return up to 10 \* 5 results, depending on what was matched by the query.

Is there any way to specify the absolute maximum number of results? e.g. If I want exactly 50 results in total, the above configuration will not work if any of the groups contain less than 5 results. The only way to ensure that I get at least 50 results is to set the size of the terms aggregation to 50, but then in the worst case the response will contain 50 \* 5 documents, which leads to poor performance.

Thanks,  
Matt

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 5, 2017, 11:13pm UTC](https://discuss.elastic.co/t/top-n-documents-from-top-hits-rather-than-top-n-per-bucket/42624/2 "2017-07-05T23:13:54Z")

</div>


