Java API client 7.16.3 : handling for loops in terms aggregations

Hello.

I struggle to do aggregations on multiple terms using the new Java API, whenever using loops.

I have a map of terms I need to aggregate on with their renamed value that I need to loop on.

I have tried the following code, but I can't return the builder instead of the aggregations.

co.elastic.clients.elasticsearch.core.SearchRequest.Builder searchBuilder = co.elastic.clients.elasticsearch.core.SearchRequest.of(b1 -> b1
            .aggregations("agg", (b2, c2) -> {
                    for (Map.Entry<String, String> fieldEntry : fieldNames.entrySet()) {
                        String esField = fieldEntry.getKey();
                        String renamedValue : fieldNames.get(esField);
                        b2.terms(b3 ->
                            b3.field(esField)
                                .missingBucket(true)
                                .name(renamedValue)
                        );
                    }
                    return b2;
                }
            )
            .size(0)
        );

How should I change the code to solve this issue ?

I am using the version 7.16.3 of the new Java API.

Thanks

I actually found out my issue : I used a terms aggregation instead of a composite aggregation, which is what I intended to run at the beginning.
Here is the updated code.

searchBuilder.aggregations("agg", b2 ->
                b2.composite( c ->
                {
                    CompositeAggregationSource.Builder builderComposite = new CompositeAggregationSource.Builder();
                    Map<String, CompositeAggregationSource> sourceMap= new HashMap<>();
                    for (Map.Entry<String, List<String>> fieldEntry : fieldNames.entrySet()) {
                        String esField = fieldEntry.getKey();
                        String renamedValue = fieldNames.getValue();
                        builderComposite.terms(t -> t
                                .field(esField)
                                .missingBucket(true)
                        );
                        sourceMap.put(renamedValue, builderComposite.build());
                    }
                    c.sources(sourceMap);
                    c.size(10000);
                    return c;
                })
            )
            .size(0);

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