| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879 | [[java-aggs-metrics-tophits]]==== Top Hits AggregationHere is how you can use{ref}/search-aggregations-metrics-top-hits-aggregation.html[Top Hits Aggregation]with Java API.===== Prepare aggregation requestHere 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")                .explain(true)                .size(1)                .from(10)        );--------------------------------------------------===== Use aggregation responseImport 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 objectTerms agg = sr.getAggregations().get("agg");// For each entryfor (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",...}]--------------------------------------------------
 |