3

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();
Vinay
  • 2,272
  • 4
  • 19
  • 34

4 Answers4

9

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

long total = searchresponse.getHits().getTotalHits();
Val
  • 207,596
  • 13
  • 358
  • 360
2

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

searchResponse.getHits().getTotalHits()

Richa
  • 7,419
  • 6
  • 25
  • 34
2

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.

Nishant
  • 7,504
  • 1
  • 21
  • 34
1

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

Kapil
  • 817
  • 2
  • 13
  • 25
  • 1
    No, another query is not required. Check the answers below. – Richa Dec 24 '18 at 05:36
  • Check what OP is asking **How can i get total count before setFrom is applied to query?** – Kapil Dec 24 '18 at 05:37
  • I think there's no reason to build a pagination before the first results come back. At that time you know how many results you're getting using `getTotalHits()` and can build the pagination based on that for the next queries. In the first query, theOP must use `setFrom(0)` to get the first 20 results back. – Val Dec 24 '18 at 05:42
  • Since OP wants to create links to navigate across pages you can not say user to click on 1st link before clicking others. – Kapil Dec 24 '18 at 05:46
  • No but since the query contains `pSearchTerm` I assume that the user first has to input something to trigger the search, right? even if the input is empty in which case he will want to match all names. – Val Dec 24 '18 at 05:55