Knowledge Sprint SeriesMT24 Learning

Phase 13 · Sprint 39/90 · Semantic Search & RetrievalCleverdon · Spärck Jones · Robertson

Keyword Search: Inverted Index & BM25

Search does not read. It counts words, weighs the rare ones and keeps repeats in check.

In short. The inverted index, why rare words weigh more, how BM25 caps repeats and adjusts for length, and how a ranking is scored with nDCG.

Sprint 39 of 90 infographic: Keyword Search: Inverted Index & BM25. Search does not read. It counts words, weighs the rare ones and keeps repeats in check. The full text of the image is on this page.
Full resolution2160 × 2700 PNGPhase summary

The part of the image you are reading lights up. Tap a part to jump to its text.

Fig. 1 in words

1 400 abstracts, 225 questions · Cranfield (1960s) · same data as code 05

  1. 1 Posting lists

    • query 3 · how many abstracts hold
    • of: 1 394 · weight 0.00
    • in: 1 241 · weight 0.12
    • heat: 254 · weight 1.71
    • conduction: 43 · weight 3.47
    • composite: 9 · weight 4.99
    • slabs: 6 · weight 5.37
    • rare word → long weight, short list
  2. 2 Build-up

    • nDCG@10, mean of 225 questions
    • count 0.026 · +rare 0.252 · +cap 0.326 · +length 0.382
    • BM25 = all four steps
  3. 3 Cap the repeats

    • weight of one word vs. its count
    • counting: 10 · BM25, k1 1.2: 1.00 at one mention, 1.96 at ten
    • times the word appears, 0 to 10
    • ten mentions weigh 1.96× one
  4. 4 Same run, 4 ways

    • BM25 nDCG@10, scored by
    • Cleverdon order: 0.382 · 1 = best, −1 set aside
    • 4 = best: 0.307 · the ir_datasets labels
    • all lines relevant: 0.485 · −1 counted, grades ignored
    • matched by .I: 0.010 · scored against the wrong question
    • the number depends on the reading

01 The Inverted Index Index

  • One list per word: the abstracts that hold it, with counts
  • A query reads only its own words’ lists; 7 471 lists cover 1 400 abstracts
  • “the” is in 1 391 abstracts, “flutter” in 56

Manning, Raghavan & Schütze (2008), ch. 1.

02 Rare Words Weigh More IDF

  • Spärck Jones (1972): weight a word by how few documents use it
  • Counting every match: nDCG@10 0.026. Weighting rare words: 0.252
  • “of” and “in” match almost every abstract, so they tell almost nothing

Added first, this step brings 63% of the gain; added last, 26%.

03 BM25: Cap and Scale BM25

  • Repeats saturate: with k1 1.2, ten mentions weigh 1.96× one
  • Long abstracts are scaled down (b 0.75): 0.326 → 0.382
  • Robertson & Zaragoza (2009): 1.2 < k1 < 2 and 0.5 < b < 0.8 work in many settings

Claim tested: “the page that repeats your words most wins.” Counting alone: 0.026.

04 Scoring a Ranking nDCG

  • Cranfield (1960s): paper authors set the questions and graded the papers they cited
  • Grade 1 = a complete answer … 4 = minimum interest (Cleverdon)
  • nDCG@10 (common log2 form) rewards good grades near the top (Järvelin & Kekäläinen 2002)

The paper coded −1, read as each question’s base paper, is set aside: Cleverdon removed base papers.

05 Try It Yourself PYTHON 3.13.17 · NUMPY 2.5.3

sprint39_keyword_search_inverted_index_bm25.py

import re, math, pathlib, collections as C, numpy as np

def blocks(f):                    # each record starts ".I n"
    t = pathlib.Path("cran", f).read_text(encoding="latin-1")
    return [b.split(".W", 1) for b in re.split(r"\n?\.I ", t)[1:]]
tok = lambda s: re.findall(r"[a-z0-9]+", s.lower())
docs = [tok(b[1]) for b in blocks("cran.all.1400")]
qs = [tok(b[1]) for b in blocks("cran.qry")]
rel = C.defaultdict(dict)         # query 1..225 -> {doc: code}
for l in pathlib.Path("cran/cranqrel").read_text().splitlines():
    q, d, r = map(int, l.split()); rel[q][d - 1] = r
post = C.defaultdict(list)        # inverted index: word -> docs
for d, ws in enumerate(docs):
    for w, c in C.Counter(ws).items(): post[w].append((d, c))
post = {w: np.array(p).T for w, p in post.items()}
N, L = len(docs), np.array([len(d) for d in docs])

def bm25(q, idf=True, k1=1.2, b=0.75):
    s = np.zeros(N)
    for w in filter(post.__contains__, q):
        d, c = post[w]; n = len(d)
        c = c / (1 - b + b * L[d] / L.mean())        # length
        s[d] += (math.log(1 + (N - n + .5) / (n + .5)) if idf
                 else 1) * (c * (k1 + 1) / (c + k1) if k1 else c)
    return s
