Rohit
Rohit

Reputation: 97

How to get bucket count with condition in elasticsearch?

I want to count all the unique sellers whose sell sum should be greater than 100.

I have tried this approach using terms aggregation but this will return a bucket list. But what I want is only the total seller count whose sell sum should be greater than 100.

Is there any way to do this using cardinality or anything else?

I have also tried with cardinality but not worked.

Query

{
    "size": 0,
    "aggregations": {
        "seller_count": {
            "terms": {
                "field": "seller_id"
            },
            "aggregations": {
                "total_sell": {
                    "sum": {
                        "field": "sell"
                    }
                },
                "sell_bucket_filter": {
                    "bucket_selector": {
                        "buckets_path": {
                            "totalSell": "total_sell"
                        },
                        "script": {
                            "source": "params.totalSell > 100"
                        }
                    }
                }
            }
        }
    }
}

Upvotes: 2

Views: 1807

Answers (1)

Bhavya
Bhavya

Reputation: 16172

You can use stats bucket aggregation, to get the count of those seller_id whose sell sum is greater than 100

Adding a working example with index data, mapping, search query, and search result.

Index Mapping:

{
  "mappings": {
    "properties": {
      "sell": {
        "type": "integer"
      }
    }
  }
}

Index Data:

{
  "seller_id": 1,
  "sell": 50
}
{
  "seller_id": 2,
  "sell": 50
}
{
  "seller_id": 2,
  "sell": 60
}
{
  "seller_id": 3,
  "sell": 60
}
{
  "seller_id": 3,
  "sell": 100
}

Search Query:

{
  "size": 0,
  "aggregations": {
    "seller_count": {
      "terms": {
        "field": "seller_id"
      },
      "aggregations": {
        "total_sell": {
          "sum": {
            "field": "sell"
          }
        },
        "sell_bucket_filter": {
          "bucket_selector": {
            "buckets_path": {
              "totalSell": "total_sell"
            },
            "script": {
              "source": "params.totalSell > 100"
            }
          }
        }
      }
    },
    "bucketcount":{
      "stats_bucket":{
        "buckets_path":"seller_count._count"
      }
    }
  }
}

Search Result:

"aggregations": {
    "seller_count": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": 2,
          "doc_count": 2,
          "total_sell": {
            "value": 110.0
          }
        },
        {
          "key": 3,
          "doc_count": 2,
          "total_sell": {
            "value": 160.0
          }
        }
      ]
    },
    "bucketcount": {
      "count": 2,                 // note this
      "min": 2.0,
      "max": 2.0,
      "avg": 2.0,
      "sum": 4.0
    }
  }

Upvotes: 2

Related Questions