Skip to main content

Search & Inverted Indexes

Learning objectives
  • Explain how an inverted index and an analysis pipeline turn text into searchable terms, and why LIKE '%…%' does not scale
  • Explain BM25 scoring and how to blend text relevance with business signals for product search
  • Describe Elasticsearch/OpenSearch internals — shards, replicas, segments, refresh, translog, query-then-fetch — and size a cluster roughly
  • Design a reliable DB → search pipeline with CDC, plus autocomplete and faceted navigation, for an e-commerce catalog or a bank's transaction search

TL;DR​

  • An inverted index maps each term to a sorted postings list of documents (with frequencies and positions). Queries become fast set operations on postings, not table scans.
  • Analyzers (character filters → tokenizer → token filters) decide what a "term" is: lowercasing, accent folding (điện thoại → dien thoai), stemming, synonyms, n-grams. Index-time and query-time analysis must be compatible.
  • BM25 (the default in Lucene-based engines) scores by term rarity (IDF), saturating term frequency (k1, default 1.2) and length normalisation (b, default 0.75). Product search then blends in popularity, stock and margin.
  • Elasticsearch/OpenSearch index = N primary shards (fixed at creation) + replicas; each shard is a Lucene index of immutable segments. New documents become visible after a refresh (≈ 1 s by default) — near real-time, not transactional.
  • The search index is a derived read model, never the source of truth. Feed it from the database via CDC or an outbox, with idempotent, versioned upserts and a reindex-with-alias-swap procedure.
  • Autocomplete uses edge n-grams or a completion suggester; facets use aggregations over keyword fields backed by doc values.

Why it matters​

  • E-commerce: search is often the most-used entry point to the catalog and among the strongest purchase-intent signals. Zero-result queries, slow facets or a misspelt "iphon" returning nothing lose revenue directly. During a sale, search traffic spikes along with everything else. See Product Catalog & Search.
  • Banking: customers search their own history ("Grab", "250,000", "rent"), support agents search across customers by phone, name or reference (with strict access control and audit), and compliance runs fuzzy name screening against sanctions lists. All need text search over data whose system of record is a relational ledger.
  • Interviews: "design product search", "design autocomplete" and "how do you keep Elasticsearch in sync with the database?" are common, and they test both data-structure knowledge and pipeline design.

Core concepts​

Why not LIKE​

WHERE name LIKE '%phone%' cannot use a B-tree index (leading wildcard), returns no relevance ranking, does not understand plurals, accents or typos, and degrades linearly with table size. PostgreSQL full-text search (tsvector + GIN) or trigram indexes (pg_trgm) are good options for moderate needs inside the database; dedicated engines win when you need rich relevance, facets, autocomplete and scale.

The inverted index​

Three products:

DocTitle
1Apple iPhone 15 128GB Black
2Samsung Galaxy phone case black
3iPhone 15 silicone case

After analysis (lowercase, tokenise), the index looks like:

TermPostings (doc: term frequency)
apple1:1
black1:1, 2:1
case2:1, 3:1
iphone1:1, 3:1
phone2:1
151:1, 3:1
  • Postings are sorted by doc id and compressed (delta encoding plus compact integer codecs), so intersections and unions are fast sequential merges with skip lists.
  • Positions enable phrase and proximity queries ("iphone 15" as a phrase).
  • Lucene stores the term dictionary compactly (as a finite-state transducer), which also enables fast prefix and fuzzy lookups.
  • Doc values are a separate columnar structure per field used for sorting, aggregations and scripting — the inverted index answers "which docs contain term t", doc values answer "what is field f for doc d".

