Inverted indexes and analysis

Tokenisation, stemming, the analyser chain, and the difference between a text field and a keyword field.

12 min read🔎 Search with Elasticsearch

WHERE title LIKE '%kafka%' scans every row and finds nothing for "Kafka's" or "kafka-based". A search engine answers the same question in milliseconds over millions of documents because it did the work at index time: it broke each document into terms, normalised them, and built a structure that maps every term to the documents containing it. Understanding that structure — and the analysis that feeds it — is most of what separates a search that works from one that returns nothing for the query the user actually typed.

The inverted index

A database index maps a key to rows. An inverted index maps a term to the list of documents it appears in, with positions:

plaintext
term        postings (doc id: positions)
"kafka"     1:[3], 4:[0, 12], 9:[7]
"consumer"  1:[4], 9:[8]
"lag"       1:[5]

A query for kafka consumer looks up two postings lists and intersects them — document 1 and 9 — in time proportional to the lists' lengths, not the corpus size; a phrase query additionally checks that the positions are adjacent. That is the whole reason full-text search is fast, and it is also why the choice of what counts as a term is the choice of what can be found at all: if "Kafka's" was indexed as the term kafka's, a query for kafka will not match it.

Elasticsearch (and OpenSearch, the same engine forked) keeps one such index per field, in Lucene segments that are written once and never modified — a deleted document is marked, an updated one is a delete plus a new document, and segments are periodically merged. Two operational facts follow: an index is near-real-time, with a document searchable about a second after it is written (the refresh_interval), not immediately; and an update is not cheap, because it is a whole new document.

Analysis: from text to terms

An analyser is the pipeline that turns a string into terms, applied to the document at index time and — this is the part people miss — to the query at search time, so that both sides agree. It has three parts:

  1. Character filters: strip HTML, map characters (& to and).
  2. A tokeniser: split into tokens. standard splits on Unicode word boundaries; whitespace only on spaces; keyword does not split at all; ngram and edge_ngram produce substrings for autocomplete; pattern splits on a regex.
  3. Token filters: lowercase; stop removes "the", "a", "of"; stemmer reduces "consumers" and "consuming" to consum; asciifolding turns "café" into "cafe"; synonym expands "k8s" to "kubernetes".
a custom analyserjson
"analysis": {
  "analyzer": { "en_tech": { "tokenizer": "standard", "filter": ["lowercase", "asciifolding", "english_stop", "english_stemmer"] } },
  "filter": { "english_stemmer": { "type": "stemmer", "language": "english" }, "english_stop": { "type": "stop", "stopwords": "_english_" } }
}

The _analyze API shows what an analyser does to a string — POST /_analyze { "analyzer": "en_tech", "text": "Kafka's consumers are lagging" } returns kafka, consum, lag — and it is the first thing to run when a query does not match: analyse the document's text and the query's text and compare the terms. Stemming is language-specific (the English stemmer mangles German), and stemming plus stop words trade recall for precision in ways a product team should decide, not a default.

text versus keyword

The most consequential mapping decision, and the one every Elasticsearch beginner gets wrong once:

  • A text field is analysed: split into terms, lowercased, stemmed. It is for full-text search — match queries, relevance scoring, phrase queries. It cannot be sorted on, aggregated on, or matched exactly, because the field's value is gone; only its terms remain.
  • A keyword field is stored as one term, exactly as given. It is for identifiers, status codes, tags, email addresses, anything you filter with term, sort by, or aggregate over. A term query on a keyword field for PAID matches PAID; the same query on a text field matches nothing, because the indexed term is paid.

A field that needs both — a product name you search and sort by — is mapped as text with a keyword sub-field (name and name.keyword), which is what dynamic mapping does for every string, and which doubles the index for strings that only ever needed one of the two.

Mappings

A mapping is the schema: each field's type and analyser. text, keyword, the numeric types, date with its formats, boolean, geo_point, nested for arrays of objects whose fields must be matched together (the MongoDB $elemMatch problem: without nested, an array of {sku, qty} objects is flattened into two independent arrays, and sku: A-1 AND qty > 5 matches across elements), and object for everything else. Set the mapping explicitly before the first document, with "dynamic": "strict" so that an unexpected field is an error rather than a guess.

Because a field's type and analyser decide what was indexed, a mapping cannot be changed for an existing field: changing status from text to keyword means reindexing every document into a new index, which is what the operations lesson's aliases are for. Design the mapping from the queries — the same access-pattern-first rule as the document-modelling lesson — and treat it as a migration when it changes.

Dynamic mapping traps

With no mapping, the first document's shape becomes the mapping, guessed. The guesses that hurt: a string becomes text with a keyword sub-field (fine, and twice the size); a number that arrives as "42" in the first document becomes a keyword and rejects 42 in the second; a date that arrives as "2026-09-18" becomes a date and rejects "18/09/2026"; a field that is an object in one document and a string in another rejects the second forever; and a document with a thousand distinct keys (a map of user-defined attributes) creates a thousand fields, which is the mapping explosion that makes a cluster slow and is capped by index.mapping.total_fields.limit at 1,000 for exactly that reason. Every one of those is an indexing error at 3 am on a document that was fine in development. Explicit mappings, dynamic: strict, and flattened for the user-defined maps.

Under the hood: the tokenizer/filter chain, and what stemming actually does to a word

