Companies Level 2 This level · 7 of 7
Medium zalando companies

Why does a term query on a text field miss documents, and how do multi-fields fix it?

The 30 second answer

A text field is analyzed at index time, so "Red Dress" is stored as the tokens red and dress. A term query is not analyzed, so it looks for the exact string Red Dress and finds nothing. Use match for full text, and add a keyword sub-field through multi-fields for exact filters, sorting and facets. That gives one source value indexed two ways, each for its own job.

Could you say this in an interview?

This is one of the most common Elasticsearch mistakes, and it shows up again in the facet question below, because facets need the same exact values.

Why it misses. The official docs warn: "Avoid using the term query for text fields." A text field goes through an analyzer at index time. The default standard analyzer removes most punctuation, splits on word boundaries and lowercases, so the brand value "Tommy Hilfiger" is indexed as the two terms tommy and hilfiger. A term query is not analyzed. Searching term: { brand: "Tommy Hilfiger" } looks for one term with a capital T and a space in it, which does not exist in the index, so it returns nothing. term: { brand: "tommy" } would match, which is even more confusing in a code review.

Match versus term. A match query runs the query text through the field's search analyzer first, so match: { brand: "Tommy Hilfiger" } produces the same tokens and matches. Use match (and its relatives such as multi_match) for what a shopper types, and term, terms or range for exact, structured values such as an id, a size code or a flag.

Multi-fields. Most product attributes need both behaviours: brand must be searchable as words and also filterable, sortable and aggregatable as an exact value. Multi-fields index the same source value more than once:

"brand": {
  "type": "text",
  "fields": {
    "raw": { "type": "keyword" }
  }
}

Queries use brand for full text and brand.raw for term filters, sorting and terms aggregations. A keyword field is indexed as one unanalyzed term and has doc values, which is what sorting and aggregations read. If case differences in the source are a problem, a normalizer on the keyword field lowercases it without splitting it.

Why the dynamic default matters. With dynamic mapping, Elasticsearch typically maps a new string as text with a keyword sub-field, which is why field.keyword appears in so many examples. In a production catalog you want explicit mappings instead, so analyzers per language and keyword sizes are deliberate and a stray field cannot cause a mapping explosion.

How to debug it live. Run the _analyze API with the field's analyzer on the stored value and on the query text, then compare tokens. If the tokens differ, the query type or the mapping is wrong.

Alternate interview scenarios

"A filter on colour works for most values but not for 'Light Blue'. Why?"

Most colours are single words, so the analyzed tokens happen to equal the lowercased value and a term filter on lowercase input appears to work. "Light Blue" becomes two tokens, so an exact match on the whole value can never succeed against the text field. The fix is to filter on a keyword sub-field, with a normalizer if the data has inconsistent casing.

"Can you aggregate on a text field?"
Not by default, because text fields do not have doc values; aggregations and sorting need a keyword (or numeric) field. Enabling fielddata on a text field makes it possible but loads the analyzed terms into heap, which is expensive and aggregates on tokens rather than whole values. Use a keyword sub-field instead.

<!-- include: system-design/elasticsearch-slow-query-pitfalls#a-search-query-is-slow-even-though-every-field-is-indexed --> <!-- why: A latency debugging question is likely in a search round, and the answer starts with the slow log and Profile API, not guesses. -->

<!-- include: system-design/elasticsearch-slow-query-pitfalls#why-is-a-wildcard-search-that-starts-with-an-asterisk-slow --> <!-- why: Shoppers and internal tools type contains-style searches, and a core search API has to stop leading wildcards from hurting a shared cluster. -->

<!-- include: system-design/elasticsearch-slow-query-pitfalls#why-do-scripts-make-elasticsearch-queries-slow-and-what-do --> <!-- why: Ranking and sorting in a catalog tempt teams into scripts; moving the work to index time is the expected senior answer. -->

