skip to content

Search & Information Retrieval Concepts

The engine-agnostic ideas every search system rests on: inverted indexes, text analysis, ranking functions like TF-IDF and BM25, relevance tuning, and how you measure whether search is actually any good. Learn these once and Elasticsearch, Solr, and Lucene stop looking like magic.

on this pageshow

questions

page 1 of 2

What is an inverted index in a search engine, and how does it differ from a forward index?

level: juniorimportance: must knowfreq 85%

answer

  1. Think about which way the mapping points
  2. Scanning every document is far too slow
  3. Like the index at the back of a book
  4. Term to documents, not document to terms
  5. Two parts: dictionary plus postings lists

basics

~20 s

An inverted index maps each term to the list of documents containing it, so a query is a dictionary lookup instead of a scan over documents. A forward index maps each document to its terms — the natural storage direction.

solid answer

~40 s

An inverted index flips the natural storage direction. A **forward index** maps each document to the terms it contains — the shape you get if you simply store the documents. An **inverted index** maps each *term* to a **postings list**: the sorted document IDs where that term occurs, usually with a per-document frequency and often token positions. A query for one word becomes a single dictionary lookup plus a walk of one list, rather than reading every document. Multi-term queries intersect or union postings lists, and scoring reuses the counts already stored there. The price is paid at index time: text is analysed once, the term dictionary is built sorted, postings are compressed, and updates become comparatively expensive. Forward-oriented structures do not disappear — engines keep document-oriented data for highlighting, sorting and faceting.

code

json · 6 lines
json
// forward: document -> terms
{ "doc": 3, "terms": ["fast", "search", "engine"] }

// inverted: term -> sorted postings
{ "search": { "doc_freq": 3, "docs": [3, 9, 14] },
  "engine": { "doc_freq": 2, "docs": [3, 27] } }

go deeper

for a junior

Be able to define both directions in one sentence each and name the two parts of an inverted index: a term dictionary and postings lists of document IDs. The book-index comparison is a fine way to open.

for a middle

Explain why sorted document IDs turn boolean queries into a merge of sorted lists, and which statistics the index stores so that ranking needs no extra passes over the text.

for a senior

Show you know the write-side consequences: analysis is fixed at index time, single-document updates are expensive, and engines work around that with immutable index units, tombstoned deletes and background merging.

for a principal

Own the framing that a search system is several indexes at once — inverted for matching, columnar and per-document for sorting, faceting and highlighting — and that each one is a separate storage and latency budget you choose to spend.

