Apply condition on value (count) greater than some value in aggregation

ok I found a solution let me share it here. I add "bucket_selector" in my query to fulfill my requirements here is my updated query.

    {
        "size": 0,
        "aggs": {
            "by_brand": {
                "terms": {
                    "field": "brand_name.keyword",
                    "size": 10000,
                    "order": {
                        "_key": "asc"
                    }
                },
                "aggs": {
                    "product": {
                        "cardinality": {
                            "field": "product_id"
                        }
                    },
                    "brand_bucket_filter": {
                        "bucket_selector": {
                            "buckets_path": {
                                "totalProducts": "product"
                            },
                            "script": "params.totalProducts > 50"
                        }
                    }
                }
            }
        },
        "query": {
            "bool": {
                "filter": {
                    "script": {
                        "script": {
                            "source": "doc['image_src.keyword'].size()!=0",
                            "lang": "painless"
                        }
                    }
                }
            }
        }
    }

it will filter out products which have count less then 50.

Regards

1 Like