<!-- include: system-design/elasticsearch-slow-query-pitfalls#should-a-product-id-be-mapped-as-a-number-or-a-keyword-in --> <!-- why: Product and SKU IDs are everywhere in a fashion catalog, so the mapping choice comes up in any search design review. -->

<!-- include: system-design/elasticsearch-slow-query-pitfalls#why-do-date-range-queries-with-now-miss-the-cache-and-how --> <!-- why: New-arrivals and campaign pages filter by date for many shoppers at once, which is exactly where cacheable filters pay off. -->

<!-- include: system-design/elasticsearch-slow-query-pitfalls#how-do-you-make-prefix-and-autocomplete-queries-fast-in --> <!-- why: Autocomplete runs on every keystroke in the shop search box, so its query cost multiplies quickly. -->

<!-- include: system-design/elasticsearch-slow-query-pitfalls#why-does-searching-across-many-fields-slow-elasticsearch --> <!-- why: Product documents carry many attributes, and search across all of them must stay fast while title and brand keep their boosts. -->

<!-- include: system-design/elasticsearch-query-optimization#how-do-you-structure-a-bool-query-with-must-should-filter --> <!-- why: Every search request starts as a bool query, and putting brand, size and market in the right clause decides both ranking and caching. -->

<!-- include: system-design/elasticsearch-query-optimization#when-do-you-use-match-match-phrase-or-term-and-what-does --> <!-- why: Choosing match, phrase or term for a shopper query is the first thing a live Elasticsearch exercise checks. -->

<!-- include: system-design/elasticsearch-query-optimization#how-do-you-search-several-product-fields-with-boosts-and --> <!-- why: Queries like "red nike sneakers" span colour, brand and type fields, so the multi_match type changes what ranks first. -->

<!-- include: system-design/elasticsearch-query-optimization#how-do-you-add-typo-tolerance-without-making-every-search --> <!-- why: Misspelled brand and product names are common in shop search, and fuzziness is easy to make expensive. -->

<!-- include: system-design/elasticsearch-query-optimization#should-synonyms-be-applied-at-index-time-or-at-query-time --> <!-- why: A multi-market, multi-language catalog needs synonyms that change without a reindex. -->

<!-- include: system-design/elasticsearch-query-optimization#write-the-elasticsearch-request-for-a-product-listing-page --> <!-- why: The most likely live task: a catalog page with facets, sort and paging, the same split the Zalando catalog layer uses for facet calls. -->

<!-- include: system-design/elasticsearch-query-optimization#what-is-the-difference-between-filter-and-post-filter-and --> <!-- why: Selected facets must narrow the grid while facet counts still show alternatives, which is what post_filter is for. -->

<!-- include: system-design/elasticsearch-query-optimization#why-is-deep-pagination-with-from-and-size-expensive-and --> <!-- why: Zalando names max_result_window as a guardrail; deep paging by shoppers, crawlers or exports is a classic follow-up. -->

<!-- include: system-design/elasticsearch-query-optimization#what-makes-sorting-expensive-in-elasticsearch-and-how-can --> <!-- why: Sort by price or newest is on every listing page, and sorting the wrong field type is a common production mistake. -->

<!-- include: system-design/elasticsearch-query-optimization#how-do-you-add-business-signals-to-ranking-without-paying --> <!-- why: Blending popularity and stock into ranking without scoring every match connects query writing to the two-stage ranking stack. -->

<!-- include: system-design/elasticsearch-query-optimization#how-do-you-show-one-result-per-product-model-when-each --> <!-- why: Colour variants as separate documents make field collapsing and its counting caveats a natural fashion-search question. -->

<!-- include: system-design/elasticsearch-query-optimization#why-can-highlighting-make-search-slower-and-how-do-you --> <!-- why: Highlighting is a hidden per-result cost that shows up in latency reviews of search APIs. -->

<!-- include: system-design/elasticsearch-query-optimization#why-are-terms-aggregation-counts-approximate-and-how-do --> <!-- why: Facet counts are approximate across shards, which follows directly from the facet overload incident on this page. -->

