use of org.elasticsearch.search.aggregations.metrics.TopHits in project snow-owl by b2ihealthcare.
the class EsDocumentSearcher method aggregate.
@Override
public <T> Aggregation<T> aggregate(AggregationBuilder<T> aggregation) throws IOException {
final String aggregationName = aggregation.getName();
final EsClient client = admin.client();
final DocumentMapping mapping = admin.mappings().getMapping(aggregation.getFrom());
final EsQueryBuilder esQueryBuilder = new EsQueryBuilder(mapping, admin.settings(), admin.log());
final QueryBuilder esQuery = esQueryBuilder.build(aggregation.getQuery());
final SearchRequest req = new SearchRequest(admin.getTypeIndex(mapping));
final SearchSourceBuilder reqSource = req.source().query(esQuery).size(0).trackScores(false).trackTotalHitsUpTo(Integer.MAX_VALUE);
// field selection
final boolean fetchSource = applySourceFiltering(aggregation.getFields(), mapping, reqSource);
reqSource.aggregation(toEsAggregation(mapping, aggregation, fetchSource));
SearchResponse response = null;
try {
response = client.search(req);
} catch (Exception e) {
admin.log().error("Couldn't execute aggregation", e);
throw new IndexException("Couldn't execute aggregation: " + e.getMessage(), null);
}
ImmutableMap.Builder<Object, Bucket<T>> buckets = ImmutableMap.builder();
Aggregations topLevelAggregations = response.getAggregations();
Nested nested = topLevelAggregations.get(nestedAggName(aggregation));
Terms aggregationResult;
if (nested != null) {
aggregationResult = nested.getAggregations().get(aggregationName);
} else {
aggregationResult = topLevelAggregations.get(aggregationName);
}
for (org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket bucket : aggregationResult.getBuckets()) {
final TopHits topHits;
if (nested != null) {
final ReverseNested reverseNested = bucket.getAggregations().get(reverseNestedAggName(aggregation));
topHits = reverseNested.getAggregations().get(topHitsAggName(aggregation));
} else {
topHits = bucket.getAggregations().get(topHitsAggName(aggregation));
}
Hits<T> hits;
if (topHits != null) {
hits = toHits(aggregation.getSelect(), List.of(aggregation.getFrom()), aggregation.getFields(), fetchSource, aggregation.getBucketHitsLimit(), (int) bucket.getDocCount(), null, topHits.getHits());
} else {
hits = new Hits<>(Collections.emptyList(), null, aggregation.getBucketHitsLimit(), (int) bucket.getDocCount());
}
buckets.put(bucket.getKey(), new Bucket<>(bucket.getKey(), hits));
}
return new Aggregation<>(aggregationName, buckets.build());
}
Aggregations