def ndcg(s, j, gain=lambda r: 5 - r, skip_base=True, k=10):
    skip = {d for d, r in j.items() if r == -1 and skip_base}
    top = [d for d in np.argsort(-s, kind="stable")
           if d not in skip][:k]  # Cleverdon: 1 = complete answer
    g = {d: max(gain(r), 0) for d, r in j.items() if d not in skip}
    dcg = sum(g.get(d, 0) / math.log2(i + 2) for i, d in enumerate(top))
    ig = sorted(g.values())[::-1][:k]
    return dcg / sum(v / math.log2(i + 2) for i, v in enumerate(ig))
def mean(J=None, gain=lambda r: 5 - r, skip_base=True, **kw):
    J = J or [rel[i + 1] for i in range(len(qs))]
    return np.mean([ndcg(bm25(q, **kw), j, gain, skip_base) if j
                    else 0 for q, j in zip(qs, J)])

if __name__ == "__main__":
    print(N, "abstracts,", len(post), "words | 'the' in", len(post[
          "the"][0]), "| 'flutter' in", len(post["flutter"][0]))
    print("nDCG@10 count, +rare, +cap, +length:", np.round([mean(idf=0,
          k1=None, b=0), mean(k1=None, b=0), mean(b=0), mean()], 3))
    top1 = [rel[i + 1].get(np.argmax(bm25(q))) for i, q in enumerate(qs)]
    print("code -1 ranked first:", top1.count(-1), "of", len(qs))
    print(f"same run, 4 = best: {mean(gain=lambda r: r, skip_base=0):.3f}"
          f" | all relevant: {mean(gain=lambda r: 1, skip_base=0):.3f}")
    by_I = [rel.get(int(b[0]), {}) for b in blocks("cran.qry")]
    print(f"queries matched by .I number: {mean(by_I):.3f}")
    rare = lambda ws: {w for w in ws if w in post
                       and len(post[w][0]) < N / 10}   # in < 10%
    pairs = [(q, docs[d]) for i, q in enumerate(qs)
             for d, r in rel[i + 1].items() if r > 0]
    print("judged pairs sharing no rare word:", sum(not rare(q) &
          rare(d) for q, d in pairs), "of", len(pairs))

Output, as printed on the image

1400 abstracts, 7471 words | 'the' in 1391 | 'flutter' in 56
nDCG@10 count, +rare, +cap, +length: [0.026 0.252 0.326 0.382]
code -1 ranked first: 92 of 225
same run, 4 = best: 0.307 | all relevant: 0.485
queries matched by .I number: 0.010
judged pairs sharing no rare word: 393 of 1612

Run it. sprint39_keyword_search_inverted_index_bm25.py · versions, data and steps

Check: (0.252 − 0.026) ÷ (0.382 − 0.026) = 0.63 · 10 × 2.2 ÷ 11.2 = 1.96
393 ÷ 1 612 = 0.24

06 General Notes Data

  • Judgments number questions 1–225; the query file’s .I runs to 365. Matched by .I: 0.010
  • One paper per question is coded −1. It reads like the question’s source paper: BM25 ranks it first 92 times
  • ir_datasets labels 4 “complete answer” and −1 “no interest”: the reverse of the readme

Bridge: 393 of 1 612 judged pairs share no rare word (Furnas et al. 1987).

07 Mini Project Hands-on

  • Stem the words (Porter): 4 820 words, nDCG@10 0.409
  • Sweep k1 0.5–2 and b 0–1: the best cell (k1 2.0, b 0.75) gives 0.390
  • Pick k1 and b on half the questions, score the other half (Sprint 20)

Tuning on all 225 questions grades your own exam.

R Trusted Sources

  1. Cleverdon, Mills & Keen (1966) ASLIB Cranfield Research Project, vol. 1
  2. Spärck Jones (1972) J. Doc. 28(1), 11–21
  3. Robertson & Walker (1994) SIGIR, 232–241
  4. Robertson & Zaragoza (2009) FnTIR 3(4), 333–389
  5. Järvelin & Kekäläinen (2002) ACM TOIS 20(4), 422–446
  6. Manning, Raghavan & Schütze (2008) Introduction to Information Retrieval, CUP
  7. Furnas, Landauer, Gomez & Dumais (1987) CACM 30(11), 964–971
  8. Glasgow IR group, Cranfield collection and cranqrel.readme · ir_datasets, cranfield

Cite this phase

Tahri, M. (2026). MT24 Learning — Knowledge Sprint Series, Phase 13: Semantic Search & Retrieval (Version 1.0) [Educational resource]. Zenodo. https://doi.org/10.5281/zenodo.24012904

Version DOI 10.5281/zenodo.24012904 · all versions 10.5281/zenodo.24012903 · first published 27 October 2026