ElasticSearch aggregation get hit with min date

How can I get hit with min date after aggregation? I have aggregation by some field, then subAggregation(AggregationBuilders.min("createdDate") with this date and then topHits subAggregation. But it returns me 3 hits, not 1 with this value.

You cannot define topHits as a subaggregation of "min". What you probably did was to specify min and topHits on the same level, which means that those two subaggregations are independent.

Please give a mapping and a query example when asking questions, otherwise it's hard to figure out what exactly you want to achieve.

Here is my template with mappings:

I can't get query, because I use official Java ES Framework. I can provide only code.

SearchResponse articlesAggregationResponse = transportClient.prepareSearch(articlesIndexAndType[0]).setTypes(articlesIndexAndType[1]) .setQuery(queryBuilder) .addAggregation(AggregationBuilders.terms("aggregation").field("userId").size(criteiraSize) .subAggregation(AggregationBuilders.count("articlesCount")) .subAggregation(AggregationBuilders.min("firstArticle").field("createdDate")) .subAggregation(AggregationBuilders.topHits("hit"))).execute().actionGet();

what I explained before:

the topHits sub-aggregation is at the same nesting level as the min sub-aggregation in your code, and is thus computed independently, i.e., for each userId, the minimum createdDate and the top hits are calculated independently from each other. Nesting topHits below min aggregation is not possible.

What you actually want is to sort the topHits by createdDate and only return the first result:

.subAggregation(AggregationBuilders.topHits("hit").sort("createdDate").size(1))
1 Like

Thanks. And how can I retrieve with max date? Sort in DESC order?

yes, use SortOrder.DESC if you want the max.

1 Like

Thanks. How can I plus you reputation here? :slight_smile:

some :heart: is all I need :wink:

1 Like

Ok. Have a nice day and thank you again. I spent too much time to solve this :slight_smile: