Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch Pagination - Last Page Returning Too Many Results

My Elasticsearch query is returning 111 results, which means that if I'm paging through them (with 10 results per page) I should have 12 pages: 11 full pages and 1 page with a single result.

However, my last page is still returning 10 results. It's returning the very last result as expected, but also 9 results from the previous page. How do I disable this behavior and have it just return the single result as expected?

I'm using the Java API, with the following code:

SearchResponse response = client.prepareSearch("my_index")
   .setTypes("my_output")
   .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
   .setQuery(QueryBuilders.queryStringQuery(query))
   .setFrom(page).setSize(size)
   .execute()
   .actionGet();
like image 866
James Baker Avatar asked Feb 08 '23 23:02

James Baker


1 Answers

The from parameter in the ES query is not a page number but an offset. So if you want the 11th page, from must be 110 (assuming size is 10) and not 11.

So you can keep passing a page number using @PathParam, but the value you pass to setFrom() must be page * size and not just page.

So for page = 0, you'll call setFrom(0), for page = 1 you'll call setFrom(10), etc and for page = 11 (i.e. the 12th page), you'll call setFrom(110).

like image 79
Val Avatar answered Feb 11 '23 16:02

Val