How to get Total hits for an ES query after setting from and size field

Viewed 430
searchSourceBuilder.query(query).sort(sb).from(fromField).size(sizeField);
searchRequest.indices(elasticsearchUserIndex).source(searchSourceBuilder);
SearchResponse searchResponse = elasticSearchConfig.client().search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] hits = searchResponse.getHits().getHits();
Long totalCount = searchResponse.getHits().getTotalHits();
List<Map<String, Object>> list = new ArrayList<>();
for (SearchHit value: hits) {
    list.add(value.getSourceAsMap());
    }

That is the code I'm using. Once I've set the from and the size parameter I get the hits according to the size set. But to add the total page count in response I need the total hits for that query.

How to get total result count when setFrom is used in elasticsearch QueryBuilders?

Tried to use the solution from that thread but I'm getting total hits as 0 even though I get the hits according to the size. totalCount is returning 0

2 Answers

You need to set track_total_hits to true and you will be able to get total hits for response.

SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery()).from(0).size(10);
searchSourceBuilder.trackTotalHits(true);
searchRequest.source(searchSourceBuilder);
Long totalCount = searchResponse.getHits().getTotalHits();
Related