Analysis: tokenizers and analyzers​

  • Tokenizer: splits text into tokens. Standard/ICU tokenizers handle Unicode word boundaries; language-specific tokenizers handle languages without spaces (Chinese, Japanese, Thai).
  • Token filters: lowercase; ASCII folding (removing diacritics); stop words; stemming/lemmatisation for languages like English ("running" → "run"); synonyms ("tv" ⇄ "tivi" ⇄ "television"); n-grams for partial matching.
  • Vietnamese specifics: words are often multi-syllable with spaces between syllables (điện thoại is one word, two syllables), and users type both with and without diacritics. A practical approach is a multi-field: one sub-field with folding (matches dien thoai), one without (exact diacritics score higher), plus phrase or shingle matching so syllables that belong together rank above scattered matches. Community Vietnamese analysis plugins exist; evaluate them against your query logs.
  • Index vs query time: the same analyzer is used by default. Synonyms are often applied at query time so you can update them without reindexing.

Relevance: BM25 and business signals​

BM25 scores each matching term t in document d and sums over the query terms:

score(t, d) = IDF(t) × tf × (k1 + 1) / (tf + k1 × (1 − b + b × len(d) / avg_len))

  • IDF (inverse document frequency): rare terms ("silicone") weigh more than common ones ("case").
  • tf with saturation (k1, default ≈ 1.2): a term appearing 10 times is better than once, but not 10× better — keyword stuffing has diminishing returns.
  • Length normalisation (b, default 0.75): a match in a short title is worth more than the same match in a long description.

Product search is rarely pure text relevance:

  • Field boosts: title matches count more than description matches (title^3).
  • Phrase/proximity boosts: "iphone 15" adjacent beats scattered.
  • Business signals via function scores: sales velocity, rating, in-stock status, margin, freshness, sponsored placement. Filter out-of-stock or push it down rather than hiding it, depending on policy.
  • Learning to rank: train a model on click and purchase logs to re-rank the top few hundred results.
  • Measure: zero-result rate, click-through and conversion per query, and offline metrics such as NDCG on judged queries. Relevance changes go through A/B tests.
  • Semantic search: vector (embedding) search catches meaning ("laptop for students") that keywords miss; modern engines support hybrid retrieval that combines BM25 and vector scores.

Elasticsearch / OpenSearch architecture​

OpenSearch is the open-source fork of Elasticsearch 7.10 (2021); the core architecture below applies to both, with features diverging by version.

  • Cluster and nodes: master-eligible nodes manage cluster state and shard allocation (use three for quorum); data nodes hold shards; ingest nodes run pre-processing pipelines; any node can coordinate requests.
  • Index → shards: an index has N primary shards (fixed at creation; changing it requires split/shrink or reindex) and R replicas of each. A document's shard is hash(_routing) mod number_of_primary_shards, where _routing defaults to the document id. Custom routing (for example by customer_id) can keep one customer's documents on one shard.
  • Replicas provide failover and extra read throughput; they are never placed on the same node as their primary.
  • Search is query-then-fetch: the coordinator sends the query to one copy of every shard, each returns its top-k ids and scores, the coordinator merges them, then fetches the winning documents. Deep pagination (from=10000) makes every shard produce 10,000+ results — use search_after with a point-in-time instead.

Write path:

  • Segments are immutable. Updates are "delete old + index new"; deletes are tombstones until segments merge. Heavy update workloads cost merge I/O.
  • Refresh makes buffered documents searchable (default about every second on active indexes) — this is why search is near real-time. You can request refresh=wait_for for read-your-writes on a specific write, at a throughput cost; during bulk reindexing, raise or disable the refresh interval.
  • Translog provides durability between flushes; it is replayed after a crash.
  • No multi-document transactions, no joins: denormalise into the document (product + brand name + category path + price), or use limited nested/parent-child structures.

