Sub topic 9
Designing search queries: filters, facets, and pagination
This chapter assumes you know the basics of an inverted index, how text fields differ from keyword fields in a mapping, and how a search request reaches a cluster. The examples use Elasticsearch-style syntax. OpenSearch and Solr have equivalent features under different names.
A search request does three jobs at once. It finds documents that match the user's words, narrows them with exact conditions, and returns a manageable page along with summary counts. Each job has its own query feature, and mixing them up causes most of the bugs and performance problems in search APIs.
Scoring versus filtering
Elasticsearch separates two kinds of conditions.
- Query context asks "how well does this document match?" The engine computes a relevance score, for example with BM25.
- Filter context asks "does this document match, yes or no?" There is no score, and the engine can cache the result.
In a bool query, must and should clauses run in query context. filter and must_not clauses run in filter context.
GET /products/_search
{
"query": {
"bool": {
"must": [ { "match": { "name": "running shoes" } } ],
"filter": [
{ "term": { "category": "footwear" } },
{ "range": { "price": { "lte": 100 } } },
{ "term": { "in_stock": true } }
]
}
},
"size": 10
}Put free-text input in must and everything that is a yes/no condition in filter. This gives you two benefits:
- Filters do not distort ranking. A cheap shoe does not rank higher because it satisfied a price range.
- Filters are cheaper. The engine caches the set of matching documents for commonly used filters and reuses it across requests.
Filter on the right field type
The most common filter bug is a term query on a text field. A text field is analyzed, so "Running Shoes" is stored as the terms running and shoes. A term query for "Running Shoes" looks for that exact string among the terms and finds nothing. Use term and range on keyword, numeric, date, and boolean fields. Use match on text fields. If you need both behaviors on one value, map it twice, for example name as text with a name.raw keyword subfield.
Build the query on the server
Do not accept raw query JSON from the client. Accept a small, validated request such as q, category, max_price, page, and sort. Then build the bool query in your service code. This lets you cap the page size, allow only known filter fields, and avoid expensive constructs like leading wildcards or unbounded regular expressions. It is also where you attach permission filters, which a later chapter covers.
Facets
A facet is the list of values the user can click to narrow results, such as "Footwear (214)", "Jackets (87)". Search engines compute them with aggregations: counts and statistics calculated over the documents that matched the query.
GET /products/_search
{
"query": { "match": { "name": "running" } },
"size": 10,
"aggs": {
"categories": { "terms": { "field": "category", "size": 10 } },
"price_ranges": {
"range": {
"field": "price",
"ranges": [ { "to": 50 }, { "from": 50, "to": 100 }, { "from": 100 } ]
}
}
}
}The response contains the usual hits plus an aggregations object with one bucket list per facet.
Facet fields need doc values
Aggregations read from column-oriented doc values, which keyword, numeric, and date fields have by default. Aggregating on an analyzed text field is blocked unless you enable fielddata, which loads every term into heap memory. Plan the facet fields in your mapping up front.
Multi-select facets and `post_filter`
A common problem appears when you put the user's clicked category into the filter clause. Aggregations run over the filtered set, so the category facet then shows only the selected category. The user can no longer see the alternatives or switch to another one.
The post_filter clause fixes this. It narrows the returned hits after aggregations have been computed.
GET /products/_search
{
"query": { "match": { "name": "running" } },
"post_filter": { "term": { "category": "footwear" } },
"aggs": {
"categories": { "terms": { "field": "category" } }
},
"size": 10
}Here the categories facet counts every category among documents matching "running", while hits contains only footwear. For a full multi-select interface, each facet should apply every active filter except its own. You do this by wrapping each aggregation in a filter aggregation that carries the other filters.
Facet costs and accuracy
- Cardinality. A
termsaggregation on a field with millions of distinct values, such as user ID, is slow and memory-heavy. Facet only on low-to-moderate cardinality fields. - Approximate counts. Each shard returns its top buckets and the coordinator merges them. Counts for buckets near the cutoff can be slightly off, and the response reports
doc_count_error_upper_bound. Raisingshard_sizeimproves accuracy at a cost. - Cost grows with matches. Aggregations touch every matching document, not just the top 10. A broad query with five facets does much more work than the hit list suggests.
Pagination
Users expect "next page", and the engine must return the right slice of a ranked list. There are three mechanisms.
| Method | How it works | Good for | Limits |
|---|---|---|---|
| `from` and `size` | Skip `from` hits, return `size` | Page numbers, shallow browsing | Capped by `index.max_result_window` (default 10,000). Cost rises with depth. |
| `search_after` | Continue after the sort values of the last hit | "Load more", infinite scroll, deep traversal | No random page jumps. Needs a stable sort. |
| Scroll or point in time export | Walk a snapshot of the whole result set | Batch jobs and exports | Holds resources. Not for user-facing paging. |
Why deep pages are expensive
With from=9990, size=10, every shard must build a sorted list of its top 10,000 hits. The coordinating node then merges all those lists and discards 9,990. Cost scales with from + size times the number of shards. This is why the engine caps the window. Raising the cap moves the problem to memory and latency without fixing it.
Most users never go past page 5 of search results. A practical API caps the page number, for example at 50 pages, and tells the user to refine their query beyond that.
Stable ordering with `search_after`
search_after needs a sort order where no two documents tie. Scores tie often, and a tie broken differently between requests causes duplicated or skipped results. Add a unique tiebreaker. The cleanest approach is a point in time (PIT), which freezes the view of the index so that refreshes between requests do not shift results.
POST /products/_pit?keep_alive=1mThe response contains a PIT id. Pass it in the next request. Replace PIT_ID_FROM_RESPONSE with that value.
GET /_search
{
"size": 10,
"query": { "match": { "name": "running" } },
"pit": { "id": "PIT_ID_FROM_RESPONSE", "keep_alive": "1m" },
"sort": [ { "_score": "desc" }, { "_shard_doc": "asc" } ],
"search_after": [ 1.2, 4194305 ]
}The search_after values are copied from the sort array of the last hit on the previous page. With a PIT you omit the index name from the URL, because the PIT already identifies it. If you do not use a PIT, sort on a unique field instead, such as a keyword product ID.
Total counts
By default the engine counts hits exactly only up to 10,000 and reports "relation": "gte" beyond that. Exact totals require visiting every match. Show "10,000+ results" rather than forcing track_total_hits: true on every request.
How a request flows
The diagram shows where each clause takes effect.
Common mistakes
- Using
termon atextfield and getting no results. - Placing the selected facet value in
filter, so the other facet values disappear. - Paging with
fromandsizeand ordering only by_score, so tied results shift between pages. - Letting clients request
size=10000or arbitrary page numbers. - Faceting on a high-cardinality field.
- Treating the total hit count as exact.
Exercise
A user searches for "jacket" and clicks the "Outerwear" category facet. Afterward the facet list shows only "Outerwear" and the user cannot switch to "Rainwear". What caused this, and how do you fix it?
Show answer
The selected category was added to the query's filter clause, so the aggregation ran only over documents already restricted to Outerwear. Move the category condition to post_filter. Aggregations then count all categories among documents matching "jacket", while the returned hits are narrowed to Outerwear. For several active facets, wrap each aggregation in a filter aggregation that applies every active filter except its own.
Exercise
Your product list uses from and size with a score sort. QA reports that on page 3 some items from page 2 appear again, and others never appear. Give two causes and a fix.
Show answer
Scores tie, and ties can be ordered differently between requests. Index refreshes between requests can also change the result set and shift positions. Add a unique tiebreaker to the sort, such as a product ID keyword. For consistency across pages, use search_after with a point in time so each page reads the same snapshot of the index.