The system design course's search lesson gives the shape of an inverted index — term maps to postings, tokenising and stemming happen before the index is built. What it does not go into is the pipeline mechanics, and mechanics are where "the query doesn't match" incidents actually live.

The chain runs in a fixed order, and each stage's output is the next stage's only input. Character filters see the raw string first (and can rewrite it before anything else looks at it — stripping HTML tags, mapping & to and); the tokeniser sees only what the character filters produced, never the original string, and splits it into a sequence of tokens; each token filter then runs over that token sequence in the order it is declared, one filter's output feeding the next. Reorder lowercase and stop in the filter list and nothing breaks, because both are case- and content-independent of order here — but reorder stemmer before lowercase and a capitalised word can reach the stemmer un-lowercased, matching none of the suffix rules the stemmer expects and passing through unstemmed. The chain is a pipeline, not an unordered set of options, and the order in a custom analyser's filter array is the order it runs.

Stemming is not a lookup — it is a rule-driven suffix rewrite, and the classic algorithm (Porter, 1980) works in an ordered sequence of steps. Each step is a small set of suffix-replacement rules — "if the word ends in -ATIONAL, and enough of a stem precedes it, replace with -ATE; if it ends in -SSES, replace with -SS" — and "enough of a stem precedes it" is measured by counting the consonant-vowel groups before the suffix (Porter's m), so that a long enough word ending in -ational becomes -ate (national → nation in a later step) while a short word that happens to end the same way is left alone rather than stripped down to nothing. The rules are applied in a fixed sequence of passes, each looking only at the suffix that remains after the previous pass, which is why stemmers are fast (no dictionary lookup, just pattern matching) and why they are crude: consum (from consuming, consumer, consumes) is not an English word, and the algorithm has no idea whether saw is the past tense of "see" or a tool — it strips suffixes by shape, never by meaning.

Lemmatization is the different, more expensive approach the stemmer is often confused with. A lemmatiser looks a word up against a vocabulary (and often needs the word's part of speech to disambiguate: "saw" as a verb lemmatises to "see", as a noun it stays "saw") and returns an actual dictionary form — better → good, ran → run — rather than a truncated stem. Elasticsearch ships stemmers for many languages (Snowball, an improved successor to Porter's original algorithm, among them) but no general lemmatiser out of the box, because a correct lemmatiser needs language resources and POS tagging a suffix-stripping algorithm does not.

Why index-time and query-time analysis must be the identical pipeline, concretely. A term match is string equality between the term the document produced and the term the query produced — nothing about "close enough". If the field's analyser stems at index time (consuming → consum) but the query is run with match_phrase against a keyword sub-field, or a synonym filter is added to the index-time analyser without adding it to the query-time one, the two sides produce different term sets and the query returns zero results with no error anywhere — not a slow query, not an exception, just silence. That is why _analyze (run against the mapped field, not a guessed analyser name) is the first diagnostic step in the "why did this match nothing" runbook: it shows the actual terms each side produced, and the mismatch is usually visible in one comparison.

Try it yourself

Trace the analyser by hand

An index maps a description field to a custom analyser: tokenizer: standard, filters ["lowercase", "english_stop", "english_stemmer"] (the same chain as the en_tech example above, minus asciifolding). A document is indexed with the text "The Consumers Are Running Slow".

Work out, in order, what each stage produces, then check your trace.

Walk the chain stage by stage

The standard tokeniser splits on word boundaries first, before any filter runs: ["The", "Consumers", "Are", "Running", "Slow"] — five tokens, punctuation and case untouched. lowercase runs next, over every token: ["the", "consumers", "are", "running", "slow"]. english_stop removes stop words next — "the" and "are" are both in the English stop list, "consumers", "running" and "slow" are not — leaving ["consumers", "running", "slow"]. english_stemmer runs last, over what's left: consumers → consum, running → run, slow → slow (already at its stem), giving the final term list ["consum", "run", "slow"]. Two things follow from the order: stop-word removal runs on lowercased tokens (an analyser with stop before lowercase would fail to remove a capitalised "The"), and the stemmer sees only the three surviving tokens — a stop word is gone before the stemmer would ever touch it, so stemming rules never need to account for function words at all.

A query for "consumers running" through the same analyser produces ["consum", "run"], which both appear in the document's postings — a match, even though neither literal query word appears in the indexed terms.

Misconceptions

  • "Stemming and lemmatization are two names for the same normalisation step." A stemmer strips suffixes by pattern, fast and dictionary-free, and often produces a string that is not a real word (consum); a lemmatiser looks a word up and returns an actual dictionary form, needs a vocabulary (and often part-of-speech context) to do it, and costs more. Elasticsearch's built-in stemmer filters are stemmers, not lemmatisers — swapping languages does not change that trade-off.
  • "As long as the document's text is analysed correctly, search will work." Analysis runs on the query too, and it is the agreement between the two that makes a term match, not either one alone. A query that reaches the engine through a different code path — a different field, a term query instead of match, an override of the query-time analyser — can silently stop matching content that was indexed perfectly correctly.

Sources

  • M. F. Porter, "An algorithm for suffix stripping", Program, 1980 — the stemming algorithm described above.
  • Christopher D. Manning, Prabhakar Raghavan and Hinrich Schütze, Introduction to Information Retrieval — tokenisation, stemming and lemmatization, chapter 2.
  • Elasticsearch documentation, "Text analysis" (analyzers, tokenizers, token filters, the _analyze API and the stemmer/snowball filters).
Progress is saved on this device and to your account when signed in.