Rough sizing guidance (check your engine's current docs): keep shards in the tens of gigabytes, avoid thousands of tiny shards (each has heap and file overhead), size heap and filesystem cache together, and separate heavy aggregation or log workloads from latency-critical product search.

ApproachProblem
Dual write from the app (DB then search)Partial failures leave them inconsistent; ordering across concurrent writers is lost
Periodic batch reindexStale for minutes to hours; heavy load
CDC from the DB log (or a transactional outbox)Ordered per row, captures every writer including batch jobs and manual fixes — the usual choice

Making CDC indexing correct:

  • Key the topic by document id so updates for one product stay ordered.
  • Idempotent, versioned upserts: index with an external version (the row version or the commit LSN) so a late or replayed event never overwrites newer data.
  • Deletes: propagate tombstones; soft-deleted rows become deletes or "hidden" flags.
  • Enrichment: a product document needs brand, category and price from several tables — either join at the source (an outbox event with the full document) or have the indexer look them up and re-index when a dependency changes (a brand rename touches thousands of products).
  • Full reindex with alias swap: create products_v8 with the new mapping, backfill from a snapshot, replay CDC from the snapshot's position until caught up, then atomically point the products alias at v8. Zero downtime, instant rollback.
  • Monitor lag (DB commit → searchable) as an SLO, and reconcile counts periodically.

Background on CDC: Transactional Outbox & CDC.

Autocomplete​

  • Edge n-grams at index time (iphone → i, ip, iph, …) let a normal match query act as prefix search; Elasticsearch's search_as_you_type field type packages this.
  • Completion suggester: an in-memory FST of suggestions with weights — extremely fast prefix lookups, but prefix-only and with limited filtering.
  • Query suggestions vs result suggestions: suggest popular queries (from logs, with counts and decay) or jump straight to products and categories.
  • Typo tolerance: fuzzy matching with edit distance 1–2 for longer prefixes.
  • Latency budget: each keystroke needs a response within roughly 100 ms end to end; debounce on the client, cache popular prefixes, keep the suggestion index small.
  • Full design: Search Autocomplete.

Facets (brand, price range, rating, colour) with counts come from aggregations:

  • terms aggregations on keyword fields (never on analysed text fields), range aggregations for price buckets, filter aggregations for flags like "free shipping".
  • They run over doc values, the columnar store.
  • Multi-select facets: apply the user's facet selections with a post_filter (filters the hits, not the aggregations) and per-facet filtered aggregations, so the brand facet still shows other brands' counts when one brand is selected.
  • Counts for terms aggregations across shards can be approximate for the long tail; increase shard_size if accuracy matters. Distinct counts use HyperLogLog-style approximations.

Trade-offs​

OptionStrengthsWeaknessesChoose when
SQL LIKEZero infrastructureNo relevance, full scansTiny tables, admin tools
PostgreSQL FTS / pg_trgmTransactional, no sync pipelineLimited relevance tuning, facets and scaleModerate search inside one DB (bank back-office, small catalog)
Elasticsearch / OpenSearchRich relevance, facets, autocomplete, scale-outSeparate cluster, sync pipeline, near-real-time onlyProduct search, log search, large catalogs
Managed search SaaSFast to ship, good relevance toolingCost at scale, data residency, less controlSmaller teams, non-sensitive catalogs
Vector / hybrid searchSemantic matchingEmbedding pipeline, cost, explainabilityNatural-language queries, recommendations
Edge n-gramsFlexible prefix matching with full queriesLarger indexSearch-as-you-type with filters
Completion suggesterVery fast prefix lookupPrefix-only, limited filteringQuery suggestions
CDC indexingOrdered, complete, decoupledPipeline to operateDefault sync strategy
Dual writesSimple to startInconsistency on failuresPrototypes only

In practice​

  • Explicit mappings, no dynamic mapping for user-controlled attributes (it causes mapping explosions). A product mapping sketch — vi_folded is a custom analyzer (standard tokenizer + lowercase + ASCII folding) defined in the index settings, omitted here; flattened is Elasticsearch's type for arbitrary key-value attributes (OpenSearch has flat_object):
{
"mappings": {
"dynamic": "strict",
"properties": {
"title": {
"type": "text",
"analyzer": "vi_folded",
"fields": {
"exact": { "type": "text", "analyzer": "standard" }
}
},
"title_suggest": { "type": "search_as_you_type" },
"brand": { "type": "keyword" },
"category_path": { "type": "keyword" },
"price_vnd": { "type": "long" },
"in_stock": { "type": "boolean" },
"sales_30d": { "type": "integer" },
"attributes": { "type": "flattened" }
}
}
}
  • A query that matches on folded and exact fields, filters cheaply, and boosts by sales:
{
"query": {
"function_score": {
"query": {
"bool": {
"must": [
{ "multi_match": { "query": "dien thoai iphone", "fields": ["title^2", "title.exact^3"] } }
],
"filter": [
{ "term": { "in_stock": true } },
{ "range": { "price_vnd": { "lte": 30000000 } } }
]
}
},
"field_value_factor": { "field": "sales_30d", "modifier": "log1p", "factor": 0.5 },
"boost_mode": "sum"
}
},
"aggs": { "brands": { "terms": { "field": "brand", "size": 20 } } }
}
  • A CDC indexer batches events into the bulk API with external versions, so replays and out-of-order deliveries are harmless:
package indexer

import (
"bytes"
"encoding/json"
)

type ProductChanged struct {
ID string `json:"id"`
Version int64 `json:"version"` // row version or commit LSN, monotonic per product
Deleted bool `json:"deleted"`
Doc json.RawMessage `json:"doc"`
}

// BulkBody builds NDJSON for the _bulk endpoint. With version_type=external the
// engine rejects any operation whose version is not newer than the stored one
// (a 409 per item), which the indexer treats as "already applied".
func BulkBody(index string, events []ProductChanged) ([]byte, error) {
var buf bytes.Buffer
enc := json.NewEncoder(&buf) // Encode appends the newline NDJSON needs
for _, e := range events {
meta := map[string]any{"_index": index, "_id": e.ID, "version": e.Version, "version_type": "external"}
action := "index"
if e.Deleted {
action = "delete"
}
if err := enc.Encode(map[string]any{action: meta}); err != nil {
return nil, err
}
if !e.Deleted {
if err := enc.Encode(e.Doc); err != nil {
return nil, err
}
}
}
return buf.Bytes(), nil
}
  • Banking search hygiene: encrypt at rest, restrict who can query cross-customer indexes, apply document- or field-level security where supported, mask PII in results, audit every back-office search, and keep retention aligned with the source data.

Common pitfalls​

  • Treating search as the source of truth. Symptom: an order or balance shown from search disagrees with the database; data lost when the index is rebuilt.
  • Dual writes. Symptom: products that exist in the DB but not in search (or vice versa) after partial failures.
  • Out-of-order CDC updates without versioning. Symptom: an old price reappears after a replay or consumer restart.
  • Dynamic mapping on arbitrary attributes. Symptom: thousands of fields, cluster-state bloat, slow masters.
  • Too many small shards. Symptom: high heap usage and slow cluster operations despite little data.
  • Aggregating on text fields or sorting on analysed fields. Symptom: errors or nonsense facet values ("dien", "thoai").
  • Deep pagination with from/size. Symptom: latency and memory spikes for page 500; use search_after.
  • Ignoring diacritics. Symptom: dien thoai returns nothing while điện thoại works, or vice versa.
  • No reindex plan. Symptom: a mapping change requires downtime or a risky in-place migration.
  • Refresh interval left at 1 s during a full reindex. Symptom: slow bulk loads and heavy merging.

Interview angle​

  • Where it appears: "design product search for an e-commerce site", "design autocomplete", "design log search", or "customers want to search their transaction history".
  • Strong answer covers: inverted index and analyzers (including language specifics), relevance (BM25 plus business signals), index/shard/replica design, the DB → search sync pipeline with ordering and versioning, near-real-time visibility, autocomplete and facets, and how the system behaves under reindex and failure.
  • Follow-ups: "How fast does a price change show up in search?", "How do you change the mapping without downtime?", "How do you rank in-stock items higher?", "How do you handle typos?", "Why not just use PostgreSQL?", "How do you size shards?"
  • Red flags: writing to search and DB independently with no consistency story, using search for authoritative data, no idea what a refresh is, "just add more shards".

Self-check​

1. Explain how a query iphone case is answered by an inverted index.

The query text is analysed into terms (iphone, case). The engine looks up each term's postings list (sorted doc ids with frequencies/positions), merges them (union for OR, intersection for AND) using sorted merges and skip lists, scores matching documents with BM25 (plus boosts), and returns the top results. No document is scanned that does not contain at least one term.

2. What do BM25's k1 and b control, and why do they matter for product titles vs descriptions?

k1 controls term-frequency saturation: more occurrences help but with diminishing returns, limiting keyword stuffing. b controls length normalisation: matches in shorter fields count more. Titles are short and precise, so a match there should outweigh one in a long description — length normalisation and explicit field boosts both encode that.

3. Why is a document not immediately searchable after indexing, and what can you do about it?

New documents go into an in-memory buffer (and the translog for durability) and become searchable only when a refresh writes a new segment, by default about every second. For a specific write that must be visible immediately, use refresh=wait_for (costly at scale); otherwise design the UX for near-real-time (for example, show the item from the API response, not from search).

4. Design a zero-downtime mapping change for a 50 M-document product index.

Create a new index with the new mapping and a higher refresh interval. Record the CDC position (Kafka offset or LSN), snapshot-backfill from the database, then replay CDC from the recorded position with external versioning until lag is near zero. Validate counts and sample queries, restore the refresh interval, atomically swap the alias, and keep the old index for rollback until confident.

5. Scenario: a product's price was changed twice quickly (100 → 90 → 80), but search shows 90. What happened and how do you prevent it?

The two update events were applied out of order (parallel consumers, a retry, or a replay), so 90 overwrote 80. Prevent it by keying events by product id so they are ordered within a partition, and indexing with an external version (row version or LSN) so an older version is rejected. Periodic reconciliation catches anything else.

6. How would you build transaction search for a bank's mobile app?

The ledger stays the source of truth. CDC feeds an index of transactions with customer-scoped routing (so a customer's documents live together) and fields for merchant name (folded and exact), description, amount, date and category. Every query is filtered by the authenticated customer id on the server, never by the client. Encrypt at rest, mask sensitive fields, and fall back to a keyset-paginated DB query for exact lookups. For modest volumes, PostgreSQL full-text search on a per-customer partition may be enough.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

  1. Run OpenSearch or Elasticsearch locally (single node, Docker). Create a products_v1 index with a folded analyzer (lowercase + ASCII folding) and an exact sub-field; load 100k products (generate Vietnamese and English titles).
  2. Compare results and scores for điện thoại and dien thoai with and without the exact sub-field boost. Use the _analyze API to show the tokens.
  3. Build a CDC pipeline: PostgreSQL → Debezium → Kafka → a Go indexer using the BulkBody function. Update the same product's price 1,000 times rapidly from two writers and verify the final indexed price equals the DB.
  4. Perform an alias-swap reindex to products_v2 with a new field while a load generator queries products; record errors (should be zero).

Done looks like: _analyze output for both queries, a passing consistency check, and a log of the reindex with no failed queries.

Further reading​

  • Introduction to Information Retrieval (Manning, Raghavan, Schütze) — inverted indexes, compression, scoring (free online edition from Stanford NLP).
  • Relevant Search (Doug Turnbull, John Berryman, Manning) — practical relevance tuning.
  • Robertson & Zaragoza, "The Probabilistic Relevance Framework: BM25 and Beyond" (Foundations and Trends in IR, 2009).
  • Elasticsearch Reference and OpenSearch documentation: index modules, refresh, translog, mapping, aggregations, search_after.
  • Elasticsearch: The Definitive Guide (Gormley & Tong) — older version, still a good conceptual tour of internals.
  • Debezium documentation (debezium.io) — PostgreSQL and MySQL connectors.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).