ASN
ASN

Reputation: 1863

How to create pagination based on client.Search results Elasticsearch Nest

Is there any way in which I can retrieve all the results from client.Search (I think this can be done using scroll API) and create a pagination for these results when displaying them? Is there any API from ES for doing so?

Or using From() and size(), can it be done?

For eg: Lets say, I have 100,000 documents on the index and when I search for a keyword it generates some 200 results. How can I use scroll, from and size to show them?

TIA

Upvotes: 0

Views: 1503

Answers (1)

Hosang Jeon
Hosang Jeon

Reputation: 1423

We use from and size options to implement pagination for Elasticsearch results. The code snippet can be something like below:

def query(page)
  size = 10
  page ||= 1
  from = (page-1) * size 

  # elasticsearch query with from * size options
end 

You may need to know total number of results to implement pagination without sending a additional count request. To get the total results, you can use the total field of the response.

=== Updated

If you want to get the search results of the first page, then you can use query(1). If you want to get the search results of the second page, then you can use query(2) and so on.

The purpose of the scroll is slightly different. Let's say you need to get all records of the search results and the number of results are too large (eg., millions of results). If you retrieve all the data at once, it will arise a kind of memory issue or problems because of the high load. In this case, you can use scroll to fetch results step by step.

For the pagination, you don't need to get all data of the search results. You only need to get some data of a specific page. In this case, you may need to use just query with from and size options NOT scroll.

Upvotes: 1

Related Questions