# Set top\_hits size dynamically for each bucket based on its doc\_count with a script

**URL:** <https://discuss.elastic.co/t/set-top-hits-size-dynamically-for-each-bucket-based-on-its-doc-count-with-a-script/338728>\
**Category:** Elasticsearch\
**Created:** [July 18, 2023, 11:31pm UTC](https://discuss.elastic.co/t/set-top-hits-size-dynamically-for-each-bucket-based-on-its-doc-count-with-a-script/338728 "2023-07-18T23:31:51Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![DMinovski](https://avatars.discourse-cdn.com/v4/letter/d/5fc32e/32.png) [@DMinovski](https://discuss.elastic.co/u/DMinovski)\
**Post date:** [July 18, 2023, 11:31pm UTC](https://discuss.elastic.co/t/set-top-hits-size-dynamically-for-each-bucket-based-on-its-doc-count-with-a-script/338728/1 "2023-07-18T23:31:51Z")

</div>

I use a query to find the duplicates in an index based on a field. Some documents have the same value in this field and they are duplicates.

```auto
{
    "size": 0,
    "aggs": {
        "duplicate_terms": {
            "terms": {
                "field": "id.keyword",
                "min_doc_count": 2,
                "size": 50
            },
            "aggs": {
                "duplicate_documents": {
                    "top_hits": {
                        "size": 100
                    }
                }
            }
        }
    }
}

```

The ids can have different numbers of duplicates, for example, one can have 48, and another 7. Now it returns all the documents for a specific id, up to 100. Is there a way to set the size dynamically based on doc\_count for every bucket, so that it returns 47 documents for one id, and 6 for another?  
If it could return the duplicates except one

`doc_count - 1`

---

<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:** [August 15, 2023, 11:32pm UTC](https://discuss.elastic.co/t/set-top-hits-size-dynamically-for-each-bucket-based-on-its-doc-count-with-a-script/338728/2 "2023-08-15T23:32:06Z")

</div>

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