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

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



Solution 1:[1]

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();

Solution 2:[2]

Changed my ES version to 7.3.0. With it had to update my rest-high-level-client to 7.3.0 as well.

references: https://discuss.elastic.co/t/issue-with-high-level-rest-client-api/195853

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Aditya K