Course map

Topic 209 / Advanced

Search engine internals: inverted indexes, relevance, faceting

Chapter 13.1 · Search Engine Internals

What and why

Database full-text search (→ 65) works until query volume, relevance sophistication, or data volume outgrows what a relational engine's full-text features can do economically — the moment a product catalog needs faceted navigation, typo-tolerant ranking, or sub-second search over very large document sets, a dedicated search engine takes over. Its core data structure is the inverted index: instead of mapping document → words (a forward index), it maps word → list of documents containing it, making "find every document containing X" a single lookup instead of a full scan. Builds on: → 65 (full-text search basics; its own description names the handoff point: "large scale → 209").

Diagram

Documents                         Inverted index
───────────                       ──────────────
doc1: "red shoes"                 "red"   → [doc1, doc3]
doc2: "blue socks"                "shoes" → [doc1]
doc3: "red socks"                 "blue"  → [doc2]
                                   "socks" → [doc2, doc3]

Query "red socks" → intersect postings for "red" and "socks" → [doc3]

How it works

  1. Tokenization and analysis — each document's text is split into tokens, lowercased, stripped of punctuation, and reduced to a base form (stemming); stop words and synonyms are handled here so the index stores normalized terms, not raw text.
  2. Inverted index build — for each normalized term, append the document's ID (and position/frequency) to that term's postings list; a query becomes list intersection/union over postings instead of a scan over documents.
  3. Relevance scoring ranks matches instead of just finding them. TF-IDF weights a term by how often it appears in a document (term frequency) against how rare it is across all documents (inverse document frequency — common words score low). BM25 refines this with saturation (a term repeated 50 times doesn't score 50× higher than once) and length normalization (a short document isn't penalized against a long one).
  4. Faceting counts, alongside the ranked results, how many matching documents fall into each value of chosen fields (brand, price range, color) by aggregating over the same postings lists — the sidebar counts a faceted-search UI shows.
  5. Index sharding partitions the index (the partitioning concept of → 73, applied to an index instead of a table) across nodes by document range or hash; a query fans out to every shard and merges ranked results.
  6. Near-real-time refresh: new or changed documents aren't instantly searchable — engines batch recent writes into small, immutable index segments on a short interval, merging segments in the background, a deliberate latency between write and visibility.
  7. Autocomplete is built on a separate structure, typically a trie (→ 2), matching query prefixes to completions by traversal rather than postings lookup.

Practical example

(illustrative). A 3-document catalog: doc1 "red shoes", doc2 "blue socks", doc3 "red socks". "red" appears in 2 of 3 documents (common, lower relevance weight); "shoes" appears in 1 of 3 (rarer, higher weight). A query for "red shoes" matches only doc1 on both terms, while doc3 matches "red" alone. Scoring both terms together — not just counting matches — is why doc1 outranks doc3: doc1 fully satisfies the query, doc3 only partially does.

When to use it

  • Use when: relevance ranking matters (not just filtering), faceted navigation is a UI requirement, or query volume and document count have outgrown the database's full-text index.
  • Avoid when: exact-match or simple filtered lookups suffice, or data volume is small — database full-text search (→ 65) is the simpler default until measurement says otherwise.
  • Failure scenarios: the index and database drifting out of sync when reindexing has no reliable replay path from the source of truth; a hot shard from a skewed term slowing every query that touches it; near-real-time refresh delay surprising users who expect a write to be instantly searchable.
  • Simpler alternative: database full-text search (→ 65) for smaller catalogs and lower query complexity.

Practice

(Mechanism kind — build a tiny version; 25–30 min, no lab services). Build an inverted index by hand (or in a few lines of code) over 10 short sentences you write yourself. Implement a query that intersects postings for a 2-word query, then compute a simplified TF-IDF score (term count in document ÷ document length, times log of total documents ÷ documents containing the term) for each match and rank by it. Done when editing one document to repeat a query term correctly changes its rank.

Key takeaway

A search engine is an inverted index plus a relevance function plus the operational machinery — sharding, near-real-time refresh — to keep both current at scale. Done when you can: explain why postings-list intersection beats scanning documents, and compute a TF-IDF score by hand. Used next in → 222 (vector search's hybrid keyword-plus-vector mode reuses this retrieval model).

References

None — this topic makes no external claims.

Source directory

Search the guide