How to get latest values for each group with an Elasticsearch query?
- taolius
- Jan 22, 2018
- 1 min read
Use "top hits" aggregation(https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-top-hits-aggregation.html)
POST /test/_search?search_type=count { "aggs": { "group": { "terms": { "field": "country" }, "aggs": { "group_docs": { "top_hits": { "size": 1, "sort": [ { "collected": { "order": "desc" } } ] } } } } } }
// java api
https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/_metrics_aggregations.html
AggregationBuilder aggregation = AggregationBuilders .terms("agg").field("gender") .subAggregation( AggregationBuilders.topHits("top") .explain(true) .size(1) .from(10)
.sort(sortBuilder) );
// using the result
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()); } }
Comments