How to Paginate Results in Elasticsearch: Syntax and Examples
To paginate results in Elasticsearch, use the
from parameter to skip a number of results and the size parameter to limit how many results are returned. For example, from: 10 and size: 5 returns results 11 to 15. This helps you fetch results page by page.Syntax
Pagination in Elasticsearch is controlled by two parameters in the search request:
from: The number of results to skip before starting to return results.size: The number of results to return in the current page.
These parameters are used inside the JSON body of a search query or as URL parameters in a GET request.
json
{
"from": 10,
"size": 5,
"query": {
"match_all": {}
}
}Example
This example shows how to get the second page of results when each page has 5 items. It skips the first 5 results (from: 5) and returns the next 5 (size: 5).
json
{
"from": 5,
"size": 5,
"query": {
"match": {
"title": "database"
}
}
}Output
{
"hits": {
"total": {
"value": 23,
"relation": "eq"
},
"hits": [
{"_id": "6", "_source": {"title": "Database Basics"}},
{"_id": "7", "_source": {"title": "Advanced Database"}},
{"_id": "8", "_source": {"title": "Database Optimization"}},
{"_id": "9", "_source": {"title": "NoSQL Database"}},
{"_id": "10", "_source": {"title": "Database Security"}}
]
}
}
Common Pitfalls
Common mistakes when paginating in Elasticsearch include:
- Using very large
fromvalues, which can slow down queries because Elasticsearch still has to scan all skipped results. - Not setting a
size, which defaults to 10 and may not match your page size. - Ignoring the
search_aftermethod for deep pagination, which is more efficient for large offsets.
For deep pagination, consider using search_after with a sort key instead of large from values.
json
{
"from": 10000,
"size": 10,
"query": { "match_all": {} }
}
{
"size": 10,
"query": { "match_all": {} },
"search_after": ["last_sort_value"],
"sort": [ {"date": "asc"}, {"_id": "asc"} ]
}Quick Reference
| Parameter | Description | Example |
|---|---|---|
| from | Number of results to skip | from: 10 |
| size | Number of results to return | size: 5 |
| search_after | Value to continue after for deep pagination | search_after: ["last_sort_value"] |
| sort | Sort order required for search_after | sort: [{"date": "asc"}, {"_id": "asc"}] |
Key Takeaways
Use
from and size to paginate results by skipping and limiting hits.Avoid large
from values for deep pagination to prevent slow queries.Use
search_after with sorting for efficient deep pagination.Always specify
size to control page size explicitly.Pagination parameters go inside the search query JSON body.