# How to filter the buckets that have more than N documents using ElasticSearch DSL in python?

**URL:** <https://discuss.elastic.co/t/how-to-filter-the-buckets-that-have-more-than-n-documents-using-elasticsearch-dsl-in-python/327412>\
**Category:** Elasticsearch\
**Tags:** language-clients\
**Created:** [March 10, 2023, 4:41am UTC](https://discuss.elastic.co/t/how-to-filter-the-buckets-that-have-more-than-n-documents-using-elasticsearch-dsl-in-python/327412 "2023-03-10T04:41:09Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Ashar\_Ahmad](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/ashar_ahmad/32/118288_2.png) [@Ashar\_Ahmad](https://discuss.elastic.co/u/Ashar_Ahmad)\
**Post date:** [March 10, 2023, 4:41am UTC](https://discuss.elastic.co/t/how-to-filter-the-buckets-that-have-more-than-n-documents-using-elasticsearch-dsl-in-python/327412/1 "2023-03-10T04:41:09Z")

</div>

I have an index in Elasticsearch that contains information of a user in each document, along with the facebook posts they have made (in a denormalized manner).

Each document contains: User\_ID | User\_Name | Post\_Text | Post\_Emojis

I want to retrieve the IDs of the users who have more than N posts.

I am new to using Elasticsearch, especially to Search DSL using python ([Search DSL — Elasticsearch DSL 7.2.0 documentation](https://elasticsearch-dsl.readthedocs.io/en/latest/search_dsl.html))

I am creating buckets using the terms aggregation on the User\_ID field, and want to filter the buckets based on the number of documents that fall inside each bucket.

This is the function I managed to create, however, as I'm unaware of the proper syntax, and am still confused with the documentation, I can't manage to execute it and attain the correct response.

```auto
def users_more_posts_than_query(search_object: Search, num_posts: int):
    search_object = search_object.aggs.bucket('posts_count', 'terms', field='user_id')\
        .pipeline("having_posts", "bucket_selector", buckets_path={"postsCount": "_count"}, script=f"params.postsCount > {num_posts}")

    response = search_object.execute()

    for hit in response.hits:
            hit.user_id

```

Please point out what I am doing wrong here, and how I can achieve my desired goal.

---

<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:** [April 7, 2023, 4:42am UTC](https://discuss.elastic.co/t/how-to-filter-the-buckets-that-have-more-than-n-documents-using-elasticsearch-dsl-in-python/327412/2 "2023-04-07T04:42:02Z")

</div>

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