Search code examples
javaelasticsearchlimit

Elasticsearch Java REST Client: see if number of eligible hits exceeded SearchSourceBuilder size


I have an Elasticsearch request:

SearchSourceBuilder source = new SearchSourceBuilder()
    .size(limit)
    .from(offset)
    .query(queryBuilder)
SearchRequest searchRequest = new SearchRequest(indexName)
        .types(type)
        .source(source);
SearchResponse searchResponse = client.search(searchRequest);

I need to optionally return a pagination token based on whether or not the number of results returned was limited by the limit parameter (in other words, are there more results to return). Is there a way to see if the number of eligible search hits that matched the query exceeded limit, other than either doing another query, or by setting the size to limit + 1 and removing the last hit in the response?


Solution

  • Elasticsearch returns the total number of documents matching your query in hits.totalHits property in the response. If it is bigger than offset+limit then you have next page.