## The problem A search engine must answer "which documents contain this word?" over millions or billions of documents, in milliseconds, for many concurrent users. Reading every document and testing it is linear in the size of the whole corpus, and the corpus is the largest thing in the system. The inverted index exists to make query cost proportional to the number of *matching* documents rather than to the number of *stored* documents. ## The forward index: document → terms If you store documents the obvious way, you have a forward index. Document 7 is a record; from its ID you can retrieve its text, or the list of terms it produced after analysis. This direction answers "what is in document 7?" in one lookup and answers "which documents contain *ranking*?" only by examining every record. ## The inverted index: term → documents Inverting means building the transpose of that relation. Conceptually you take every (document, term) pair, sort by term instead of by document, and group. The result has two parts: - **Term dictionary** — every distinct term in the corpus, held in sorted order, each entry carrying the term's document frequency (how many documents contain it) and a pointer to where its postings live. - **Postings lists** — for each term, the ascending list of document IDs containing it, typically with the term frequency in that document and, when enabled, the token positions and character offsets of each occurrence. So `search → [3, 9, 14, 27]` says exactly which documents to consider, and nothing about the other millions. ## Why this makes queries cheap Three properties fall out of the shape: 1. **Selective lookup.** A one-word query touches one dictionary entry and one list. Work scales with the number of hits, not the corpus. 2. **Cheap set algebra.** Because postings are sorted by document ID, a boolean AND is a merge of two sorted lists — linear in the shorter one when skip structures are present — and an OR is a merge union. This is why boolean queries over an inverted index are fast without any per-document work. 3. **Scoring data is already there.** Ranking models need the term frequency in the document, the document frequency of the term, and the document's length. The first two are stored in the index itself, so relevance scores are computed from numbers already being read, not by re-parsing text. ## What forward structures are still for An inverted index is a poor fit for questions that start from a document. "Show me every term in document 7 with its frequency" and "sort these 10,000 hits by price" and "count hits per category" all read *per document*. Engines therefore keep forward-oriented structures alongside the inverted one: a per-document term list (often called a term vector) for highlighting and more-like-this, a columnar per-document value store for sorting, faceting and aggregation, and the original stored content for returning results. A mature search engine is not one index; it is an inverted index plus several forward ones, each earning its storage. ## What it costs - **Build cost.** Text is analysed once, the pairs are sorted, the dictionary and postings are written. That work is real and happens on the write path. - **Storage.** Postings, and especially positions, are a substantial fraction of index size. Compression is not optional. - **Update rigidity.** Inserting one document touches the postings list of every term it contains. Most engines therefore build small immutable index units and merge them in the background rather than editing lists in place, which is why updates are visible only after a commit or refresh and why deletes are usually recorded as tombstones first. - **Analysis is baked in.** What you indexed is what you can find. Change the tokenizer or the stemmer and the existing terms are wrong; you must rebuild. ## How to say it in an interview Name both directions, name the two parts (dictionary and postings), say why sorted document IDs make boolean queries a merge, and mention that the index also carries the statistics ranking needs. Then add the honest trade-off: fast reads bought with index-time work and expensive in-place updates. That last sentence is what separates a memorised definition from understanding.

  • If the inverted index is so much better for search, why do engines keep document-oriented structures at all?
    Because some questions start from the document. Highlighting needs the terms and offsets of one specific document; sorting and faceting need one field's value for every hit, read per document. Those are answered by forward structures — term vectors and a columnar per-document value store — plus the stored original content for returning results. The inverted index would have to be scanned end to end to answer them.
  • What happens to an inverted index when a single document is updated?
    Logically, every term in that document has a postings list that must change, which is expensive in place. Most engines avoid it: they write new immutable index units, mark the old document as deleted with a tombstone so it is filtered from results, and reclaim the space later when background merging rewrites the affected units.
  • Why does query latency depend more on how common a term is than on how large the corpus is?
    Because work is proportional to postings read, not documents stored. A rare term has a short list and finishes immediately; a very common term has a list proportional to the corpus and is the expensive case. That asymmetry is why stopword handling, term-frequency-aware query planning and early-termination algorithms all target the common terms.

It is the index at the back of a textbook. The chapters themselves are the forward view; the index at the back lists each concept once with the page numbers that mention it, so you never read the book to find a word.

saying these in an interview costs you the question

  • Says the inverted index stores documents in reverse order
  • Claims search reads each document and filters it
  • Thinks it is just a hash map from document ID to text
  • Believes an inverted index makes single-document updates cheap
  • Assumes no forward structures exist alongside it

context

open as a page

In search relevance tuning, when should a requirement be a hard filter rather than a boost?

level: juniorimportance: must knowfreq 58%

basics

~20 s

Filter when a non-matching document must never be shown: permissions, region, availability. Boost when the signal is only a preference — recent or in-stock items should rank higher, but a strong match elsewhere may still outrank them.

open as a page

In search relevance evaluation, what do precision@k and recall@k measure, and how does k change each?

level: juniorimportance: must knowfreq 68%

basics

~20 s

Precision@k is the fraction of the top k results that are relevant. Recall@k is the fraction of all relevant documents that appear in the top k. Raising k can only raise recall, and usually lowers precision.

open as a page

What steps turn a raw text field into indexed terms in a search engine's analysis pipeline?

level: juniorimportance: must knowfreq 68%

basics

~20 s

Text analysis runs in three stages: character filtering (strip markup, map characters), tokenization (cut the stream into tokens), then token filtering (lowercase, fold accents, drop stopwords, stem, add synonyms). The surviving tokens become the index terms.

open as a page

What does the k constant in reciprocal rank fusion control?

level: middleimportance: must knowfreq 62%

basics

~20 s

Reciprocal rank fusion gives each document 1/(k + rank) from every list it appears in, summed. The constant k controls how sharply top ranks dominate: small k makes rank one overwhelming, large k flattens the curve so agreement across lists matters more.

open as a page