<!-- include: system-design/elasticsearch-query-optimization#how-do-the-node-query-cache-and-the-shard-request-cache --> <!-- why: Zalando caches queries and facets at several layers; knowing which Elasticsearch requests are cacheable is the base of that design. -->

<!-- include: system-design/elasticsearch-query-optimization#how-do-routing-and-shard-count-affect-how-many-shards-a --> <!-- why: Market isolation across clusters and shard fan-out decide how far one heavy query can spread. -->

<!-- include: system-design/elasticsearch-query-optimization#how-do-you-write-range-and-geo-filters-so-they-stay-cheap --> <!-- why: Price sliders, new-arrival dates and store availability are range and geo filters on catalog queries. -->

<!-- include: system-design/postgresql-query-optimization#how-do-you-read-an-explain-analyze-plan-and-what-do-you --> <!-- why: Catalog and offer data behind search often lives in PostgreSQL, and reading a plan is the first step of any SQL question. -->

<!-- include: system-design/postgresql-query-optimization#a-query-that-was-fast-yesterday-is-slow-today-with-no-code --> <!-- why: Zalando has published its own PostgreSQL plan-flip story caused by rare status values, so expect statistics to come up. -->

<!-- include: system-design/postgresql-query-optimization#how-do-you-choose-the-column-order-of-a-composite-index --> <!-- why: Composite, partial and covering indexes are the standard answer to a slow catalog or order query. -->

<!-- include: system-design/postgresql-query-optimization#why-does-wrapping-a-column-in-a-function-or-comparing-it --> <!-- why: Functions and type mismatches on indexed columns are the SQL version of the slow-query-despite-index question. -->

<!-- include: system-design/postgresql-query-optimization#why-can-an-or-condition-make-postgresql-ignore-your --> <!-- why: Optional-filter endpoints generate OR conditions that quietly turn index lookups into full scans. -->

<!-- include: system-design/postgresql-query-optimization#how-do-you-make-a-contains-search-like-like-boot-fast-and --> <!-- why: Contains search in PostgreSQL versus a search engine is a natural question for a search team. -->

<!-- include: system-design/postgresql-query-optimization#how-does-postgresql-choose-between-a-nested-loop-hash-join --> <!-- why: Join strategy choice explains most slow multi-table reports and depends on row estimates. -->

<!-- include: system-design/postgresql-query-optimization#when-do-you-use-exists-in-or-a-join-and-why-is-not-in --> <!-- why: Semi-joins, anti-joins and the NOT IN null trap are common live SQL follow-ups. -->

<!-- include: system-design/postgresql-query-optimization#why-is-count-slow-on-a-large-table-and-what-do-you-do --> <!-- why: Exact result counts cost in PostgreSQL just as track_total_hits does in Elasticsearch. -->

<!-- include: system-design/postgresql-query-optimization#how-do-you-get-the-top-n-rows-per-group-such-as-the-three --> <!-- why: Top products per category is the classic window-function live coding task. -->

<!-- include: system-design/postgresql-query-optimization#live-task-write-the-sql-for-a-monthly-category-report-then --> <!-- why: A report query written step by step, then indexed, is the likely shape of a SQL whiteboard round. -->

<!-- include: api-performance/api-latency-optimization#how-do-you-find-and-fix-an-n-1-problem --> <!-- why: A Java search API that loads products and then their brands or prices one by one is the N+1 problem in Hibernate or across services. -->

<!-- include: api-performance/api-latency-optimization#offset-pagination-is-slow-on-page-5-000-why-and-how-do-you --> <!-- why: Keyset pagination is the SQL twin of search_after, with a published incident showing what deep OFFSET does to a shared database. -->

Sources (3)
  1. Elasticsearch: Term queryelastic.co
  2. Elasticsearch: Multi-fieldselastic.co
  3. Elasticsearch: Keyword field typeelastic.co
Previous
Next