Search code examples
elasticsearchelasticsearch-jest

Bucket script java api in elasticsearch


I made elasticsearch query that get each oid name and it's count divided by 1000. ( the number(1000) can be changed)

    "aggregations" : {
        "agg_oid" : {
          "terms" : {
            "field" : "oid",
            "order" : {
              "_count" : "desc"
            }
          },
          "aggregations" : {
              "agg_values" : {
                  "bucket_script": {
                        "buckets_path": {
                          "count": "_count"
                        },
                        "script": "count / 1000"
                    }
              }
          }
        }
      }

It works well, and tried to make it with java api (currently using jest).

AggregationBuilders
    .terms( "agg_oid")
    .field( "oid")
    .subAggregation(
        AggregationBuilders
             // bucket script and path for count
    );

How to implement of 'bucket_script' in java? If not, is there any way to query aggregation's count with caculating in java api?


Solution

  • Something like this should do:

    Map<String, String> bucketsPathsMap = new HashMap<>();
    bucketsPathsMap.put("count", "_count");
    Script script = new Script("count / 1000");
    
    BucketScriptPipelineAggregationBuilder bs = PipelineAggregatorBuilders
        .bucketScript("agg_values", bucketsPathsMap, script);
    
    TermsAggregationBuilder oid = AggregationBuilders.terms("agg_oid")
        .field("oid")
        .order(InternalOrder.COUNT_DESC).
        subAggregation(bs);