Beyond document IDs, what does a postings list store, and what does each part enable?

level: middleimportance: must knowfreq 70%

basics

~10 s

A posting carries the document ID plus, optionally, the term frequency in that document for scoring, the token positions for phrase and proximity matching, character offsets for highlighting, and sometimes per-position payloads.

open as a page

In BM25, what do the k1 and b parameters control?

level: middleimportance: must knowfreq 70%

basics

~20 s

k1 controls term-frequency saturation: how quickly extra occurrences of a term stop adding score. b controls document-length normalisation: how strongly a document longer than the collection average is penalised, from none at zero to full at one.

open as a page

In TF-IDF weighting, what do the term frequency and inverse document frequency factors each measure?

level: middleimportance: must knowfreq 75%

basics

~20 s

Term frequency measures how often a term occurs in one document, a proxy for how much that document is about the term. Inverse document frequency measures how rare the term is across the whole collection, a proxy for how discriminating it is.

open as a page

Why does boosting the title field ten times often make search relevance worse?

level: middleimportance: must knowfreq 68%

basics

~20 s

Because a boost multiplies that field's score contribution, and field contributions are not on a comparable scale. A ten-times title boost lets a weak, incidental title match outscore a document that matches the query strongly everywhere else.

open as a page

How is NDCG@k computed over a ranked result list, and why divide by the ideal DCG?

level: middleimportance: must knowfreq 72%

basics

~20 s

NDCG sums each result's graded relevance discounted by a logarithm of its position, then divides that discounted cumulative gain by the gain of the best possible ordering. The division normalises every query onto a 0-to-1 scale so scores can be averaged.

open as a page

Why must index-time and query-time text analysis produce compatible terms in a search engine?

level: middleimportance: must knowfreq 75%

basics

~20 s

Both sides must reduce text to the same term forms. The index stores analyzed terms, and a query can only match a term spelled identically after its own analysis, so mismatched pipelines silently return zero hits instead of an error.

open as a page

How do you normalize BM25 and cosine scores onto one scale before blending them?

level: seniorimportance: must knowfreq 58%

basics

~20 s

Map each leg onto a comparable range before weighting: min-max or z-score over a fixed candidate window, or a corpus-calibrated bound. Per-query min-max is the usual choice and the usual bug, because it forces a 1.0 onto every query's best hit however bad it is.

open as a page

Offline NDCG improved but online click-through fell after a ranking change. How would you diagnose that?

level: seniorimportance: must knowfreq 58%

basics

~20 s

Check first whether the click drop is real harm or good abandonment, then look for the usual gaps: an unrepresentative judgment query sample, judges guessing intent differently from users, position and presentation bias in clicks, and non-relevance regressions such as latency.

open as a page

In information retrieval, how does Boolean retrieval differ from ranked retrieval?

level: juniorimportance: should knowfreq 50%

basics

~20 s

Boolean retrieval treats a query as a logical predicate and returns an unordered set of documents that satisfy it. Ranked retrieval scores every candidate for degree of relevance and returns them ordered, so partial matches still surface.

open as a page

Why does dense vector retrieval always return k results when a keyword query can return none?

level: middleimportance: should knowfreq 52%

basics

~20 s

Nearest-neighbour search ranks by distance and has no match predicate, so it returns the k closest vectors however far away they are. Keyword retrieval intersects postings lists first, so query terms that appear nowhere yield an empty result set.

open as a page

Why is a search engine's term dictionary kept in sorted order rather than as a hash table?

level: middleimportance: should knowfreq 45%

basics

~20 s

Sorted order lets the engine enumerate ranges — prefixes, wildcards, fuzzy neighbourhoods — compress shared prefixes between adjacent terms, and hold only a sparse in-memory index over on-disk blocks. A hash table gives exact lookup and nothing else.

open as a page

In the vector space model, why is cosine similarity used instead of a raw dot product?

level: middleimportance: should knowfreq 45%

basics

~20 s

A raw dot product grows with vector magnitude, so long documents win simply for containing more terms. Cosine divides by both vector lengths, comparing the direction of the vectors — the mix of terms — rather than their size.

open as a page

How do you fold document freshness into a relevance score without letting recency dominate?

level: middleimportance: should knowfreq 52%

basics

~20 s

