[[java-aggs-metrics-tophits]] ==== Top Hits Aggregation Here is how you can use {ref}/search-aggregations-metrics-top-hits-aggregation.html[Top Hits Aggregation] with Java API. ===== Prepare aggregation request Here is an example on how to create the aggregation request: [source,java] -------------------------------------------------- AggregationBuilder aggregation = AggregationBuilders .terms("agg").field("gender") .subAggregation( AggregationBuilders.topHits("top") ); -------------------------------------------------- You can use most of the options available for standard search such as `from`, `size`, `sort`, `highlight`, `explain`... [source,java] -------------------------------------------------- AggregationBuilder aggregation = AggregationBuilders .terms("agg").field("gender") .subAggregation( AggregationBuilders.topHits("top") .setExplain(true) .setSize(1) .setFrom(10) ); -------------------------------------------------- ===== Use aggregation response Import Aggregation definition classes: [source,java] -------------------------------------------------- import org.elasticsearch.search.aggregations.bucket.terms.Terms; import org.elasticsearch.search.aggregations.metrics.tophits.TopHits; -------------------------------------------------- [source,java] -------------------------------------------------- // sr is here your SearchResponse object Terms agg = sr.getAggregations().get("agg"); // For each entry for (Terms.Bucket entry : agg.getBuckets()) { String key = entry.getKey(); // bucket key long docCount = entry.getDocCount(); // Doc count logger.info("key [{}], doc_count [{}]", key, docCount); // We ask for top_hits for each bucket TopHits topHits = entry.getAggregations().get("top"); for (SearchHit hit : topHits.getHits().getHits()) { logger.info(" -> id [{}], _source [{}]", hit.getId(), hit.getSourceAsString()); } } -------------------------------------------------- This will basically produce for the first example: [source,text] -------------------------------------------------- key [male], doc_count [5107] -> id [AUnzSZze9k7PKXtq04x2], _source [{"gender":"male",...}] -> id [AUnzSZzj9k7PKXtq04x4], _source [{"gender":"male",...}] -> id [AUnzSZzl9k7PKXtq04x5], _source [{"gender":"male",...}] key [female], doc_count [4893] -> id [AUnzSZzM9k7PKXtq04xy], _source [{"gender":"female",...}] -> id [AUnzSZzp9k7PKXtq04x8], _source [{"gender":"female",...}] -> id [AUnzSZ0W9k7PKXtq04yS], _source [{"gender":"female",...}] --------------------------------------------------