Elasticsearch query writing and optimization for product search 16 questions in 4 chapters

  1. 01Writing the search query5 questions
  2. 02Facets, paging and the product listing page3 questions
  3. 03Sorting, scoring and result shaping4 questions
  4. 04Aggregations and cluster-level query cost4 questions

Writing the search query

  • 1.1 How do you structure a bool query with must, should, filter and must_not? Medium 3 min

    Anything that should affect ranking, like the shopper's words, goes in must or should. Hard yes-or-no conditions such as market, category, size and stock go in filter, because filters skip scoring and can be cached. Exclusions go in must_not. Should clauses are optional boosts unless there is no must or filter, in which case one must match; minimum_should_match makes that explicit.

    Read the full answer
  • 1.2 When do you use match, match_phrase or term, and what does each cost? Medium 3 min

    match analyzes the shopper's text and finds documents with any of the words by default, or all of them with operator and. match_phrase also needs the words in order and next to each other, which reads term positions and costs more. term does no analysis, so it belongs on keyword, numeric and boolean fields for exact filters. I use match for search, match_phrase as a boost, term for filters.

    Read the full answer
  • 1.3 How do you search several product fields with boosts, and when do you pick best_fields or cross_fields? Hard 3 min

    multi_match runs the query over several fields. best_fields, the default, scores a document by its single best field, which suits "the whole query appears in the title". cross_fields treats fields with the same analyzer as one big field and looks for each word in any of them, which suits "red Nike" split across colour and brand. I boost the strong fields, like name over description, and add a small tie_breaker.

    Read the full answer
  • 1.4 How do you add typo tolerance without making every search slow? Medium 3 min

    Fuzzy matching expands each word into terms within an edit distance, then searches all of them, so cost grows with the number of expansions. I use fuzziness AUTO, which allows no edits for words up to two characters, one for three to five, and two above five. I set prefix_length so the first characters must match, keep max_expansions low, and often run fuzzy only when the exact query finds little.

    Read the full answer
  • 1.5 Should synonyms be applied at index time or at query time? Medium 3 min

    I prefer query time with a synonym_graph filter in the search analyzer. It handles multi-word synonyms correctly, and I can change the rules without reindexing; synonym sets from the synonyms API reload analyzers automatically. Index time makes queries slightly cheaper but needs a reindex for every rule change and doesn't handle multi-word synonyms well. The cost of query time is more terms per query.

    Read the full answer

Facets, paging and the product listing page

  • 2.1 Write the Elasticsearch request for a product listing page with facets, sorting and pagination. Hard 5 min

    One request with a bool query: the shopper's text in must, market and category in filter. Selected facet values go in post_filter, so facet counts are still computed over the wider result set. Each facet is a terms aggregation wrapped in a filter aggregation that applies every selected facet except its own. Sort by score or price with a unique tiebreaker, and page with search_after, not deep from.

    Read the full answer
  • 2.2 What is the difference between filter and post_filter, and what does post_filter cost? Medium 3 min

    A filter in the bool query limits both the hits and the aggregations, and it's cacheable. A post_filter runs after the aggregations, so it limits only the hits; that's how selected facets narrow the product grid while facet counts still show the other options. The cost is that the main query matches more documents than are returned, so use post_filter only for the selected facet values, never for hard limits like market.

    Read the full answer
  • 2.3 Why is deep pagination with from and size expensive, and when do you use search_after, a point in time or scroll? Hard 4 min

    For page from plus size, every shard must find its top from-plus-size hits and the coordinating node merges them all, so cost grows with depth. That's why index.max_result_window defaults to 10,000. For deep or infinite scrolling I use search_after with a unique tiebreaker, plus a point in time when pages must stay consistent. Scroll is no longer recommended for deep pagination; it's for batch exports.

    Read the full answer

Sorting, scoring and result shaping

  • 3.1 What makes sorting expensive in Elasticsearch, and how can index sorting help? Hard 3 min

    Sorting reads each matching document's value from doc values, a columnar on-disk structure, and keeps the best N per shard. It breaks on text fields, which have no doc values by default; enabling fielddata loads them into heap, which is costly. Sort on keyword or numeric fields instead. If one sort dominates, like newest first, index sorting stores documents in that order, so with track_total_hits false a shard can stop early.

    Read the full answer
  • 3.2 How do you add business signals to ranking without paying for them on every match? Hard 4 min

    function_score runs its functions on every matching document, so I keep them cheap: field_value_factor on a precomputed popularity field, filter-plus-weight boosts, no scripts. Anything heavier goes in a rescore block, which re-ranks only the top window_size hits per shard, default 10. Filters that shouldn't score go in filter or constant_score, and track_total_hits stays at its default instead of exact counts.

    Read the full answer
  • 3.3 How do you show one result per product model when each colour variant is its own document? Hard 3 min

    Use field collapsing on model_id, a single-valued keyword field with doc values: Elasticsearch keeps only the top-scoring document per model. Collapsing is cheap, but inner_hits to show the other colours sends an extra query per collapsed hit, so I keep it small or fetch variants separately. Collapsing doesn't affect aggregations or hits.total, so counts are per variant unless I add a cardinality aggregation.

    Read the full answer
  • 3.4 Why can highlighting make search slower, and how do you keep it cheap? Medium 3 min

    To build a snippet, the highlighter needs the character offsets of matched words. Without stored offsets, the unified highlighter re-analyzes the text of every returned document. Storing offsets in the postings with index_options offsets lets it skip that, and term vectors serve the fast vector highlighter at the cost of a bigger index. I highlight few fields, only for the returned page, and keep the default max_analyzed_offset cap.

    Read the full answer

Aggregations and cluster-level query cost

  • 4.1 Why are terms aggregation counts approximate, and how do you trade accuracy against cost? Hard 4 min

    Each shard returns only its top shard_size terms, default size times 1.5 plus 10, and the coordinator merges them, so a term that's big overall but small on one shard can be undercounted. doc_count_error_upper_bound shows the possible error and sum_other_doc_count what was cut. Raise shard_size before size, route related data to one shard for exact counts, use composite to page all values, and cardinality for approximate distinct counts.

    Read the full answer
  • 4.2 How do the node query cache and the shard request cache work, and how do you write queries that hit them? Hard 3 min

    The node query cache stores which documents match a filter-context clause, per segment, up to 10% of heap by default; term queries and scoring clauses aren't eligible. The shard request cache stores whole responses, by default only for size zero requests like facet counts, keyed by a hash of the entire JSON body and cleared on every refresh. So keep filters in filter context, round dates, build request JSON deterministically, and don't refresh more often than needed.

    Read the full answer
  • 4.3 How do routing and shard count affect how many shards a query touches? Hard 4 min

    By default a search goes to one copy of every shard, so each query fans out to all shards and each runs on one thread. Custom routing sends documents with the same key to one shard, so a query that knows the key hits one shard instead of all; the risk is hot or uneven shards, which routing_partition_size softens. Splitting by market into separate indices or clusters removes a filter and isolates load.

    Read the full answer
  • 4.4 How do you write range and geo filters so they stay cheap? Medium 3 min

    Ranges on numbers and dates and geo filters on geo_point fields are yes-or-no conditions, so they go in filter context, where they skip scoring and can be cached. I filter by a radius or bounding box first and only then sort by distance, because a distance sort computes a value for every match. For dates I round now, and for prices I query the precomputed per-market field.

    Read the full answer