TExcelTAD
Home › NLP, Transformers & LLM Fine-Tuning › Similarity and Keyword Search: Cosine, Jaccard and BM25

Similarity and Keyword Search: Cosine, Jaccard and BM25

A help centre has a few dozen articles, a shop has a million product descriptions, a company wiki has every document anyone ever wrote. A user types a few words and expects the right page at the top. Before anything is generated, a retrieval-augmented LLM has to solve the same problem: find the passages that answer the question (Building a RAG Pipeline). The classical answer is keyword search: represent query and documents by their terms, score each document by how well its terms match the query's, return the best. It needs no training, runs in milliseconds over millions of documents thanks to an inverted index, and, in the form of BM25, is still the baseline that neural retrievers are measured against.

This lesson builds an inverted index, scores documents with Jaccard similarity, TF-IDF cosine similarity and BM25 written from scratch, and evaluates them on the TAD Bikes help centre, a small corpus of 16 articles with 12 test queries that the later lessons on dense retrieval and RAG evaluation reuse. The numbers here become their keyword baseline.

The corpus and the queries

Each query has exactly one relevant document, chosen by hand. Some queries use the article's own words ("the lock will not open"), others paraphrase ("my bike has a flat tyre" for the article about reporting a damaged bike, "what happens if my bike is stolen" for the one about a lost bike). That mix is realistic: users do not know the help centre's wording.

python
docs = [
    "Rentals are charged per hour. The first 30 minutes cost 2 euros and every extra hour costs 3 euros.",
    "A day pass costs 15 euros and covers unlimited rides for 24 hours from the first unlock.",
    "To unlock a bike, scan the QR code on the handlebar with the app and wait for the green light.",
    "If the lock does not open, check that Bluetooth is on and move closer to the bike, then try again.",
    "Return the bike at any station. Push it into a free dock until the light turns green and you hear a beep.",
    "If a station is full, the app shows the nearest station with free docks and adds 15 free minutes.",
    "Report a damaged bike in the app under Help, Report a problem, and add a photo of the damage.",
    "Electric bikes have a range of about 60 km. The battery level is shown on the display and in the app.",
    "Children under 14 may not rent bikes. Riders between 14 and 18 need permission from a parent.",
    "Helmets are not included in the rental, but we recommend wearing one on every ride.",
    "You can pay with a credit card, a debit card or the app wallet. Cash is not accepted.",
    "Refunds for a ride that was charged twice are sent to the original card within five working days.",
    "A lost bike must be reported within 24 hours. If it is not found, a fee of 400 euros is charged.",
    "Our support team answers chat messages every day from 7 am to 10 pm.",
    "Students get 30 percent off the monthly pass with a valid student card uploaded in the app.",
    "Bikes can be reserved for up to 10 minutes before unlocking. A reservation is free.",
]
queries = [  # (query, id of the relevant document)
    ("how much does one hour cost", 0), ("price for a whole day", 1), ("the lock will not open", 3),
    ("where do I leave the bike when the dock is full", 5), ("my bike has a flat tyre", 6),
    ("how far can an e-bike go", 7), ("can my 12 year old rent a bike", 8), ("do you take cash", 10),
    ("I was charged twice", 11), ("what happens if my bike is stolen", 12), ("discount for students", 14),
    ("can I hold a bike for later", 15),
]

Every runnable example below starts with this same block (the code is repeated so that each example runs on its own).

Measuring retrieval

With one relevant document per query, two metrics cover what matters. Recall@k is the fraction of queries whose relevant document is among the top kk results; recall@1 asks "is the first answer right?", recall@3 "is the answer on the first screen?". The mean reciprocal rank averages the inverse of the relevant document's rank rqr_q over the ∣Q∣|Q| queries:

recall@k=1∣Q∣∑q∈Q[ rq≤k ],MRR=1∣Q∣∑q∈Q1rq.\text{recall@}k = \frac{1}{|Q|} \sum_{q \in Q} [\, r_q \le k \,], \qquad \text{MRR} = \frac{1}{|Q|} \sum_{q \in Q} \frac{1}{r_q} .

