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

Time:05-02

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

CodePudding user response:

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

CodePudding user response:

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

  • Related