Pagination

This entry is part 33 of 35 in the series Complete Guide to Elasticsearch

In this article, you will learn how to do pagination in Elasticsearch.

In the previous article, I introduced the size parameter, which I will also be using to paginate through search results. While the size parameter specifies how many documents should be returned in the results, the from parameter specifies which document index to start from. It’s important to note that this index starts from zero, exactly like with arrays in a programming language. So to start from the first index, one would specify zero, and one for the second document, etc. The default value for the from parameter is zero.

To demonstrate how to paginate through search results, I will just search for pasta as usual.

GET /ecommerce/product/_search?q=name:pasta&size=5

I have specified the page size as 5. I have not added a from parameter because the default of zero is what I need for the first page of results, but I could just as well have specified it as zero explicitly if I wanted to. This is the first page of search results, so let’s get to the interesting part and see how we can fetch the second page.

GET /ecommerce/product/_search?q=name:pasta&size=5&from=5

Remember that the first query returned the documents with the indexes 0 through 4 due to a size parameter of 5, so to retrieve the next page, I set the from parameter to 5. To retrieve the third page, I can simply set the parameter to 10.

GET /ecommerce/product/_search?q=name:pasta&size=5&from=10

It’s as simple as that! The concept is the same when using the query DSL, which I will show you now. So I’m going to use the same example and write an equivalent query with the query DSL.

GET /ecommerce/product/_search
{
  "query": {
    "match": {
      "name": "pasta"
    }
  },
  "size": 5
}

You saw this query in a previous article, so nothing new here. This query fetches the first page of results, as the first document index defaults to zero. As you might have guessed, I can add a from property of 5 in order to fetch the second page.

GET /ecommerce/product/_search
{
  "query": {
    "match": {
      "name": "pasta"
    }
  },
  "size": 5,
  "from": 5
}

And to fetch the third page of results, I simply increase the from property to 10.

GET /ecommerce/product/_search
{
  "query": {
    "match": {
      "name": "pasta"
    }
  },
  "size": 5,
  "from": 10
}

If you are familiar with relational databases such as MySQL, then you can think of these parameters as being similar to the LIMIT and OFFSET keywords.

That’s all there is to it. Now you should know how to paginate through search results, which can be used for making search results pages for a web application, for example.

Series Navigation<< Changing the Size of Result SetsSorting Results >>

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *