Search and inverted indexes
How full-text search works: analysis, the inverted index and posting lists, BM25 ranking, measuring relevance, immutable segments with refresh and merge, sharded search with global statistics, and keeping the index in sync.
ConceptCore32 min readUpdated
- 1 architecture diagram
- 1 sequence flow
- 8 code samples
- 9 interviewer follow-ups
- 4 self-checks
On this page14 sectionsHLDLLDSenior depth
- Explain how an inverted index answers keyword, boolean and phrase queries, and what analysis does to both documents and queries.
- Explain BM25 (term frequency, inverse document frequency, saturation, length normalisation) and measure ranking quality with MRR and nDCG.
- Describe immutable segments, refresh, merging and deletes, and why search lags writes.
- Design a sharded search cluster (scatter-gather, global statistics, deep pagination) and keep it in sync with a source-of-truth database.
8 code samples (419 lines), collapsed so the explanation stays in focus.
A B-tree index finds a row when you know the value of a column. Search asks something different: which of ten million documents are about "storage engines", and in what order should they be shown? A scan with LIKE '%storage%' reads every row and knows nothing about relevance. A B-tree on the text column cannot find a word inside it. Search needs its own data structure, the inverted index, and its own idea of a good answer: a ranking.
Four needs push search out of the relational database. Matching inside text: you want documents containing the words, whatever their order, with plurals and tenses treated alike. Ranking: the best answer first, not any answer. Forgiveness: typos, synonyms, partial words. Scale and speed: results in tens of milliseconds over many millions of documents, with filters and counts (facets) alongside.
The tools are Lucene and the systems built on it (Elasticsearch, OpenSearch, Solr), newer engines such as Tantivy, Meilisearch, Typesense and Vespa, and the full-text features of databases (PostgreSQL's tsvector with a GIN index, SQLite's FTS5). They differ in scale and features, and inside they do the same thing.
A book has an index at the back: for each term, the pages where it appears. An inverted index is the same thing for documents. It maps every term to a posting list, the sorted list of documents that contain it. (The same structure finds the time series that carry a label in a time-series database.) Each posting stores the document id, how many times the term occurs (the frequency, used for ranking) and where (the positions, used for phrases).
Before indexing, text goes through analysis: split into tokens, lowercase, reduce words to a stem so that "running", "runs" and "run" meet, and sometimes drop very common words (stop words; many modern engines keep them, because dropping them breaks phrases such as "to be or not to be" and idf already makes them cheap to ignore). The same analysis must be applied to the query, or the terms will not match. Real analyzers use Porter or Snowball stemming and language-specific rules; the sample's stemmer is crude on purpose.
To answer a query the engine looks up only the posting lists of the query's terms, never the whole collection:
- AND: intersect the sorted lists by walking them together, starting from the shortest, since the result can never be longer than it. A plain merge costs the sum of the lengths; real engines add skip pointers to leap through the longer lists, so the work approaches the length of the shortest one, not the size of the collection.
- OR: merge the lists.
- Phrase ("storage engines"): find documents containing all terms, then check that the positions are consecutive.
Real engines compress the lists (document ids are stored as small gaps in blocks, packed into few bits each) and add skip pointers so that an intersection can jump over stretches that cannot match. The sample keeps the structure and drops the compression.
C# · Analysis turns text into the terms that are indexed and searched. The same steps must…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
// Analysis turns text into the terms that are indexed and searched. The same steps must run on documents and on queries.
public static class Analyzer
{
private static readonly HashSet<string> StopWords = new HashSet<string> { "a", "an", "the", "and", "or", "of", "to", "in", "is", "it", "for", "on", "with" };
public static List<string> Terms(string text) =>
Regex.Split(text.ToLowerInvariant(), "[^a-z0-9]+")
.Where(word => word.Length > 0 && !StopWords.Contains(word))
.Select(Stem)
.ToList();
// A very small stemmer, so that "running" and "runs" meet at "run". Real analyzers use Porter or Snowball.
public static string Stem(string word)
{
string stem = word;
if (word.EndsWith("ies") && word.Length > 4) stem = word.Substring(0, word.Length - 3) + "y";
else if (word.EndsWith("ing") && word.Length > 5) stem = word.Substring(0, word.Length - 3);
else if (word.EndsWith("ed") && word.Length > 4) stem = word.Substring(0, word.Length - 2);
else if (word.EndsWith("s") && !word.EndsWith("ss") && word.Length > 3) stem = word.Substring(0, word.Length - 1);
if (stem != word && stem.Length > 2 && stem[^1] == stem[^2] && "bdgmnprt".Contains(stem[^1])) stem = stem.Substring(0, stem.Length - 1); // runn -> run
return stem;
}
}
// One entry in a posting list: the document, how often the term occurs in it, and where.
public sealed record Posting(int DocId, int Frequency, int[] Positions);
// What a ranking function needs to know about the collection. An index knows its own; a cluster can supply the total.
public interface ICollectionStatistics
{
int Documents { get; }
int DocumentFrequency(string term);
double AverageLength { get; }
}
// The inverted index: for each term, the sorted list of documents that contain it.
public sealed class InvertedIndex : ICollectionStatistics
{
private readonly SortedDictionary<string, List<Posting>> postings = new SortedDictionary<string, List<Posting>>(StringComparer.Ordinal);
private readonly Dictionary<int, int> lengths = new Dictionary<int, int>();
public int Documents => lengths.Count;
public double AverageLength => lengths.Count == 0 ? 0 : lengths.Values.Average();
public int Length(int doc) => lengths[doc];
public IEnumerable<int> DocIds => lengths.Keys;
// Documents must be added in increasing id order, which keeps every posting list sorted without a sort.
public void Add(int docId, string text)
{
var terms = Analyzer.Terms(text);
lengths[docId] = terms.Count;
foreach (var group in terms.Select((term, position) => (term, position)).GroupBy(t => t.term))
{
if (!postings.TryGetValue(group.Key, out var list)) postings[group.Key] = list = new List<Posting>();
list.Add(new Posting(docId, group.Count(), group.Select(t => t.position).ToArray()));
}
}
public IReadOnlyList<Posting> Postings(string term) => postings.TryGetValue(term, out var list) ? list : (IReadOnlyList<Posting>)Array.Empty<Posting>();
public int DocumentFrequency(string term) => Postings(term).Count;
// Documents containing every term: intersect the posting lists, starting with the shortest.
public List<int> All(IEnumerable<string> terms)
{
var lists = terms.Select(t => Postings(t).Select(p => p.DocId).ToList()).OrderBy(l => l.Count).ToList();
if (lists.Count == 0) return new List<int>();
var result = lists[0];
foreach (var next in lists.Skip(1)) result = Intersect(result, next);
return result;
}
public List<int> Any(IEnumerable<string> terms) => terms.SelectMany(t => Postings(t).Select(p => p.DocId)).Distinct().OrderBy(d => d).ToList();
// The documents where the terms occur next to each other, in order. This is why postings store positions.
public List<int> Phrase(IReadOnlyList<string> terms)
{
var result = new List<int>();
foreach (int doc in All(terms))
{
var first = Postings(terms[0]).First(p => p.DocId == doc).Positions;
bool found = first.Any(start => Enumerable.Range(1, terms.Count - 1).All(i => Postings(terms[i]).First(p => p.DocId == doc).Positions.Contains(start + i)));
if (found) result.Add(doc);
}
return result;
}
private static List<int> Intersect(List<int> a, List<int> b) // both sorted: walk them together
{
var result = new List<int>();
int i = 0, j = 0;
while (i < a.Count && j < b.Count)
{
if (a[i] == b[j]) { result.Add(a[i]); i++; j++; }
else if (a[i] < b[j]) i++;
else j++;
}
return result;
}
}C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
Debug.Assert(string.Join(" ", Analyzer.Terms("The Running dogs, and the cities!")) == "run dog city");
// A random collection: 2,000 documents of 5 to 40 words from a vocabulary of 300, with a few very common words.
var corpusRandom = new Random(12);
var vocabulary = Enumerable.Range(0, 300).Select(i => "w" + (char)('a' + i % 26) + (char)('a' + i / 26 % 26) + (i % 7 == 0 ? "ing" : "")).ToArray();
string RandomWord() => vocabulary[(int)(Math.Pow(corpusRandom.NextDouble(), 2.5) * vocabulary.Length)]; // a skewed pick: low indexes are common
var docs = Enumerable.Range(0, 2_000).Select(id => string.Join(" ", Enumerable.Range(0, corpusRandom.Next(5, 41)).Select(_ => RandomWord()))).ToList();
var index = new InvertedIndex();
for (int id = 0; id < docs.Count; id++) index.Add(id, docs[id]);
var tokenized = docs.Select(Analyzer.Terms).ToList();
// The index must give exactly the answers a scan of every document gives, for AND queries, OR queries and phrases.
for (int q = 0; q < 300; q++)
{
var terms = Enumerable.Range(0, corpusRandom.Next(1, 4)).Select(_ => Analyzer.Stem(RandomWord())).ToList();
var scanAll = Enumerable.Range(0, docs.Count).Where(d => terms.All(t => tokenized[d].Contains(t))).ToList();
var scanAny = Enumerable.Range(0, docs.Count).Where(d => terms.Any(t => tokenized[d].Contains(t))).ToList();
Debug.Assert(index.All(terms).SequenceEqual(scanAll));
Debug.Assert(index.Any(terms).SequenceEqual(scanAny));
}
for (int q = 0; q < 300; q++)
{
int source = corpusRandom.Next(docs.Count);
var words = tokenized[source];
if (words.Count < 3) continue;
int start = corpusRandom.Next(words.Count - 2);
var phrase = words.Skip(start).Take(2 + corpusRandom.Next(2)).ToList();
var scanPhrase = Enumerable.Range(0, docs.Count).Where(d => Enumerable.Range(0, tokenized[d].Count - phrase.Count + 1).Any(s => tokenized[d].Skip(s).Take(phrase.Count).SequenceEqual(phrase))).ToList();
Debug.Assert(index.Phrase(phrase).SequenceEqual(scanPhrase));
Debug.Assert(scanPhrase.Contains(source));
}The test builds 2,000 random documents. It runs 300 random queries, each as an AND and as an OR, and 300 phrases cut from real documents, against the index and against a brute-force scan of every document. The index gave exactly the scan's answers every time.
A matching document is not necessarily a good one. Scoring combines a few ideas.
- Term frequency (tf): a document that mentions "raft" five times is more likely to be about Raft than one that mentions it once.
- Inverse document frequency (idf): a term that appears in almost every document tells you little ("the", "system"); a rare term is strong evidence. The weight of a term falls as the number of documents containing it rises.
- Saturation: the tenth occurrence adds much less than the second. Raw counts reward repetition without limit, which is what keyword stuffing exploits.
- Length normalisation: three mentions in a 50-word page mean more than three in a 5,000-word one.
BM25 (Okapi BM25) combines all four, and has been the default scoring in Lucene and Elasticsearch since 2016. For one term in one document:
score = idf * f * (k1 + 1) / (f + k1 * (1 - b + b * len / avglen))
score one term's score in one document; a query adds up its terms
f how often the term occurs in the document
len the document's length; avglen is the collection's average
idf ln(1 + (N - n + 0.5) / (n + 0.5)), N documents, n contain the term
k1, b 1.2 and 0.75 by default: saturation speed and length effectReal systems add field boosts (a match in the title counts more than in the body), proximity (terms close together), and signals that are not about text: freshness, popularity, click-through, personalisation. A common design is two stages: BM25 retrieves a few hundred candidates cheaply, and a learning-to-rank model rescoring them with many features picks the order.
C# · Scoring, Ranking, Evaluation
using System;
using System.Collections.Generic;
using System.Linq;
public enum Scoring { TermCount, TfIdf, Bm25 }
public static class Ranking
{
public const double K1 = 1.2, B = 0.75; // BM25's usual defaults
// How surprising a term is: rare terms carry more information than common ones. (Lucene's form: never negative.)
public static double Idf(int documents, int documentFrequency) =>
Math.Log(1 + (documents - documentFrequency + 0.5) / (documentFrequency + 0.5));
// BM25 for one term in one document. The frequency saturates (the tenth occurrence adds little) and is discounted
// for documents longer than average.
public static double Bm25(double frequency, double length, double averageLength) =>
frequency * (K1 + 1) / (frequency + K1 * (1 - B + B * length / averageLength));
// Scores every document that contains at least one query term, term by term, and returns the best k.
public static List<(int Doc, double Score)> Search(InvertedIndex index, ICollectionStatistics stats, string query, int k, Scoring scoring)
{
var scores = new Dictionary<int, double>();
foreach (string term in Analyzer.Terms(query).Distinct())
{
int df = stats.DocumentFrequency(term);
foreach (var posting in index.Postings(term))
{
double weight = scoring switch
{
Scoring.TermCount => posting.Frequency,
Scoring.TfIdf => posting.Frequency * Math.Log((double)stats.Documents / Math.Max(1, df)),
_ => Idf(stats.Documents, df) * Bm25(posting.Frequency, index.Length(posting.DocId), stats.AverageLength),
};
scores[posting.DocId] = scores.GetValueOrDefault(posting.DocId) + weight;
}
}
return scores.OrderByDescending(s => s.Value).ThenBy(s => s.Key).Take(k).Select(s => (s.Key, s.Value)).ToList();
}
}
public static class Evaluation
{
// Reciprocal rank of the first relevant result: 1 if it is first, 1/2 if second, and so on.
public static double ReciprocalRank(IReadOnlyList<int> ranked, Func<int, bool> relevant)
{
for (int i = 0; i < ranked.Count; i++) if (relevant(ranked[i])) return 1.0 / (i + 1);
return 0;
}
// Normalised discounted cumulative gain at k: relevant results near the top count most, scaled so a perfect list scores 1.
public static double NdcgAt(int k, IReadOnlyList<int> ranked, Func<int, bool> relevant, int totalRelevant)
{
double dcg = ranked.Take(k).Select((doc, i) => relevant(doc) ? 1 / Math.Log2(i + 2) : 0).Sum();
double ideal = Enumerable.Range(0, Math.Min(k, totalRelevant)).Select(i => 1 / Math.Log2(i + 2)).Sum();
return ideal == 0 ? 0 : dcg / ideal;
}
}The sample first checks each effect as a number, then compares three scorers on a labelled collection: 1,000 documents of 30 to 600 words, each about one of 20 topics; 60 spam pages that repeat one topic term 40 times among common words; and 300 queries of two terms from one topic plus one common word, as real queries carry words that tell you little. A document is relevant if it is about the query's topic.
C# · The three effects BM25 is built from, as numbers.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// The three effects BM25 is built from, as numbers.
Debug.Assert(Ranking.Idf(1_000, 10) > 3 * Ranking.Idf(1_000, 900)); // a rare term is worth much more than a common one
Debug.Assert(Ranking.Bm25(2, 100, 100) < 2 * Ranking.Bm25(1, 100, 100)); // the second occurrence adds less than the first
Debug.Assert(Ranking.Bm25(10, 100, 100) < 1.5 * Ranking.Bm25(5, 100, 100)); // and by ten the curve has flattened
Debug.Assert(Ranking.Bm25(3, 50, 100) > Ranking.Bm25(3, 400, 100)); // the same count in a short document counts for more
// A labelled collection. 1,000 documents, each about one of 20 topics. Every topic has 15 signature terms, 8% of a document's
// words are drawn from them, and the rest are common words shared by all topics. Document lengths vary from 30 to 600 words.
// Then 60 spam pages: 300 words of common text with one signature term stuffed in 40 times. They are about no topic.
var labelRandom = new Random(2);
var common = Enumerable.Range(0, 200).Select(i => "common" + i).ToArray();
string Common() => common[(int)(Math.Pow(labelRandom.NextDouble(), 3) * common.Length)];
string Signature(int topic) => "topic" + topic + "term" + labelRandom.Next(15);
var topicOf = new List<int>();
var searchIndex = new InvertedIndex();
for (int id = 0; id < 1_000; id++)
{
int topic = labelRandom.Next(20);
int length = labelRandom.Next(30, 601);
topicOf.Add(topic);
searchIndex.Add(id, string.Join(" ", Enumerable.Range(0, length).Select(_ => labelRandom.NextDouble() < 0.08 ? Signature(topic) : Common())));
}
for (int id = 1_000; id < 1_060; id++)
{
topicOf.Add(-1);
searchIndex.Add(id, string.Join(" ", Enumerable.Repeat(Signature(labelRandom.Next(20)), 40).Concat(Enumerable.Range(0, 300).Select(_ => Common()))));
}
// 300 queries: two terms of one topic and one common word, the way real queries carry words that tell you little.
var results = new Dictionary<Scoring, (double Mrr, double Ndcg)>();
foreach (var scoring in new[] { Scoring.TermCount, Scoring.TfIdf, Scoring.Bm25 })
{
var queryRandom = new Random(99);
double mrr = 0, ndcg = 0;
for (int q = 0; q < 300; q++)
{
int topic = queryRandom.Next(20);
string query = $"topic{topic}term{queryRandom.Next(15)} topic{topic}term{queryRandom.Next(15)} {common[queryRandom.Next(5)]}";
var ranked = Ranking.Search(searchIndex, searchIndex, query, 10, scoring).Select(r => r.Doc).ToList();
Func<int, bool> relevant = doc => topicOf[doc] == topic;
mrr += Evaluation.ReciprocalRank(ranked, relevant);
ndcg += Evaluation.NdcgAt(10, ranked, relevant, topicOf.Count(t => t == topic));
}
results[scoring] = (mrr / 300, ndcg / 300);
}
foreach (var r in results) Console.WriteLine($"{r.Key}: MRR {r.Value.Mrr:F3}, nDCG@10 {r.Value.Ndcg:F3}");
Debug.Assert(results[Scoring.Bm25].Ndcg > results[Scoring.TermCount].Ndcg + 0.1); // ignoring how common a term is hurts a lot
Debug.Assert(results[Scoring.Bm25].Ndcg >= results[Scoring.TfIdf].Ndcg);| Scoring | MRR | nDCG@10 |
|---|---|---|
| Raw term count | 0.514 | 0.308 |
| TF-IDF (count times idf) | 0.850 | 0.930 |
| BM25 | 0.995 | 0.998 |
Counting terms without weighting them is dominated by the common word in the query, so long documents win whatever they are about. Weighting by idf removes that. But plain TF-IDF still counts 40 mentions as 40 times one, so the spam pages that match a query term climb above real answers. BM25's saturation caps what 40 mentions can earn at about twice the score of one, so repetition stops paying. (Common TF-IDF variants dampen the count with a logarithm, which softens the problem without capping it.) The collection is synthetic: the numbers show the direction of each effect, not the quality of any real system.
Relevance is easy to argue about and hard to improve by anecdote: a change that fixes one query usually breaks another. The discipline is offline evaluation with a set of queries and judgments of which documents are relevant (labelled by people, or inferred from clicks, which are biased toward whatever was shown first). Common measures:
- Precision@k and recall@k: of the top k, how many are relevant; of all relevant, how many are in the top k.
- Mean reciprocal rank (MRR): the average over queries of 1 / (rank of the first relevant result). It suits "find the one right answer" queries.
- nDCG@k: the discounted cumulative gain of the top k, with gains discounted by the logarithm of the rank and divided by the best possible score so a perfect list is 1. It handles several relevant results and graded relevance, and rewards putting the good ones first.
The sample implements MRR and binary nDCG. Offline numbers tell you whether a change helps on the judged queries; online tests (A/B experiments on click-through, reformulation rate and zero-result rate) tell you whether it helps users. Watch queries that return nothing and queries that users immediately rewrite: they point at missing synonyms, bad analysis or missing content.
A real index is not one structure rewritten on every change. In Lucene and Elasticsearch it is a set of segments, each a small, complete, immutable inverted index. New documents wait in an in-memory buffer (and in a transaction log for durability). A refresh, by default every second on an index that is being searched, writes the buffer as a new segment, and only then can those documents be found: search is near real time, not instant. Immutability makes segments cheap to read, cache and copy, and it means a document cannot be changed in place.
- Updates and deletes are recorded as a bitmap of deleted documents next to the segment; the old version stays on disk. An update is a delete plus an add. The deleted documents are skipped at query time.
- Merges run in the background: several small segments are rewritten into one larger one, dropping deleted documents and keeping the segment count low. Reads must consult every segment, so too many segments slow queries. This is the same idea as compaction in an LSM tree (see storage engines and indexes), for the same reasons, including a cost in write amplification and I/O.
C# · An immutable piece of the index, plus a bitmap of the documents that have been deleted…
using System;
using System.Collections.Generic;
using System.Linq;
// An immutable piece of the index, plus a bitmap of the documents that have been deleted from it since.
public sealed class Segment
{
public readonly InvertedIndex Index = new InvertedIndex();
public readonly Dictionary<int, string> Documents = new Dictionary<int, string>();
public readonly HashSet<int> Deleted = new HashSet<int>();
}
// How Lucene and Elasticsearch organise an index: new documents wait in a buffer, a refresh turns the buffer into a new
// segment (and only then can they be searched), and background merges combine small segments into larger ones.
public sealed class SegmentedIndex
{
private const int MergeFactor = 4;
private readonly List<(int Id, string Text)> buffer = new List<(int Id, string Text)>();
private readonly List<int> pendingDeletes = new List<int>();
public readonly List<Segment> Segments = new List<Segment>();
public void Add(int id, string text) { Delete(id); buffer.Add((id, text)); } // an update is a delete plus an add
public void Delete(int id) { buffer.RemoveAll(b => b.Id == id); pendingDeletes.Add(id); }
public void Refresh()
{
foreach (int id in pendingDeletes)
foreach (var segment in Segments) if (segment.Documents.ContainsKey(id)) segment.Deleted.Add(id); // marked, not removed
pendingDeletes.Clear();
if (buffer.Count > 0)
{
var segment = new Segment();
foreach (var (id, text) in buffer.OrderBy(b => b.Id)) { segment.Index.Add(id, text); segment.Documents[id] = text; }
Segments.Add(segment);
buffer.Clear();
}
MergeSmallSegments();
}
// Segments of a similar size are merged four at a time, so the number of segments stays logarithmic in the data.
private void MergeSmallSegments()
{
while (true)
{
var tier = Segments.GroupBy(s => (int)Math.Log(Math.Max(1, s.Documents.Count), MergeFactor)).FirstOrDefault(g => g.Count() >= MergeFactor);
if (tier == null) return;
Merge(tier.Take(MergeFactor).ToList());
}
}
// A merge writes a new segment from the live documents only, which is when deleted documents really go away.
public void Merge(IReadOnlyList<Segment> inputs)
{
var merged = new Segment();
var live = inputs.SelectMany(s => s.Documents.Where(d => !s.Deleted.Contains(d.Key))).OrderBy(d => d.Key);
foreach (var d in live) { merged.Index.Add(d.Key, d.Value); merged.Documents[d.Key] = d.Value; }
foreach (var s in inputs) Segments.Remove(s);
Segments.Add(merged);
}
public void ForceMerge() => Merge(Segments.ToList());
// Search every segment and skip the deleted documents.
public List<int> All(IReadOnlyList<string> terms) =>
Segments.SelectMany(s => s.Index.All(terms).Where(d => !s.Deleted.Contains(d))).OrderBy(d => d).ToList();
}C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
var segmentRandom = new Random(8);
var segmented = new SegmentedIndex();
var model = new Dictionary<int, string>(); // what the index should contain once it has been refreshed
string Words() => string.Join(" ", Enumerable.Range(0, segmentRandom.Next(4, 12)).Select(_ => "t" + segmentRandom.Next(40)));
int nextId = 0, maxSegments = 0;
for (int op = 1; op <= 4_000; op++)
{
int roll = segmentRandom.Next(10);
if (roll < 6 || model.Count == 0) { string text = Words(); segmented.Add(nextId, text); model[nextId++] = text; } // a new document
else if (roll < 8) { int id = model.Keys.ElementAt(segmentRandom.Next(model.Count)); string text = Words(); segmented.Add(id, text); model[id] = text; } // an update
else { int id = model.Keys.ElementAt(segmentRandom.Next(model.Count)); segmented.Delete(id); model.Remove(id); } // a delete
if (op % 20 == 0)
{
segmented.Refresh(); // only now do the last twenty changes become visible
maxSegments = Math.Max(maxSegments, segmented.Segments.Count);
var terms = Enumerable.Range(0, segmentRandom.Next(1, 3)).Select(_ => "t" + segmentRandom.Next(40)).ToList();
var expected = model.Where(d => terms.All(t => Analyzer.Terms(d.Value).Contains(t))).Select(d => d.Key).OrderBy(d => d).ToList();
Debug.Assert(segmented.All(terms).SequenceEqual(expected));
}
}
segmented.Refresh();
int storedBeforeMerge = segmented.Segments.Sum(s => s.Documents.Count);
segmented.ForceMerge();
int storedAfterMerge = segmented.Segments.Sum(s => s.Documents.Count);
Debug.Assert(segmented.Segments.Count == 1 && storedAfterMerge == model.Count); // deleted and replaced versions are gone
Debug.Assert(storedBeforeMerge > storedAfterMerge && maxSegments <= 12); // and the segment count stayed small all along
// A document added now cannot be found until a refresh.
segmented.Add(99_999, "brand new zzzword");
Debug.Assert(segmented.All(new[] { "zzzword" }).Count == 0);
segmented.Refresh();
Debug.Assert(segmented.All(new[] { "zzzword" }).SequenceEqual(new[] { 99_999 }));The test applies 4,000 random adds, updates and deletes, refreshing every 20 operations, and after every refresh compares the segmented index's answer to a query against a simple model. They always agreed. The index never held more than 11 segments, because merging combines four segments of similar size at a time. Before the final merge it stored 1,673 documents to serve 1,557 live ones: the rest were deleted and replaced versions that only a merge removes. A document added after the last refresh was not found until the next refresh.
One machine cannot hold or serve a large index, so the index is split into shards, each a complete index over part of the documents, and each shard has replicas for availability and for more query throughput. A query goes to a coordinator, which sends it to one copy of every shard (scatter), takes each shard's best k results, merges them and keeps the best k (gather). A second step fetches the stored fields (title, snippet) of the winners only.
Three consequences matter in design.
Latency is set by the slowest shard. The coordinator must wait for every shard, so the tail-latency arithmetic applies (see tail latency and overload).
10 shards, each with a p99 of 50 ms
chance a query waits for at least one slow shard: 1 - 0.99^10 = 9.6%
200M documents, 20M per shard: 10 shards, each with 2 replicas
1,000 queries a second x 10 shards = 10,000 shard searches a secondTechniques from that lesson help: hedged requests to a second replica, timeouts that return partial results, and keeping shards small and evenly loaded. Adding shards does not make a single query faster past a point, and it multiplies the work per query. Choose the shard count from the data size and the target shard size, because it is hard to change later.
Scores must be comparable across shards. BM25 uses collection statistics (the number of documents, how many contain each term, the average length). If each shard uses its own, the same term has a different weight in each, and the merged ranking is distorted. The sample puts the collection in four shards by topic, as happens when data is routed by customer or category, and compares the merged top ten with a single index over the same documents.
C# · Totals across all the shards, which is what a ranking function needs to score documents…
using System;
using System.Collections.Generic;
using System.Linq;
// Totals across all the shards, which is what a ranking function needs to score documents the same way everywhere.
public sealed class GlobalStatistics : ICollectionStatistics
{
private readonly IReadOnlyList<InvertedIndex> shards;
public GlobalStatistics(IReadOnlyList<InvertedIndex> shards) { this.shards = shards; }
public int Documents => shards.Sum(s => s.Documents);
public int DocumentFrequency(string term) => shards.Sum(s => s.DocumentFrequency(term));
public double AverageLength => shards.Sum(s => s.AverageLength * s.Documents) / Documents;
}
public static class ScatterGather
{
// Every shard returns its own best k; the coordinator merges them and keeps the best k overall.
public static List<int> Search(IReadOnlyList<InvertedIndex> shards, string query, int k, bool globalStatistics)
{
var global = new GlobalStatistics(shards);
return shards
.SelectMany(shard => Ranking.Search(shard, globalStatistics ? global : shard, query, k, Scoring.Bm25))
.OrderByDescending(r => r.Score).ThenBy(r => r.Doc).Take(k).Select(r => r.Doc).ToList();
}
}C# · The collection from the ranking test, but stored in four shards chosen by topic (as when…
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// The collection from the ranking test, but stored in four shards chosen by topic (as when each customer's data is routed together).
var shardTopics = new List<int>();
var wholeIndex = new InvertedIndex();
var shardIndexes = Enumerable.Range(0, 4).Select(_ => new InvertedIndex()).ToList();
var shardRandom = new Random(2);
var commonWords = Enumerable.Range(0, 200).Select(i => "common" + i).ToArray();
string AnyCommon() => commonWords[(int)(Math.Pow(shardRandom.NextDouble(), 3) * commonWords.Length)];
string AnySignature(int topic) => "topic" + topic + "term" + shardRandom.Next(15);
var docsByShard = Enumerable.Range(0, 4).Select(_ => new List<(int Id, string Text)>()).ToList();
for (int id = 0; id < 1_060; id++)
{
bool spam = id >= 1_000;
int topic = spam ? -1 : shardRandom.Next(20);
string text = spam
? string.Join(" ", Enumerable.Repeat(AnySignature(shardRandom.Next(20)), 40).Concat(Enumerable.Range(0, 300).Select(_ => AnyCommon())))
: string.Join(" ", Enumerable.Range(0, shardRandom.Next(30, 601)).Select(_ => shardRandom.NextDouble() < 0.08 ? AnySignature(topic) : AnyCommon()));
wholeIndex.Add(id, text);
docsByShard[spam ? id % 4 : topic % 4].Add((id, text));
}
for (int s = 0; s < 4; s++) foreach (var (id, text) in docsByShard[s]) shardIndexes[s].Add(id, text);
int differentWithLocal = 0, differentWithGlobal = 0;
var shardQueryRandom = new Random(99);
for (int q = 0; q < 300; q++)
{
int topic = shardQueryRandom.Next(20);
string query = $"topic{topic}term{shardQueryRandom.Next(15)} topic{topic}term{shardQueryRandom.Next(15)} {commonWords[shardQueryRandom.Next(5)]}";
var single = Ranking.Search(wholeIndex, wholeIndex, query, 10, Scoring.Bm25).Select(r => r.Doc).ToList();
if (!ScatterGather.Search(shardIndexes, query, 10, false).SequenceEqual(single)) differentWithLocal++;
if (!ScatterGather.Search(shardIndexes, query, 10, true).SequenceEqual(single)) differentWithGlobal++;
}
Debug.Assert(differentWithLocal > 0 && differentWithGlobal == 0);With each shard's own statistics, 158 of 300 queries returned a different top ten than the single index. With global statistics, summed across the shards before scoring, none did. Elasticsearch offers this as dfs_query_then_fetch: an extra round trip to collect statistics first. Randomly distributed documents make the shards' statistics similar, which is why the problem often goes unnoticed until the data is routed or small.
Deep pagination is expensive. To return results 10,000 to 10,010, every shard must produce and sort its top 10,010 and the coordinator merges 10 times that. This is why Elasticsearch limits from + size to 10,000 by default. For deep or exhaustive reads use a cursor (search_after, with a point-in-time snapshot), and for users, rarely offer page 500: nobody looks.
- Fuzzy matching finds terms within a small edit distance of the query term (one insertion, deletion or substitution). Lucene does it by walking the term dictionary with an automaton, which avoids comparing against every term. An n-gram index (storing every 2- or 3-letter piece of each term) also helps, and phonetic and synonym filters handle sounds and meanings.
- Prefix and autocomplete: index edge n-grams (for "search": s, se, sea, sear, searc, search) so that a prefix is an exact term lookup, or use a dedicated structure; the autocomplete lesson designs this in full.
- Filters and facets: "in stock, under $50, brand Acme" are conditions, not relevance, so engines evaluate them as cached bitsets of matching documents and combine them with the text query. Counts per category (facets) and sorting use doc values, a columnar on-disk copy of each field, because the inverted index is the wrong shape for "give me the value of this field for these documents".
The index is derived data, and the database is the source of truth. Do not make your application write to both: a crash between the two writes leaves them different, and nothing repairs it (the dual-write problem from the distributed transactions lesson). Instead publish changes from the database through an outbox or change data capture (see logs, streams and Kafka), and have an indexer consume them.
- Make indexing idempotent and ordered by version. Index each document under its id with the source row's version, and let the engine reject an older or equal version (Elasticsearch calls this external versioning), so duplicates and reordered messages cannot bring back stale data.
- Handle deletes explicitly, as events, or they linger in results.
- Expect lag. The index trails the database by the pipeline delay plus the refresh interval. For "I just saved this and I want to see it" read your own writes from the database, or wait for a refresh, rather than assuming search is current.
- Reindexing is routine. A new analyzer, a new field type or a new ranking feature needs a full rebuild. Build a new index alongside, keep it in sync, and switch an alias to it when it is ready, with no downtime.
| Situation | What happens | Defence |
|---|---|---|
| Query and document analyzed differently | Obvious matches are not found | One analysis chain, tested on real queries |
| Scores computed from per-shard statistics | The merged ranking is wrong (158 of 300 queries in the test) | Global statistics, or fewer and larger shards |
| One slow shard | The whole query waits (9.6% of queries with 10 shards at p99) | Hedged requests, timeouts and partial results, balanced shards |
| Deep pagination | Memory and CPU on every shard grow with the offset | Cursors (search_after), limits, fewer deep pages |
| Too many small segments | Slow queries | Merge policy, fewer refreshes during bulk load |
| Too many shards | Overhead per shard, slow cluster state | Size shards by data (tens of gigabytes), not by habit |
| Index and database disagree | Missing, stale or deleted items appear | Outbox or CDC with versions, reconciliation job |
| A mapping or analyzer change | Existing documents keep the old behaviour | Reindex into a new index and swap the alias |
| Keyword stuffing and spam | Junk ranks first | Saturation (BM25), quality signals, spam filters |
| No results for a typo | Users leave | Fuzzy matching, spelling suggestions, synonyms |
Interviewer follow-upL5How does full-text search work, and why not use LIKE?How to answer
An inverted index maps each term to the sorted list of documents that contain it, built after analysis (tokenising, lowercasing, stemming). A query reads only the lists of its own terms and intersects or merges them, so its cost does not grow with the whole collection, and the engine can rank the matches. LIKE '%word%' scans every row, cannot use a normal index, and has no notion of relevance.
Interviewer follow-upL5What is BM25, and what does it fix compared with counting term occurrences?How to answer
It scores a document for a query term by the term's frequency in the document, weighted by how rare the term is across the collection (idf), with the frequency saturating so repetition stops helping and normalised for document length. Raw counts favour long documents and common words and reward keyword stuffing. In the sample, BM25 reached an nDCG@10 of 0.998 where raw counts reached 0.308.
Interviewer follow-upL6Design search for an e-commerce site.How to answer
A product database as the source of truth, with changes streamed (outbox or CDC) to an indexer that writes denormalised product documents (title, brand, category, attributes, price, availability, popularity) into a sharded, replicated index. Queries run BM25 with title boosts plus filters and facets, then a rescoring stage using popularity, conversion and freshness. Typo tolerance and synonyms, edge n-grams for autocomplete. Reindex with aliases, track nDCG offline and click-through and zero-result rate online, and keep price and stock authoritative from the database at display time.
Interviewer follow-upL6Search results lag behind writes. Why, and how do you give a user read-your-writes?How to answer
Changes go database, change stream, indexer, then a segment that becomes searchable at the next refresh, so there is pipeline delay plus up to a second of refresh. For the author of a change, read it from the database or the response of the write, or merge it into results on the client, or wait for a refresh before returning. Do not shorten the refresh interval to zero for everyone: it creates many small segments and slows the cluster.
Interviewer follow-upL6How do you keep Elasticsearch consistent with your database?How to answer
Make the database the source of truth and never write both. Publish row changes through an outbox or change data capture, consume them in an indexer that indexes by document id with the row's version so duplicates and old versions are ignored, and send deletes as events. Add a periodic reconciliation that compares counts or checksums and repairs gaps, and reindex through a new index and an alias when the mapping changes.
Interviewer follow-upL6Deep pages are slow. Why, and what do you do?How to answer
To return a page at offset N each shard has to produce and sort its top N plus the page size, and the coordinator merges all of them, so cost grows with the offset and across shards. Cap the depth (Elasticsearch defaults to 10,000), use search_after with a point-in-time for cursor-style paging, and for exports use a scan or the source database. Design the UI to refine rather than page.
Interviewer follow-upL7How would you evaluate and improve search relevance?How to answer
Build a judged set of real queries, from human labels and click logs, and measure MRR and nDCG@k offline for every change, with a no-regression gate in CI. Segment the results by query type (head, tail, navigational, long) so an improvement is not an average that hides a loss. Then A/B test on click-through, reformulations and zero-result rate. Debug by reading failures: missing synonyms, analysis mismatches, wrong boosts. Consider learning-to-rank once there are enough signals.
Interviewer follow-upL7A search cluster slows down as it grows. What do you look at?How to answer
The slowest shard sets query latency, so check for uneven shards (hot ones from routing or skew), too many shards per node, too many segments or merges starving queries, deep pagination, and expensive queries (wildcards, large aggregations). Compare shard-level tail latency, add replicas for throughput, use hedging and partial results, resize shards by data volume rather than by count, and make sure scoring uses global statistics when shards are uneven.
Interviewer follow-upL7How do you combine keyword search with semantic (embedding) search?How to answer
Run both and merge. Keyword search with BM25 is strong for exact terms, identifiers and rare words, and has no training. Embedding (vector) search finds paraphrases and meaning but misses exact strings. A hybrid system retrieves candidates from each, combines the rankings (reciprocal rank fusion is a common, simple method that needs no score calibration) and often reranks the top results with a more expensive model. The inverted index and the vector index are separate structures that can live in the same engine.
When a design needs search, name the pieces: an analysis chain and an inverted index, BM25 plus the signals that matter for the domain, shards and replicas with scatter-gather, and an indexing pipeline from the source of truth through a change stream. Then name the trade-offs: results lag writes by the refresh interval, statistics must be global for comparable scores, deep pages are expensive, and relevance has to be measured with a judged query set rather than judged by eye.
Search is an inverted index plus a scoring function. Analysis turns documents and queries into the same terms; each term has a sorted posting list with frequencies and positions, so AND, OR and phrase queries touch only the lists they need, as the brute-force comparison confirmed. BM25 weights a term by its frequency, its rarity, a saturation curve and the document's length, and beat raw counts and TF-IDF on a collection with spam. Relevance is measured with MRR and nDCG on judged queries and then with online tests. An index is a set of immutable segments, refreshed into view about once a second and merged in the background, so search lags writes and deletes are physical only after a merge. A cluster scatters a query to shards and gathers results, so latency follows the slowest shard, scores need global statistics to be comparable (158 of 300 queries differed without them), and deep pages are costly. The index is derived data, fed from the database through an outbox or change data capture with versions, and rebuilt through an alias swap.
Try answering out loud before you reveal each answer.
QuestionA query for "storage engines" returns nothing, though a document contains "Storage Engine". What is the likely cause?Reveal answer
The query and the document were analysed differently, or the analysis is missing steps: lowercasing and stemming reduce "Storage Engine" to the same terms as "storage engines" only if both sides use the same chain. Check the analyzer on the field and on the query, and test with real queries. A stemmer is what makes "engines" meet "engine".
QuestionTwo documents contain a query term three times. One has 50 words and the other 5,000. How does BM25 rank them, and why?Reveal answer
The short one ranks higher. BM25 normalises term frequency by document length relative to the average, so three occurrences in a short document are stronger evidence the document is about the term than three in a long one. Saturation also stops repeated terms from adding without limit, which blunts keyword stuffing.
QuestionWhy can a sharded search return a different top ten than the same documents in a single index, and how do you fix it?Reveal answer
Each shard scores with its own collection statistics, so the same term has a different idf and the average length differs per shard, and scores from different shards are not comparable when merged. The fix is global statistics: collect document counts, document frequencies and average length from all shards and score with them (Elasticsearch's dfs_query_then_fetch), or use fewer, larger, evenly distributed shards.
QuestionA user edits a product and searches for it a moment later but sees the old version. Name two reasons and one way to give them what they expect.Reveal answer
The change travels from the database through a change stream and an indexer before it is indexed, and it becomes searchable only at the next refresh, so there is pipeline delay plus up to a second of refresh. To give the editor what they expect, read the saved item from the database for them, or wait for the index to catch up before confirming, instead of expecting the search index to be current.
- Christopher Manning, Prabhakar Raghavan and Hinrich Schütze, Introduction to Information Retrieval (opens in a new tab) (free online): inverted indexes, scoring, evaluation and compression.
- Stephen Robertson and Hugo Zaragoza, The Probabilistic Relevance Framework: BM25 and Beyond (Foundations and Trends in Information Retrieval, 2009), and Elastic's Practical BM25 (opens in a new tab): the formula and its parameters.
- Elasticsearch documentation: Near real-time search (opens in a new tab) (refresh and segments) and Paginate search results (opens in a new tab) (
from,sizeandsearch_after). - Sergey Brin and Lawrence Page, The Anatomy of a Large-Scale Hypertextual Web Search Engine (opens in a new tab) (1998): an early description of an inverted-index architecture.
- PostgreSQL documentation, Full Text Search (opens in a new tab):
tsvector, GIN indexes and ranking inside a database. - Martin Kleppmann, Designing Data-Intensive Applications (opens in a new tab): the chapter on storage and retrieval (full-text indexes) and the chapters on keeping derived data in sync.