AlgoViz

Indexing in distributed search

medium 28 min

How documents become a searchable index spread over many machines: the analysis chain, posting lists and their compression, segments and merges, and the choice between splitting by document or by term.

An index with segments, deletes, compression and shards

Read it, run it, change a line and run it again.

Loading editor…

Small on purpose. The stemmer is a toy that handles only a few safe endings.

The same in TypeScript
// Builder and router. Use a tested analyzer in place of analyze().interface Posting { docId: string; tf: number; positions: number[] }interface Entry { df: number; postings: Map<string, Posting> }const STOP = new Set(["the", "a", "an", "is", "are", "to", "of", "in", "for", "on", "with"]);export function analyze(text: string): { term: string; position: number; start: number; end: number }[] {  let position = -1;  return [...text.toLowerCase().matchAll(/[a-z0-9]+/g)].flatMap((m) => {    position++;                                            // also for removed words    if (STOP.has(m[0])) return [];    return [{ term: m[0], position, start: m.index!, end: m.index! + m[0].length }];  });}export class IndexShard {  private index = new Map<string, Entry>();  private docs = new Map<string, string>();  put(id: string, text: string) {    this.remove(id);                                       // or it would be counted twice    this.docs.set(id, text);    const byTerm = new Map<string, number[]>();    for (const t of analyze(text)) byTerm.set(t.term, [...(byTerm.get(t.term) ?? []), t.position]);    for (const [term, positions] of byTerm) {      const e = this.index.get(term) ?? { df: 0, postings: new Map() };      e.df++;      e.postings.set(id, { docId: id, tf: positions.length, positions });      this.index.set(term, e);    }  }  remove(id: string) {    const old = this.docs.get(id);    if (old === undefined) return;    for (const term of new Set(analyze(old).map((t) => t.term))) {      const e = this.index.get(term)!;      e.df--;      e.postings.delete(id);      if (!e.df) this.index.delete(term);    }    this.docs.delete(id);  }  tfIdf(term: string, id: string) {    const e = this.index.get(term);    const p = e?.postings.get(id);    return p ? Math.log(1 + p.tf) * Math.log(this.docs.size / e!.df) : 0;  }}export function shardFor(id: string, n: number) {  let h = 0;  for (const c of id) h = (h * 31 + c.codePointAt(0)!) >>> 0;   // unsigned, so never negative  return h % n;}
The same in Java
// Postings and routing in Java.record Posting(String docId, int tf, List<Integer> positions) {}final class IndexShard {  private final Map<String, Map<String, Posting>> index = new HashMap<>();   // term -> doc -> posting  private final Map<String, Set<String>> termsOf = new HashMap<>();  synchronized void put(String id, List<String> terms) {      // terms after analysis, null = removed word    remove(id);    Map<String, List<Integer>> at = new HashMap<>();    for (int i = 0; i < terms.size(); i++)      if (terms.get(i) != null) at.computeIfAbsent(terms.get(i), k -> new ArrayList<>()).add(i);    at.forEach((t, p) -> index.computeIfAbsent(t, k -> new HashMap<>()).put(id, new Posting(id, p.size(), p)));    termsOf.put(id, Set.copyOf(at.keySet()));  }  synchronized void remove(String id) {    Set<String> terms = termsOf.remove(id);    if (terms != null) for (String t : terms) index.get(t).remove(id);  }  synchronized double tfIdf(String term, String id) {    var list = index.getOrDefault(term, Map.of());    var p = list.get(id);    return p == null ? 0 : Math.log(1 + p.tf()) * Math.log((double) termsOf.size() / list.size());  }  static int shardFor(String id, int n) { return Math.floorMod(id.hashCode(), n); }}