Vinay
Vinay

Reputation: 2339

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

I am creating pagination using elasticsearch QueryBuilders. I am using setFrom to get limited results for pagination. but I need total result count to create total page links in pagination as per result. How can i get total count before setFrom is applied to query? or I have to write same query again to get total count without setFrom and size?

this is my query

BoolQueryBuilder query = QueryBuilders.boolQuery();
for (String key : brands) {
    query.must(QueryBuilders.matchQuery("brand", key));
}

// search term
query.must(QueryBuilders.queryStringQuery(pSearchTerm + "*")
        .lenient(true).field("name"));

// price range
query.filter(QueryBuilders.rangeQuery("unit_price").from(min)
        .to(max));

SearchResponse searchresponse = client.prepareSearch("product")
        .setTypes("product").setQuery(query).setFrom(from).setSize(20)
        .setExplain(true).execute().actionGet();

SearchHit[] results = searchresponse.getHits().getHits();

Upvotes: 3

Views: 4416

Answers (4)

Kapil
Kapil

Reputation: 917

You may have to execute one more query to get total hits count. Have a look at: Counting number of documents using Elasticsearch

Upvotes: 1

Nishant
Nishant

Reputation: 7864

The SearchHits object provides global information about all hits.

So you need the following to get total count:

long totalCount = searchResponse.getHits().getTotalHits();

You can look at the documentation for such other needs.

Upvotes: 2

Richa
Richa

Reputation: 7649

No you don't have to write the query again. Just use

searchResponse.getHits().getTotalHits()

Upvotes: 2

Val
Val

Reputation: 217314

The number you're looking for is hits.total which you can get from:

long total = searchresponse.getHits().getTotalHits();

Upvotes: 9

Related Questions