A relevant document at rank 1 contributes 1 to the MRR, at rank 2 one half, at rank 10 a tenth, so MRR rewards getting the answer near the top and barely distinguishes "rank 8" from "rank 16". With 12 queries, every query is worth 1/12≈0.0831/12 \approx 0.083 of recall: treat differences of one query as noise. Evaluating Retrieval and RAG adds metrics for several relevant documents (precision@k, nDCG).

The inverted index, Jaccard and TF-IDF cosine

Scoring every document for every query is fine for 16 articles and hopeless for 16 million. Search engines store an inverted index: for each term, the sorted list of documents that contain it (its postings list). A query only touches the lists of its own terms, and only documents on at least one of those lists can get a non-zero score.

termpostings: ids of the documents containing the term bike 2 3 4 6 7 8 12 15 dock 4 5 full 5 leav (no document) cash 10 app 2 5 6 7 10 14 query: where do I leave the bikewhen the dock is full union of the query terms' lists2 3 4 5 6 7 8 12 15 score only these 9 of 16 docsbest: doc 5 (dock + full) green: terms of the query (stemmed); grey: other terms

All methods in this lesson share one analyser, the same idea as a search engine's: lowercase, words of at least two characters, a short list of 33 function words removed, then Porter stemming (Stemming and Lemmatisation), so that "docks" matches "dock". It was fixed before looking at the scores; the ablation at the end shows what other choices do.

Two similarity measures need nothing beyond the term sets and the TF-IDF vectors:

J(A,B)=∣A∩B∣∣A∪B∣,cos⁡(q,d)=q⋅d∥q∥ ∥d∥.J(A, B) = \frac{|A \cap B|}{|A \cup B|}, \qquad \cos(\mathbf{q}, \mathbf{d}) = \frac{\mathbf{q} \cdot \mathbf{d}}{\lVert \mathbf{q} \rVert \, \lVert \mathbf{d} \rVert} .

Jaccard similarity compares the sets of terms: every shared term counts the same, whether it is "bike" (in half the articles) or "cash" (in one). Cosine similarity of TF-IDF vectors weights shared terms by their idf, so rare terms dominate.

python · try it yourself
docs = [
    "Rentals are charged per hour. The first 30 minutes cost 2 euros and every extra hour costs 3 euros.",
    "A day pass costs 15 euros and covers unlimited rides for 24 hours from the first unlock.",
    "To unlock a bike, scan the QR code on the handlebar with the app and wait for the green light.",
    "If the lock does not open, check that Bluetooth is on and move closer to the bike, then try again.",
    "Return the bike at any station. Push it into a free dock until the light turns green and you hear a beep.",
    "If a station is full, the app shows the nearest station with free docks and adds 15 free minutes.",
    "Report a damaged bike in the app under Help, Report a problem, and add a photo of the damage.",
    "Electric bikes have a range of about 60 km. The battery level is shown on the display and in the app.",
    "Children under 14 may not rent bikes. Riders between 14 and 18 need permission from a parent.",
    "Helmets are not included in the rental, but we recommend wearing one on every ride.",
    "You can pay with a credit card, a debit card or the app wallet. Cash is not accepted.",
    "Refunds for a ride that was charged twice are sent to the original card within five working days.",
    "A lost bike must be reported within 24 hours. If it is not found, a fee of 400 euros is charged.",
    "Our support team answers chat messages every day from 7 am to 10 pm.",
    "Students get 30 percent off the monthly pass with a valid student card uploaded in the app.",
    "Bikes can be reserved for up to 10 minutes before unlocking. A reservation is free.",
]
queries = [  # (query, id of the relevant document)
    ("how much does one hour cost", 0), ("price for a whole day", 1), ("the lock will not open", 3),
    ("where do I leave the bike when the dock is full", 5), ("my bike has a flat tyre", 6),
    ("how far can an e-bike go", 7), ("can my 12 year old rent a bike", 8), ("do you take cash", 10),
    ("I was charged twice", 11), ("what happens if my bike is stolen", 12), ("discount for students", 14),
    ("can I hold a bike for later", 15),
]
import re
import numpy as np
from collections import defaultdict
from nltk.stem import PorterStemmer
from sklearn.feature_extraction.text import TfidfVectorizer