Multiply the relevance score by a decay factor between zero and one that falls with age, instead of adding a freshness bonus. A bounded multiplier preserves relevance ordering among documents of similar age and caps how much recency can distort ranking.

open as a page

In search evaluation, how do MAP and MRR differ, and when is each the right metric?

level: middleimportance: should knowfreq 56%

basics

~20 s

Mean reciprocal rank averages 1 divided by the position of the first relevant result, so it only sees one document per query. Mean average precision averages precision measured at every relevant position, rewarding a ranking that surfaces all relevant documents high.

open as a page

What is the difference between stemming and lemmatization in search text analysis?

level: middleimportance: should knowfreq 62%

basics

~20 s

Stemming strips affixes with language rules, fast and dictionary-free, producing stems that may not be real words. Lemmatization uses a dictionary and word context to return the true base form. Search engines usually choose stemming for speed and recall.

open as a page

What do stopwords cost in a search index, and why do modern engines usually keep them?

level: middleimportance: should knowfreq 52%

basics

~20 s

Stopword removal shrinks postings for very common words and speeds queries, but it destroys phrases and titles built from them. Modern engines usually keep stopwords because ranking already gives near-zero weight to ubiquitous terms and compression makes them cheap.

open as a page

In hybrid search, why does a selective filter hurt the vector leg more than the keyword leg?

level: seniorimportance: should knowfreq 48%

basics

~20 s

A keyword engine treats a filter as one more postings list to intersect, so it gets cheaper and stays exact as selectivity rises. An approximate vector index must discard matches after searching, or traverse a structure built over every vector, so recall falls instead.

open as a page

Why are document IDs in a postings list stored as deltas, and how does variable-byte encoding compress them?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Postings are sorted ascending, so storing gaps instead of absolute IDs turns large numbers into small ones. Variable-byte encoding then spends one byte on small gaps and more only when needed, using seven payload bits per byte plus a continuation flag.

open as a page

How do skip pointers inside a postings list speed up intersecting a rare term with a common one?

level: seniorimportance: should knowfreq 38%

basics

~20 s

An AND query drives iteration from the rarest term and asks the other lists to advance to each candidate document. Skip pointers store absolute document IDs and byte offsets at intervals, so advancing jumps over whole blocks instead of decoding every posting.

open as a page

Why does BM25 usually rank better than raw TF-IDF on collections with long documents?

level: seniorimportance: should knowfreq 55%

basics

~20 s

BM25 bounds each term's contribution with a saturation curve and folds a tunable length correction into that curve, so a long document cannot win by repetition or bulk. Raw TF-IDF grows linearly with term frequency and normalises length only crudely.

open as a page

How do you add popularity signals to search ranking without a rich-get-richer feedback loop?

level: seniorimportance: should knowfreq 47%

basics

~20 s

Saturate the raw counts, cap popularity's share of the total score, and correct for position bias — clicks measure where a document ranked as much as how good it was. Add exploration and signal ageing so new documents can be discovered.

open as a page

What does a learning-to-rank re-ranker require that hand-tuned relevance boosts do not?

level: seniorimportance: should knowfreq 44%

basics

~20 s

Labelled training data, a feature pipeline that produces identical values at training and serving time, and a latency budget for re-scoring the top candidates. Hand-tuned boosts need none of that, but they also cannot learn interactions between signals.

open as a page

Why can interleaving two search rankings detect a winner with less traffic than an A/B test?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Interleaving blends both rankings into one result list per query, so every user compares both systems at once. That paired within-user design removes between-user variance, which is what makes an A/B test need large samples.

open as a page

Why does pooling to build a relevance judgment set bias evaluation against a newly built retrieval system?

level: seniorimportance: should knowfreq 42%

basics

~10 s

Pooling judges only the documents that the contributing systems retrieved, and everything unjudged is scored as non-relevant. A new system that surfaces relevant documents no contributor ever returned is therefore penalised for finding them.

open as a page

What do you trade away by indexing edge n-grams to power prefix autocomplete?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Edge n-grams index every prefix of every token so a prefix search becomes a plain term lookup. The cost is a multiplied index and term dictionary, distorted term statistics, and a full reindex whenever the gram length range changes.

open as a page

showing 1–30 of 36