Need help with ScriptedMetricAggregation in Elasticsearch v8.7

Hello,

I am working on migrating ES 6.8 java code to ES 8.7.1 rest API java. But, I am unable to understand or find how to write script metric aggregation with ES 8.7.1. Could you please guide me using the below code from ES 6.8.

if (comp != null) 
{
	termAggregation = AggregationBuilders.terms("comp").field("eid").size(10000);
	scriptedMetricAggregationBuilder = AggregationBuilders.scriptedMetric("unique_es_count");
	scriptedMetricAggregationBuilder.initScript(new Script("state.map = [:]"));
	scriptedMetricAggregationBuilder.mapScript(new Script("if(doc['eid'] != null){" + "if (!state.map.containsKey(doc['eid'].value)){ state.map[doc['eid'].value]=1;}}"));
	scriptedMetricAggregationBuilder.combineScript(new Script("return state.map;"));
	scriptedMetricAggregationBuilder.reduceScript(new Script("int count=0; def final = [:]; for (map in states){ for (entry in map.entrySet()) { if (!final.containsKey(entry.getKey())){ final[entry.getKey()] = 1; count +=1;}}} return count;"));
	
	termAggregation1 = AggregationBuilders.topHits("distinct")
			.size(1)
			.fetchSource(includeFields, excludeFields);
	termAggregation.subAggregation(termAggregation1);
	termAggregation.subAggregation(AggregationBuilders.sum("totexp").field("expense"));
	termAggregation.subAggregation(new BucketSortPipelineAggregationBuilder("expsort", null).from(from-1).size(size));
	searchSourceBuilder.aggregation(scriptedMetricAggregationBuilder);
}

Thanks in advance
Chetan

Hi @Chetan_Ramaiah

See this example, maybe need some fixes.

var scriptedMetricAggregationBuilder = AggregationBuilders
    .scriptedMetric(sm -> sm
        .initScript(Script.of(s -> s.inline(InlineScript.of(is -> is.source("state.map = [:]")))))
        .mapScript(Script.of(s -> s.inline(InlineScript.of(is -> is
            .source("if(doc['eid'] != null){\" + \"if (!state.map.containsKey(doc['eid'].value)){ state.map[doc['eid'].value]=1;}}")))))
        .combineScript(Script.of(s -> s.inline(InlineScript.of(is -> is.source("return state.map;")))))
        .reduceScript(Script.of(s -> s.inline(InlineScript.of(is -> is.source(
            "int count=0; def final = [:]; for (map in states){ for (entry in map.entrySet()) { if (!final.containsKey(entry.getKey())){ final[entry.getKey()] = 1; count +=1;}}} return count;")))))
    );

map.put("unique_es_count", scriptedMetricAggregationBuilder);

SearchRequest searchRequest = new SearchRequest.Builder()
    .aggregations(map)
    .build();

Will try this approach and keep you posted. Thanks @RabBit_BR

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