STOP = set("a an and are as at be but by for if in into is it no not of on or such that the their "
           "then there these they this to was will with".split())            # a short search-style list
stem = PorterStemmer().stem
def analyze(s):                     # lowercase, words of 2+ characters, stop words out, Porter stems
    return [stem(w) for w in re.findall(r"\b\w\w+\b", s.lower()) if w not in STOP]

index = defaultdict(set)            # inverted index: term -> ids of the documents containing it
for i, d in enumerate(docs):
    for t in analyze(d):
        index[t].add(i)
print("terms:", len(index))
for t in ["bike", "dock", "full", "leav", "cash", "app"]:
    print(f"  {t!r:7} -> {sorted(index[t])}")
q = "where do I leave the bike when the dock is full"
cand = sorted(set().union(*(index[t] for t in analyze(q))))
print(f"{q!r} -> {analyze(q)} -> candidates {cand}")

def evaluate(score_fn, name):
    ranks = []
    for q, rel in queries:
        s = score_fn(q)
        order = sorted(range(len(docs)), key=lambda i: (-s[i], i))   # ties: lower id first
        ranks.append(order.index(rel) + 1)
    ranks = np.array(ranks)
    print(f"{name:14} recall@1 {np.mean(ranks <= 1):.3f}  recall@3 {np.mean(ranks <= 3):.3f}  "
          f"MRR {np.mean(1 / ranks):.3f}  ranks {ranks.tolist()}")

D_sets = [set(analyze(d)) for d in docs]
def jaccard(q):
    qs = set(analyze(q))
    return [len(qs & d) / len(qs | d) for d in D_sets]

vec = TfidfVectorizer(analyzer=analyze).fit(docs)
D = vec.transform(docs)
def tfidf_cosine(q):
    return (D @ vec.transform([q]).T).toarray().ravel()   # rows are l2-normalised: dot = cosine

evaluate(jaccard, "Jaccard")
evaluate(tfidf_cosine, "TF-IDF cosine")
terms: 124
  'bike'  -> [2, 3, 4, 6, 7, 8, 12, 15]
  'dock'  -> [4, 5]
  'full'  -> [5]
  'leav'  -> []
  'cash'  -> [10]
  'app'   -> [2, 5, 6, 7, 10, 14]
'where do I leave the bike when the dock is full' -> ['where', 'do', 'leav', 'bike', 'when', 'dock', 'full'] -> candidates [2, 3, 4, 5, 6, 7, 8, 12, 15]
Jaccard        recall@1 0.667  recall@3 0.833  MRR 0.764  ranks [1, 3, 1, 1, 1, 6, 2, 1, 1, 6, 1, 1]
TF-IDF cosine  recall@1 0.667  recall@3 0.833  MRR 0.762  ranks [1, 2, 1, 1, 7, 6, 1, 1, 1, 3, 1, 1]

The index has 124 terms. "bike" is in 8 of the 16 articles (stemming merged "bikes" into it), "dock" in 2, "full" and "cash" in one each, and the stem "leav" in none. The query about a full dock touches 9 candidate documents, so the other 7 are never scored; on a real collection the candidates are a tiny fraction of the index.

Both measures get 8 of the 12 queries right at rank 1 (recall@1 0.667) and 10 in the top 3 (recall@3 0.833). The rank lists show where they fail: query 2 ("price for a whole day": the article says "day pass costs"), query 5 ("flat tyre"), query 6 ("e-bike", "go far": the article says "electric bikes", "range") and query 10 ("stolen": the article says "lost"). TF-IDF puts the "flat tyre" article at rank 7 because its only shared term is "bike", which occurs in half of the articles and so has a low idf.

BM25

