Aditya K
Aditya K

Reputation: 175

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

Upvotes: 2

Views: 2559

Answers (3)

Ramkumar Pillai
Ramkumar Pillai

Reputation: 174

with new Version client here is how to get the total count

Long totalCount = searchResponse.getHits().getTotalHits().value;

this error popped up in idea java: long cannot be dereferenced

Upvotes: 0

Aditya K
Aditya K

Reputation: 175

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

Upvotes: 0

Sagar Patel
Sagar Patel

Reputation: 5486

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

Upvotes: 2

Related Questions