Search performance tuning in Elasticsearch - Time & Space Complexity
When tuning search performance in Elasticsearch, we want to understand how the time it takes to find results changes as the data grows.
We ask: How does search speed change when we add more documents or queries?
Analyze the time complexity of this Elasticsearch search query with filters and sorting.
GET /products/_search
{
"query": {
"bool": {
"filter": [
{ "term": { "category": "books" }},
{ "range": { "price": { "lte": 20 }}}
]
}
},
"sort": [ { "rating": "desc" } ]
}
This query filters products by category and price, then sorts results by rating.
Look for repeated work inside the search process.
- Primary operation: Scanning matching documents to apply filters and sorting.
- How many times: Once per matching document in the filtered set.
As the number of documents grows, the search engine checks more items to find matches and sort them.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and sorts |
| 100 | About 100 checks and sorts |
| 1000 | About 1000 checks and sorts |
Pattern observation: The work grows roughly in direct proportion to the number of matching documents.
Time Complexity: O(n)
This means the search time grows linearly with the number of documents that match the filters.
[X] Wrong: "Adding filters always makes search faster because it reduces data to check."
[OK] Correct: Some filters can be slow if they are not indexed well, causing Elasticsearch to scan many documents anyway.
Understanding how search time grows helps you explain how to keep queries fast as data grows, a key skill in real projects.
"What if we added a full-text search instead of a term filter? How would the time complexity change?"