TopHits aggregation | How to get strong type from Java API?

I am extracting the hits from a TopHits aggregation using the Java API:

Map<String, Aggregate> aggregations = searchResponse.aggregations();
TopHitsAggregate topHitsAggregate = searchResponse.aggregations().get("topHits").topHits();
List<Hit<JsonData>> hits = topHitsAggregate.hits().hits();

Using the, MyType.class) call gives the search hits converted to the target type (MyType in this case) which is really convenient. What is the recommended way to get the TopHits documents converted to the target type instead of the raw JsonData?


Very good question. @swallez do we support it with the current version of the client?

1 Like

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

Hello Dennis,

Unfortunately, we don't support automatic type conversion for Aggregation the same way as we do for Search, because it's not possible to know what the end result of an Aggregation will be, since it depends on the type of Aggregation used and how they are chained/nested.

However, we do provide an easy way to convert from JsonData to compatible java classes:

public static class MyType{}

public void typedAggregate() {
    TopHitsAggregate agg = null;

    for (Hit<JsonData> hit: agg.hits().hits()) {
        MyType data = hit.source().to(MyType.class);
        // Do something with data

Sorry for the wait! Hope this can still be helpful.