Search code examples
javaelasticsearchelasticsearch-aggregation

is it possible to use bucket_script in java?


I read the Aggregations official documentation, it says

Elasticsearch provides a full Java API to play with aggregations. See the Aggregations guide.

But I cannot just translate my following queries to Java code sadly.

{
  “size”: 0,
  “aggs”: {
    “mallBucket”: {
      “terms”: {
        “field”: “mallId”,
        “size”: 20,
        “min_doc_count”: 3,
        “shard_size”: 10000
      },
      “aggs”: {
        “totalOrderCount”: {
          “value_count”: {
            “field”: “orderSn”
          }
        },
        “filteredCoupon”: {
          “filter”: {
            “terms”: {
              “tags”: [
                “hello”,
                “cool”
              ]
            }
          },
          “aggs”: {
            “couponCount”: {
              “value_count”: {
                “field”: “orderSn”
              }
            }
          }
        },
        “countRatio”: {
          “bucket_script”: {
            “buckets_path”: {
              “orderCount”: “totalOrderCount”,
              “couponCount”: “filteredCoupon>couponCount”
            },
            “script”: “params.couponCount/params.orderCount”
          }
        },
        “ratio_bucket_sort”: {
          “bucket_sort”: {
            “sort”: [
              {
                “countRatio”: {
                  “order”: “desc”
                }
              }
            ],
            “size”: 20
          }
        }
      }
    }
  }
}

Solution

  • From the official Java Client documentation, you can use the PipelineAggregatorBuilders.bucketScript() method to achieve what you need.