Using metric aggregation in java

Hello,

I'm currently using scripted metric aggregation with groovy scripts but I would like to profile my code, that's why I would like to rewrite it but in java.

What is the correct way to do metric aggregation with custom java code instead of scripts?

Thanks

I'm trying to create a plugin to add my custom aggregation.
I copied ScriptedMetricAggregator and change
this.mapScript = scriptService.search(context.searchContext().lookup(), scriptLang, mapScript, mapScriptType, this.params);

by

this.mapScript = new MapScript(context.searchContext().lookup(), this.params);

public class MapScript implements ExecutableScript, SearchScript {

protected final static ESLogger logger = ESLoggerFactory.getLogger(MapScript.class.getName());

private Map<String, Object> params;
private SearchLookup lookup;
	
public MapScript(SearchLookup lookup, Map<String, Object> params) {
	this.lookup = lookup;
	this.params = params;
}

@Override
public void setNextVar(String name, Object value) {
}

@Override
public Object run() {
			
	return null;
}

@Override
public Object unwrap(Object value) {
	return value;
}

@Override
public void setNextReader(AtomicReaderContext reader) {
	if (lookup != null) {
		lookup.setNextReader(reader);
	}
}

@Override
public void setScorer(Scorer scorer) {
}

@Override
public void setNextDocId(int doc) {
	if (lookup != null) {
		lookup.setNextDocId(doc);
	}
}

@Override
public void setNextSource(Map<String, Object> source) {
	if (lookup != null) {
		lookup.source().setNextSource(source);
	}
}

@Override
public float runAsFloat() {
	return ((Number) run()).floatValue();
}

@Override
public long runAsLong() {
	return ((Number) run()).longValue();
}

@Override
public double runAsDouble() {
	return ((Number) run()).doubleValue();
}

}

But I can't access my document values, lookup.source().source() return null

Do I miss something?