TF-IDF has two weaknesses for search. Term frequency grows without limit: an article that says "bike" five times is not five times as relevant as one that says it once. And length normalisation by the l2 norm is a fixed choice that cannot be tuned. BM25 (Best Matching 25, from Robertson and colleagues' Okapi system in the 1990s) fixes both. For a query QQ and a document DD of length ∣D∣|D| terms, with f(t,D)f(t, D) the count of term tt in DD and avgdl\text{avgdl} the average document length:

score⁡(D,Q)=∑t∈Qidf⁡(t)⋅f(t,D) (k1+1)f(t,D)+k1(1−b+b ∣D∣avgdl),idf⁡(t)=ln⁡ ⁣(1+N−n(t)+0.5n(t)+0.5)\operatorname{score}(D, Q) = \sum_{t \in Q} \operatorname{idf}(t) \cdot \frac{f(t, D)\,(k_1 + 1)}{f(t, D) + k_1 \left(1 - b + b \, \dfrac{|D|}{\text{avgdl}}\right)}, \qquad \operatorname{idf}(t) = \ln\!\left(1 + \frac{N - n(t) + 0.5}{n(t) + 0.5}\right)

where NN is the number of documents and n(t)n(t) the number containing tt. The two parameters:

  • k1k_1 controls term-frequency saturation. For b=0b = 0 the fraction is f(k1+1)/(f+k1)f (k_1 + 1) / (f + k_1): 1 for f=1f = 1, approaching k1+1k_1 + 1 as ff grows. With k1=1.5k_1 = 1.5, one occurrence gives 1, two give 1.43, ten give 2.17, a hundred 2.46. k1=0k_1 = 0 ignores frequency entirely (presence only).
  • b∈[0,1]b \in [0, 1] controls length normalisation. With b=1b = 1 a term in a document twice the average length counts like half an occurrence; with b=0b = 0 length is ignored.

The usual defaults are k1k_1 between 1.2 and 2 and b=0.75b = 0.75 (Lucene and Elasticsearch use k1=1.2k_1 = 1.2, b=0.75b = 0.75). The idf above is the variant used by Lucene and Elasticsearch: the original Robertson-Spärck Jones form ln⁡N−n+0.5n+0.5\ln \frac{N - n + 0.5}{n + 0.5} becomes negative for terms in more than half the documents, and adding 1 inside the logarithm keeps it positive.

python · try it yourself
docs = [
    "Rentals are charged per hour. The first 30 minutes cost 2 euros and every extra hour costs 3 euros.",
    "A day pass costs 15 euros and covers unlimited rides for 24 hours from the first unlock.",
    "To unlock a bike, scan the QR code on the handlebar with the app and wait for the green light.",
    "If the lock does not open, check that Bluetooth is on and move closer to the bike, then try again.",
    "Return the bike at any station. Push it into a free dock until the light turns green and you hear a beep.",
    "If a station is full, the app shows the nearest station with free docks and adds 15 free minutes.",
    "Report a damaged bike in the app under Help, Report a problem, and add a photo of the damage.",
    "Electric bikes have a range of about 60 km. The battery level is shown on the display and in the app.",
    "Children under 14 may not rent bikes. Riders between 14 and 18 need permission from a parent.",
    "Helmets are not included in the rental, but we recommend wearing one on every ride.",
    "You can pay with a credit card, a debit card or the app wallet. Cash is not accepted.",
    "Refunds for a ride that was charged twice are sent to the original card within five working days.",
    "A lost bike must be reported within 24 hours. If it is not found, a fee of 400 euros is charged.",
    "Our support team answers chat messages every day from 7 am to 10 pm.",
    "Students get 30 percent off the monthly pass with a valid student card uploaded in the app.",
    "Bikes can be reserved for up to 10 minutes before unlocking. A reservation is free.",
]
queries = [  # (query, id of the relevant document)
    ("how much does one hour cost", 0), ("price for a whole day", 1), ("the lock will not open", 3),
    ("where do I leave the bike when the dock is full", 5), ("my bike has a flat tyre", 6),
    ("how far can an e-bike go", 7), ("can my 12 year old rent a bike", 8), ("do you take cash", 10),
    ("I was charged twice", 11), ("what happens if my bike is stolen", 12), ("discount for students", 14),
    ("can I hold a bike for later", 15),
]
import re
import numpy as np
from collections import Counter
from nltk.stem import PorterStemmer

STOP = set("a an and are as at be but by for if in into is it no not of on or such that the their "
           "then there these they this to was will with".split())
stem = PorterStemmer().stem
def analyze(s):
    return [stem(w) for w in re.findall(r"\b\w\w+\b", s.lower()) if w not in STOP]

class BM25:
    def __init__(self, docs, k1=1.5, b=0.75):
        self.k1, self.b = k1, b
        self.tf = [Counter(analyze(d)) for d in docs]
        self.len = np.array([sum(c.values()) for c in self.tf])
        self.avgdl = self.len.mean()
        N, df = len(docs), Counter(t for c in self.tf for t in c)
        self.idf = {t: np.log(1 + (N - n + 0.5) / (n + 0.5)) for t, n in df.items()}

    def scores(self, query):
        s = np.zeros(len(self.tf))
        norm = self.k1 * (1 - self.b + self.b * self.len / self.avgdl)
        for t in analyze(query):
            if t not in self.idf:
                continue                                    # unknown term: contributes nothing
            f = np.array([c[t] for c in self.tf])
            s += self.idf[t] * f * (self.k1 + 1) / (f + norm)
        return s

def evaluate(score_fn, name):
    ranks = []
    for q, rel in queries:
        s = score_fn(q)
        ranks.append(sorted(range(len(docs)), key=lambda i: (-s[i], i)).index(rel) + 1)
    ranks = np.array(ranks)
    print(f"{name:20} recall@1 {np.mean(ranks <= 1):.3f}  recall@3 {np.mean(ranks <= 3):.3f}  "
          f"MRR {np.mean(1 / ranks):.3f}  ranks {ranks.tolist()}")

bm = BM25(docs)
print(f"avgdl {bm.avgdl:.2f} | idf: bike {bm.idf['bike']:.3f}, app {bm.idf['app']:.3f}, cash {bm.idf['cash']:.3f}")
evaluate(bm.scores, "BM25 k1=1.5 b=0.75")
for k1, b in [(1.2, 0.75), (0.5, 0.75), (3.0, 0.75), (1.5, 0.0), (1.5, 1.0)]:
    evaluate(BM25(docs, k1, b).scores, f"BM25 k1={k1} b={b}")
avgdl 11.69 | idf: bike 0.693, app 0.961, cash 2.428
BM25 k1=1.5 b=0.75   recall@1 0.667  recall@3 0.750  MRR 0.743  ranks [1, 3, 1, 1, 4, 6, 1, 1, 1, 6, 1, 1]
BM25 k1=1.2 b=0.75   recall@1 0.667  recall@3 0.750  MRR 0.743  ranks [1, 3, 1, 1, 4, 6, 1, 1, 1, 6, 1, 1]
BM25 k1=0.5 b=0.75   recall@1 0.667  recall@3 0.750  MRR 0.743  ranks [1, 3, 1, 1, 4, 6, 1, 1, 1, 6, 1, 1]
BM25 k1=3.0 b=0.75   recall@1 0.583  recall@3 0.750  MRR 0.701  ranks [1, 3, 1, 1, 4, 6, 2, 1, 1, 6, 1, 1]
BM25 k1=1.5 b=0.0    recall@1 0.750  recall@3 0.750  MRR 0.795  ranks [1, 1, 1, 1, 4, 7, 1, 1, 1, 7, 1, 1]
BM25 k1=1.5 b=1.0    recall@1 0.583  recall@3 0.750  MRR 0.701  ranks [1, 3, 1, 1, 4, 6, 2, 1, 1, 6, 1, 1]

The idf values follow the formula: "bike" is in n=8n = 8 of N=16N = 16 documents, so ln⁡(1+8.5/8.5)=ln⁡2≈0.693\ln(1 + 8.5/8.5) = \ln 2 \approx 0.693; "cash" is in one, ln⁡(1+15.5/1.5)≈2.428\ln(1 + 15.5/1.5) \approx 2.428. With the defaults, BM25 gets the same 8 queries right at rank 1 as TF-IDF cosine (recall@1 0.667), but only 9 in the top 3 (recall@3 0.750, MRR 0.743): it ranks "price for a whole day" third instead of second and "stolen" sixth instead of third, while it moves "flat tyre" up from seventh to fourth. Changing k1k_1 between 0.5 and 1.5 changes nothing. b=0b = 0 is best on these queries (recall@1 0.750), but choosing it because of that would be tuning on the test set; with 12 queries the difference is a single query.

The keyword baseline for the later lessons, on the 16 articles and 12 queries with this analyser:

Method recall@1 recall@3 MRR
TF-IDF cosine 0.667 0.833 0.762
BM25 (k1=1.5k_1 = 1.5, b=0.75b = 0.75) 0.667 0.750 0.743

On 16 short articles, BM25's advantages hardly matter: few terms repeat within an article and the lengths are similar (11.69 terms on average). On real collections, with long documents and repeated terms, BM25 is consistently ahead of plain TF-IDF and is the standard first-stage retriever in search engines and in many RAG systems.

Failure cases: vocabulary mismatch

The last example compares analysers, then looks at three queries that every variant misses.

python · try it yourself
docs = [
    "Rentals are charged per hour. The first 30 minutes cost 2 euros and every extra hour costs 3 euros.",
    "A day pass costs 15 euros and covers unlimited rides for 24 hours from the first unlock.",
    "To unlock a bike, scan the QR code on the handlebar with the app and wait for the green light.",
    "If the lock does not open, check that Bluetooth is on and move closer to the bike, then try again.",
    "Return the bike at any station. Push it into a free dock until the light turns green and you hear a beep.",
    "If a station is full, the app shows the nearest station with free docks and adds 15 free minutes.",
    "Report a damaged bike in the app under Help, Report a problem, and add a photo of the damage.",
    "Electric bikes have a range of about 60 km. The battery level is shown on the display and in the app.",
    "Children under 14 may not rent bikes. Riders between 14 and 18 need permission from a parent.",
    "Helmets are not included in the rental, but we recommend wearing one on every ride.",
    "You can pay with a credit card, a debit card or the app wallet. Cash is not accepted.",
    "Refunds for a ride that was charged twice are sent to the original card within five working days.",
    "A lost bike must be reported within 24 hours. If it is not found, a fee of 400 euros is charged.",
    "Our support team answers chat messages every day from 7 am to 10 pm.",
    "Students get 30 percent off the monthly pass with a valid student card uploaded in the app.",
    "Bikes can be reserved for up to 10 minutes before unlocking. A reservation is free.",
]
queries = [  # (query, id of the relevant document)
    ("how much does one hour cost", 0), ("price for a whole day", 1), ("the lock will not open", 3),
    ("where do I leave the bike when the dock is full", 5), ("my bike has a flat tyre", 6),
    ("how far can an e-bike go", 7), ("can my 12 year old rent a bike", 8), ("do you take cash", 10),
    ("I was charged twice", 11), ("what happens if my bike is stolen", 12), ("discount for students", 14),
    ("can I hold a bike for later", 15),
]
import re
import numpy as np
from collections import Counter
from nltk.stem import PorterStemmer
from sklearn.feature_extraction.text import TfidfVectorizer, ENGLISH_STOP_WORDS

SHORT = set("a an and are as at be but by for if in into is it no not of on or such that the their "
            "then there these they this to was will with".split())
stem = PorterStemmer().stem
def make_analyzer(stop, use_stem):
    def analyze(s):
        ws = [w for w in re.findall(r"\b\w\w+\b", s.lower()) if w not in stop]
        return [stem(w) for w in ws] if use_stem else ws
    return analyze

def bm25(analyze, k1=1.5, b=0.75):
    tf = [Counter(analyze(d)) for d in docs]
    L = np.array([sum(c.values()) for c in tf]); N = len(docs)
    def score(q):
        s = np.zeros(N)
        for t in analyze(q):
            f = np.array([c[t] for c in tf]); n = int((f > 0).sum())
            if n:
                s += np.log(1 + (N - n + 0.5) / (n + 0.5)) * f * (k1 + 1) / (f + k1 * (1 - b + b * L / L.mean()))
        return s
    return score

def tfidf(analyze):
    vec = TfidfVectorizer(analyzer=analyze).fit(docs); D = vec.transform(docs)
    return lambda q: (D @ vec.transform([q]).T).toarray().ravel()

def metrics(score):
    r = np.array([sorted(range(len(docs)), key=lambda i: (-score(q)[i], i)).index(rel) + 1 for q, rel in queries])
    return f"R@1 {np.mean(r <= 1):.3f} R@3 {np.mean(r <= 3):.3f} MRR {np.mean(1 / r):.3f}"

for label, stop, st in [("no stop words, no stemming", set(), False), ("short stop list, no stemming", SHORT, False),
                        ("short stop list + Porter", SHORT, True), ("sklearn's 318 stop words + Porter", ENGLISH_STOP_WORDS, True)]:
    a = make_analyzer(stop, st)
    print(f"{label:34} TF-IDF {metrics(tfidf(a))} | BM25 {metrics(bm25(a))}")
print("'full' is an sklearn stop word:", "full" in ENGLISH_STOP_WORDS)

a = make_analyzer(SHORT, True); score = bm25(a)
for i in (4, 5, 9):
    q, rel = queries[i]
    s = score(q)
    order = sorted(range(len(docs)), key=lambda j: (-s[j], j))
    print(f"{q!r}: terms {a(q)}, relevant doc {rel} shares {sorted(set(a(q)) & set(a(docs[rel])))}, "
          f"rank {order.index(rel) + 1}, top doc {order[0]}")
no stop words, no stemming         TF-IDF R@1 0.833 R@3 0.917 MRR 0.883 | BM25 R@1 0.917 R@3 0.917 MRR 0.924
short stop list, no stemming       TF-IDF R@1 0.583 R@3 0.833 MRR 0.723 | BM25 R@1 0.583 R@3 0.833 MRR 0.723
short stop list + Porter           TF-IDF R@1 0.667 R@3 0.833 MRR 0.762 | BM25 R@1 0.667 R@3 0.750 MRR 0.743
sklearn's 318 stop words + Porter  TF-IDF R@1 0.583 R@3 0.833 MRR 0.722 | BM25 R@1 0.583 R@3 0.833 MRR 0.711
'full' is an sklearn stop word: True
'my bike has a flat tyre': terms ['my', 'bike', 'ha', 'flat', 'tyre'], relevant doc 6 shares ['bike'], rank 4, top doc 2
'how far can an e-bike go': terms ['how', 'far', 'can', 'bike', 'go'], relevant doc 7 shares ['bike'], rank 6, top doc 15
'what happens if my bike is stolen': terms ['what', 'happen', 'my', 'bike', 'stolen'], relevant doc 12 shares ['bike'], rank 6, top doc 2

The ablation has a lesson about small benchmarks. The best row is the one with no stop words and no stemming (BM25 recall@1 0.917), but for the wrong reasons: there, "what happens if my bike is stolen" finds the lost-bike article through "if", "is" and "bike" ("If it is not found"), and "can I hold a bike for later" finds the reservation article through "can" and "for" ("Bikes can be reserved for..."). Function words that happen to match are luck, not understanding, and on another set of queries the luck runs the other way. Stemming helps once stop words are gone (0.583 to 0.667 recall@1), and scikit-learn's longer stop list hurts again: it removes "full", so the full-dock query loses its most specific term.

The three failures printed at the end share one cause, vocabulary mismatch. "my bike has a flat tyre" and the damaged-bike article share only "bike"; "flat" and "tyre" never occur in the corpus, and nothing tells keyword search that a flat tyre is a kind of damage. "how far can an e-bike go" needs "far" to match "range" and "e-bike" to match "electric bike". "stolen" needs to match "lost". In each case the relevant document shares only "bike", a term in half of the articles, and lands at rank 4 or 6, behind other articles that share "bike" too or match an uninformative word such as "can". Keyword search can be patched (synonym lists, query expansion, stemming), but every patch is manual and language-specific.

Dense retrieval attacks the problem at the root: encode queries and documents as vectors with a model trained so that texts with similar meaning are close, whatever words they use. Dense Retrieval and Semantic Similarity runs the same 12 queries with sentence embeddings and compares with the table above. In practice the two are complementary: keyword search is exact on names, codes and rare terms ("QR", "Bluetooth", an error code) where embeddings can be vague, which is why production systems often combine both (hybrid search).

Pitfalls

  • Different analysers for index and query. Both sides must be lowercased, filtered and stemmed identically, or nothing matches.
  • Generic stop-word lists. They can remove the one informative term of a query ("full", "not"); search engines today often keep stop words and let idf handle them.
  • Tuning on the test queries. k1k_1, bb and the analyser should be chosen on a separate set of queries; with a dozen queries, any choice that "wins" by one query is noise.
  • Judging BM25 on tiny, uniform collections. Its saturation and length normalisation matter on long and varied documents; small demos understate it.
  • Comparing scores across queries. BM25 scores are not probabilities and depend on the query's terms; a threshold like "score > 5 means relevant" does not transfer.
  • Forgetting the index when documents change. The idf statistics and avgdl must be updated (search engines do it incrementally).

Practice

  1. Compute recall@1, recall@3 and MRR for the rank list [1, 2, 1, 5].
  2. A query term occurs once in a document whose length equals avgdl. Show that its BM25 contribution equals its idf, whatever k1k_1 and bb are.
  3. With k1=1.5k_1 = 1.5 and b=0b = 0, what is the term-frequency factor for f=3f = 3? What is its maximum as ff grows?
  4. Why does the Lucene idf add 1 inside the logarithm? Compute both versions for a term in 12 of 16 documents.
  5. Suggest two changes to the analyser that would rescue "how far can an e-bike go", and say why neither generalises well.
Answers
  1. Ranks ≤1\le 1: two of four, recall@1 =0.5= 0.5. Ranks ≤3\le 3: three of four, recall@3 =0.75= 0.75. MRR =(1+1/2+1+1/5)/4=2.7/4=0.675= (1 + 1/2 + 1 + 1/5)/4 = 2.7/4 = 0.675.
  2. With ∣D∣=avgdl|D| = \text{avgdl} the denominator is f+k1(1−b+b)=f+k1f + k_1(1 - b + b) = f + k_1; for f=1f = 1 the fraction is (k1+1)/(1+k1)=1(k_1 + 1)/(1 + k_1) = 1, so the contribution is idf⁡(t)⋅1\operatorname{idf}(t) \cdot 1.
  3. 3×2.5/(3+1.5)=7.5/4.5≈1.6673 \times 2.5 / (3 + 1.5) = 7.5/4.5 \approx 1.667. As f→∞f \to \infty the factor tends to k1+1=2.5k_1 + 1 = 2.5.
  4. The original ln⁡N−n+0.5n+0.5\ln \frac{N - n + 0.5}{n + 0.5} is negative when n>N/2n > N/2, so a common query term would lower the score of documents that contain it. For n=12n = 12, N=16N = 16: original ln⁡(4.5/12.5)≈−1.022\ln(4.5/12.5) \approx -1.022; Lucene's ln⁡(1+4.5/12.5)=ln⁡1.36≈0.307\ln(1 + 4.5/12.5) = \ln 1.36 \approx 0.307.
  5. Split hyphenated words ("e-bike" to "e" and "bike", or map "e-bike" to "electric bike") and add a synonym list ("far" to "range", "distance"). Both are hand-written for this domain and language, need maintenance, and can create wrong matches elsewhere ("far" is not always about range).

Test yourself

What does an inverted index store?

  1. For each document, its TF-IDF vector
  2. For each term, the list of documents that contain it
  3. The queries users typed
  4. A sorted list of document lengths

In BM25, what does the parameter k1k_1 control?

  1. Length normalisation
  2. How quickly repeated occurrences of a term stop adding to the score (saturation)
  3. The number of results returned
  4. The idf smoothing

On the 12 TAD Bikes queries, what were recall@1 and MRR of BM25 with k1=1.5k_1 = 1.5, b=0.75b = 0.75?

  1. 0.667 and 0.743
  2. 0.917 and 0.924
  3. 0.583 and 0.711
  4. 0.750 and 0.795

Why does keyword search miss "my bike has a flat tyre"?

  1. The query is too short
  2. BM25 cannot handle stop words
  3. The relevant article describes the problem with different words (damaged, problem) and shares only "bike"
  4. The article is too long

The configuration without stop-word removal scored best (recall@1 0.917). Why should you not adopt it on that evidence?

  1. Its wins come from function words that happen to match, and with 12 queries a difference of one query is noise
  2. Stop words make the index too large
  3. BM25 requires stop-word removal
  4. It is slower