Designing a Modular Search Engine

How to structure a search engine so that its components can be replaced, compared, and tested independently. Interfaces for analysis, indexing, and ranking, a working Python sketch, lessons from my course project code, and the course project worked in full (layout, command-line shell, a BM25 ranker checked against this site's engine, and a test scaffold).

A search engine whose ranking models must be compared fairly should put each pipeline stage behind a narrow interface, with dependencies running one way and one analyzer shared by documents and queries. This article gives such a design and a runnable Python sketch. On four short Arctic documents and the query arctic climate warming, its Boolean AND returns d1 and d2, and TF-IDF scores those two 0.551 and the other two 0.125. A query path that skips stemming silently returns nothing. Adding BM25 ($k_1 = 1.2$, $b = 0.5$) needs one new index statistic, the average document length. Counting length in all tokens, as this site's engine does, reproduces its scores (0.6182 and 0.1678); counting index terms puts d4 ahead of d3. Document length therefore belongs in the index's contract.

The architecture article ranked four short Arctic documents for the query arctic climate warming twice, once with a Boolean AND and once with TF-IDF weights. A search engine built over a semester faces that comparison again and again. The first version answers Boolean queries. A few weeks later it needs TF-IDF weighting and cosine similarity, then probabilistic weights, then BM25, and eventually classifiers and clustering built on the same index. Each new model has to be compared with the previous ones on the same documents and queries. That is only a fair comparison if everything except the model stays fixed. How should a search engine be built so that one part can change while everything else stays exactly the same? Each stage is put behind a small interface, and the other stages are written against the interface and never against the code behind it.

A system written as one long script makes this painful. Changing the ranking function means editing code that also tokenizes, indexes, and prints results, and every change risks breaking something unrelated. The remedy is a modular design: each stage of the search engine pipeline is a separate component behind an interface, so that any one of them can be replaced without touching the others. The previous article gave a second reason. Each setting needed a different part swapped in: a permission filter, date sorting, attribute parsing.

First we see why retrieval in particular needs modularity. Then we list the components and give a working Python sketch that reproduces the four-document example. Next we turn to testing, where the design pays for itself. Then we compare the design with real code: the course code, written week by week as new models were added, which this article's sketch develops further; this site's own search engine; and the Lucene library. Finally the worked problems state the course project for this topic and solve it with the sketch. The article assumes the architecture article, whose pipeline the components follow.

Why modularity matters for retrieval in particular

Modularity is good general practice, but retrieval has three specific reasons to insist on it.

Experiments compare one component at a time. Retrieval research advances by controlled comparison. Hold the collection, the queries, the relevance judgments, and the text analysis fixed, change one thing, and measure the difference. If the ranking function cannot be swapped without also changing the tokenizer, a difference in effectiveness cannot be attributed to the ranking function. The experimental method described in evaluation requires a system whose parts can be varied independently.

Documents and queries must be analyzed identically. As the architecture article showed, a query must pass through exactly the same tokenization, stop-word removal, and stemming as the documents, or terms silently fail to match. Deliberate query-side additions, such as synonym expansion, are a separate design decision. The danger is accidental differences.

Example (a query path that forgets to stem). The four Arctic documents are indexed with stemming. If a second, hand-written query path lowercases but forgets to stem, the Boolean AND returns nothing for arctic climate warming. The index holds the stems climat and warm, so the unstemmed climate and warming match no document, and only arctic survives, with a document frequency of 3 against 0 for the other two (checked by tools/experiments/foundations/modular_sketch.py, which runs the sketch below with the stemmer removed from the query side). No error is raised; the result is simply empty. The most reliable way to prevent this is to have one analysis component that both paths call. Duplicating the analysis code in two places invites the two copies to drift apart.

The index is a contract. Each ranking model needs particular statistics from the index: postings, term frequencies, document frequencies, document lengths. Suppose ranking code reads the index's internal data structures directly. Then changing how the index stores postings, for instance by compressing them or moving them to disk, breaks every ranking model at once. If ranking code asks the index for statistics through a defined interface, the index can change freely behind it.

The components

Those three reasons say where the boundaries go. A small search engine divides naturally into the following components. Each corresponds to a stage of the pipeline and to a later topic in the course.

Component Responsibility Course topic
Document source Reads documents from files, a database, or a crawler, and yields (identifier, text) pairs Web crawling
Analyzer Turns text into index terms: tokenization, normalization, stop words, stemming Text processing
Index Stores postings and collection statistics; builds, saves, and loads itself The inverted index
Query parser Turns a query string into a structured query: terms, operators, phrases Boolean retrieval
Ranker Scores documents for a query using only the index interface Vector space, probabilistic
Presenter Formats results, with titles and snippets
Evaluator Runs a set of queries and compares results with relevance judgments Evaluation

The dependencies run in one direction:

  • the index depends on the analyzer;
  • the ranker depends on the index interface, not on any particular index;
  • the search engine connects an analyzer, an index, and a ranker;
  • the evaluator depends only on the search engine's ability to answer queries.

Nothing depends on the presenter, so the same engine can drive a command-line interface, a web page, or an evaluation script.

The components in the table, with the classes of the sketch below, and what each one uses. The sketch has no separate query parser: the search engine passes the query through the analyzer. Notice that every arrow points downward or sideways toward more basic components, so there are no cycles. The two dashed boxes are interfaces: the search engine and the rankers depend only on them, and any class that implements them, such as InMemoryIndex or TfIdf, can be substituted.
The components in the table, with the classes of the sketch below, and what each one uses. The sketch has no separate query parser: the search engine passes the query through the analyzer. Notice that every arrow points downward or sideways toward more basic components, so there are no cycles. The two dashed boxes are interfaces: the search engine and the rankers depend only on them, and any class that implements them, such as InMemoryIndex or TfIdf, can be substituted.

A working sketch

A table of boundaries is easy to agree with. Does it hold up as code? It does: the following Python implements the core of this design. It is deliberately small, but it runs, and it reproduces the four-document example from the architecture article.

The analyzer is a single class used for both documents and queries. It stems with the algorithm of Porter (1980) in its original form:

import math
import re
from abc import ABC, abstractmethod
from collections import Counter, defaultdict

from nltk.stem import PorterStemmer


class Analyzer:
    """Turns raw text into index terms. Used for documents and queries alike."""

    def __init__(self, stop_words):
        self.stop_words = set(stop_words)
        self.stemmer = PorterStemmer(mode=PorterStemmer.ORIGINAL_ALGORITHM)

    def analyze(self, text):
        tokens = re.findall(r"[a-z]+", text.lower())
        return [self.stemmer.stem(t) for t in tokens if t not in self.stop_words]

The index interface states what a ranking model may ask of an index, and nothing more. An in-memory implementation stores postings in dictionaries. A later implementation could store compressed postings on disk, and no ranking code would change.

class Index(ABC):
    """What a ranking model may ask of an index, and nothing more."""

    @abstractmethod
    def postings(self, term):
        """Return a list of (doc_id, term_frequency) pairs."""

    @abstractmethod
    def doc_freq(self, term): ...

    @abstractmethod
    def doc_length(self, doc_id): ...

    @property
    @abstractmethod
    def num_docs(self): ...


class InMemoryIndex(Index):
    def __init__(self, analyzer):
        self.analyzer = analyzer
        self._postings = defaultdict(dict)
        self._lengths = {}

    def add(self, doc_id, text):
        if doc_id in self._lengths:
            raise ValueError(f"document already indexed: {doc_id}")
        terms = self.analyzer.analyze(text)
        self._lengths[doc_id] = len(terms)
        for term, tf in Counter(terms).items():
            self._postings[term][doc_id] = tf

    def postings(self, term):
        return sorted(self._postings.get(term, {}).items())

    def doc_freq(self, term):
        return len(self._postings.get(term, {}))

    def doc_length(self, doc_id):
        return self._lengths[doc_id]

    @property
    def num_docs(self):
        return len(self._lengths)

The sketch rejects a second add with an identifier already in the index. Simply overwriting would leave the old version's postings in place. A replaced document would then still match terms it no longer contains. Supporting updates properly requires a delete operation that removes those postings and adjusts the collection statistics.

Rankers share one method. A Boolean conjunction and a TF-IDF scorer are interchangeable because both use only the index interface. Both models are the course text's: the intersection of postings lists (Manning, Raghavan, and Schütze, 2008, chapter 1) and the sum of term frequency times inverse document frequency over the query terms (chapter 6), computed on terms prepared as in its chapter 2:

class Ranker(ABC):
    @abstractmethod
    def score(self, query_terms, index):
        """Return {doc_id: score} for documents matching the query."""


class BooleanAnd(Ranker):
    def score(self, query_terms, index):
        sets = [{d for d, _ in index.postings(t)} for t in query_terms]
        return {d: 1.0 for d in set.intersection(*sets)} if sets else {}


class TfIdf(Ranker):
    def score(self, query_terms, index):
        scores = defaultdict(float)
        for t in query_terms:
            df = index.doc_freq(t)
            if df == 0:
                continue
            idf = math.log10(index.num_docs / df)
            for doc_id, tf in index.postings(t):
                scores[doc_id] += tf * idf
        return dict(scores)

Because TfIdf loops over the analyzed query terms, a term that appears twice in the query contributes twice to each score. That amounts to weighting query terms by their frequency in the query. Iterating over set(query_terms) would treat the query as a set instead.

The search engine connects the parts. It analyzes the query with the same analyzer the index used, asks the ranker for scores, and sorts them. Ties are broken by document identifier, so the output is deterministic:

class SearchEngine:
    def __init__(self, analyzer, index, ranker):
        self.analyzer, self.index, self.ranker = analyzer, index, ranker

    def search(self, query, k=10):
        terms = self.analyzer.analyze(query)
        scores = self.ranker.score(terms, self.index)
        return sorted(scores.items(), key=lambda item: (-item[1], item[0]))[:k]

Nothing in these classes checks that the analyzer given to SearchEngine is the one the index was built with. Both would satisfy their interfaces, and a mismatch would only lower effectiveness without raising an error, as the unstemmed query above did. A larger system records the analyzer configuration with the index and builds the query analyzer from it.

Running both rankers on the example collection:

docs = {
    "d1": "Arctic sea ice is declining as the climate warms.",
    "d2": "A warming climate threatens Arctic seabirds and their food.",
    "d3": "Climate models predict warmer winters in Europe.",
    "d4": "Seabirds of the Arctic: a field guide.",
}
analyzer = Analyzer(["a", "and", "as", "in", "is", "of", "the", "their"])
index = InMemoryIndex(analyzer)
for doc_id, text in docs.items():
    index.add(doc_id, text)

for ranker in (BooleanAnd(), TfIdf()):
    engine = SearchEngine(analyzer, index, ranker)
    print(type(ranker).__name__, engine.search("arctic climate warming"))

produces, with scores rounded to three places,

BooleanAnd [('d1', 1.0), ('d2', 1.0)]
TfIdf [('d1', 0.551), ('d2', 0.551), ('d3', 0.125), ('d4', 0.125)]

which matches the hand computation in the architecture article. The Boolean ranker returns d1 and d2, the two documents that contain all three stems. TF-IDF also ranks them first and adds d3 and d4 below them.

Adding BM25 later means writing one new Ranker subclass. It also needs the average document length, which the interface above does not provide. A ranker cannot sum doc_length without a way to list the documents. The fix is to add one method, such as avg_doc_length, to Index and implement it once in each index class. That is the normal way an interface grows. A new model reveals a statistic it needs, the index learns to supply it, and the analyzer and search engine are unchanged. The worked problems below make the change and run it.

Testing

The sketch's output matched a hand computation. That match is the most useful kind of test, and a modular design is what makes it easy to write. Retrieval code needs tests more than it might appear. A bug in a ranking function rarely causes an error. It produces a slightly different ranking that looks plausible. The most useful tests are therefore small collections with hand-computed expected scores, such as the four-document example:

def test_tfidf_matches_hand_computation():
    engine = SearchEngine(analyzer, index, TfIdf())
    results = dict(engine.search("arctic climate warming"))
    assert abs(results["d1"] - 0.551) < 1e-3
    assert abs(results["d3"] - 0.125) < 1e-3

Example (a change of logarithm). Suppose the TfIdf class computed idf with the natural logarithm instead of base 10. The ranking of the four documents would not change: every idf, and so every score, would be multiplied by the same constant, $\ln 10 \approx 2.3026$, giving 1.269, 1.269, 0.288 and 0.288. The test above would still catch the slip, because it checks the score 0.551 itself and not only the order. A test that compared rankings alone would pass, which is why hand-computed scores are worth the trouble.

Other useful tests check properties that should hold for any correct implementation:

  • a document containing none of the query terms is never returned;
  • the analyzer produces the same terms for a word whether it appears in a document or a query;
  • adding a document identifier twice is rejected without changing the index;
  • saving and loading an index, for implementations that support it, leaves every statistic unchanged;
  • two index implementations return identical postings for the same collection.

The last kind of test is what makes it safe to replace a simple index with a faster one.

Beyond unit tests, the evaluator provides the end-to-end test. Given a set of queries with relevance judgments, it computes measures such as precision and average precision for each ranker. Whenever a component changes, rerunning the evaluation shows whether effectiveness improved, worsened, or stayed the same.

Lessons from my course code

The sketch was written with hindsight. Code written week by week, as the course added models, shows which parts of the design matter most. My homework solutions for the course, in the information-retrieval repository, and the Goodreads project that grew out of them, applied this kind of design. Reviewing them afterward shows both what worked and what I would change.

Factories for choosing implementations. HW03 defines an abstract BaseIndex with two implementations, a standard single-process index and a parallel one that uses multiple processes to build large indexes faster. An IndexFactory chooses between them. It selects the parallel index when the collection has at least 5,000 documents and multiprocessing is available, and falls back to the standard index otherwise. The vector space models follow the same pattern, with standard, sparse-matrix, and parallel implementations behind one interface. The calling code never needs to know which implementation it received, which is the main benefit the design promises.

Consistent analysis, with a coupling cost. In the Goodreads project, the Binary Independence Model processes queries by calling the index's own preprocessing method. Queries and documents are therefore guaranteed to be analyzed identically. That was the right goal. But the method is a private one (_preprocess_text), and to find candidate documents the BIM code reads the index's internal dictionary of postings (term_doc_freqs) directly. That dictionary is not part of BaseIndex. An index implementation that stored postings differently would satisfy the interface, and the BIM would have to change with it. The sketch above takes the design one step further. It makes the analyzer a separate component that both the index and the query path use, and it gives the index interface a postings method, so rankers never touch its internals.

Interfaces should be narrow. The BaseIndex in HW03 declares fourteen abstract methods and properties, including JSON export, memory usage reporting, and the per-file processing step. Every new implementation must provide all of them, even those unrelated to retrieval. That makes alternative implementations expensive to write. A better division keeps the interface that rankers depend on small, as in the sketch above, and moves reporting and persistence into separate interfaces or helper functions.

Abstractions should follow implementations. The abstract classes were most useful where at least two real implementations existed, as with the standard and parallel indexes. Where only one implementation was ever written, the abstraction prepared for a second version that the course did not call for. A reasonable rule is to write the first version concretely and extract an interface when the second version arrives. At that point it is clear which operations actually vary.

A second example: this site's search engine

The course code is one comparison. The search box on this site is another small engine of the same kind, and it divides the work differently from the sketch in one important place. It does six things:

  • indexes the wiki's articles when the site starts;
  • ranks them with BM25F over four fields (title, summary, headings, and body);
  • for the full results, fuses that ranking with a dense ranking from a small sentence encoder;
  • answers Boolean and phrase queries;
  • suggests spelling corrections;
  • gives instant results in the browser as a query is typed.

The modules, as of November 2026, and the checks that hold them together. The figure shows the BM25F path; the last two rows of the table are the hybrid ranking added beside it.

The modules of this site's search engine and the checks around them. The server side runs from routes.py down to the stemmer and the article files. Notice that the browser's instant search does not call the server's code at all: it fetches the index that SearchIndex exports, and the parity test runs both sides on the same queries to confirm they rank alike.
The modules of this site's search engine and the checks around them. The server side runs from routes.py down to the stemmer and the article files. Notice that the browser's instant search does not call the server's code at all: it fetches the index that SearchIndex exports, and the parity test runs both sides on the same queries to confirm they rank alike.
Module Public interface Input Used by
porter.py stem(word) One lowercase word search.py; check_porter.py compares it with NLTK's implementation
query.py parse(query) returns a tree and repair notes The raw query string SearchIndex.search
wiki.py Wiki().all() returns article records The Markdown files routes.py, which hands the records to SearchIndex
search.py SearchIndex(articles), with search(query), suggest(query), export() Article records routes.py, evaluate.py, test_parity.py
search-core.js new Index(data).search(text) The exported index search-ui.js in the browser, and the parity test under Node
dense.py load(articles) returns a DenseIndex, with search(query, limit, section), or None when the model or vectors are missing or stale The query; passage vectors and the pinned MiniLM encoder (all-MiniLM-L6-v2), run with onnxruntime, both built at deploy by dense_build.py hybrid.py; dense_build.py encodes the passages with its Encoder; test_hybrid.py
hybrid.py build(index, articles) returns a HybridSearch, whose search(query) takes the arguments of SearchIndex.search A SearchIndex and a DenseIndex routes.py, for /search and /api/search; test_hybrid.py

Several of the article's points show up in this code.

The parser does not analyze. query.py turns (stemming OR lemmatization) AND NOT porter into a tree of operators over the words as typed. It never lowercases, removes stop words, or stems. The index does that when it evaluates the tree, with the same folding, stop list, and stemmer it used when indexing. The parser can therefore be tested on its own, as pure syntax, and it cannot analyze a word differently from the index, because it does not analyze at all. The remaining risk is the one this article warns of. Inside SearchIndex, indexing and query evaluation call the shared folding, stop-list, and stemming functions from two separate code paths. A divergence between them would surface only as a failing test, such as an article that no longer ranks first for its own title.

Ranking is not a separate component. Here the site departs from the sketch. BM25F is a method of SearchIndex, with its field weights and parameters as module constants, rather than a Ranker behind an interface. Swapping in another model would mean editing the index class. That is the lesson about abstractions from the course code applied in reverse. The site has one ranking function, tuned once, and an interface with a single implementation would add code without adding a choice. If a second ranker were ever wanted, for comparison on the known-item queries, extracting the interface would be the first step. A second ranking did arrive in November 2026, and it was added beside the index rather than inside it. The full results (/search and /api/search) fuse BM25F's ranked list with a dense ranking from a small sentence encoder (dense.py) by reciprocal rank fusion (hybrid.py), as Hybrid Retrieval describes and evaluates. Each page scores $\sum 1/(60 + \text{rank})$ over the two rankings' top 100. A query with operators, a query BM25F finds nothing for, or a site without the dense files gets BM25F's results alone. The fusion needs only each ranker's ordered list, so SearchIndex did not change; the instant results in the browser stay BM25F alone.

The export is a contract, and a test enforces it. BM25F gives each pair of a term and an article a fixed contribution to the score. So export() precomputes those weights, and the browser's code only adds them up. The browser therefore needs no stemmer and no BM25F of its own. It cannot rank differently from the server unless the export or the adding is wrong. test_parity.py checks exactly that. It runs search-core.js under Node and SearchIndex.search in Python on every article title, cut off at several lengths, and on the known-item queries. It fails if any ranking differs. It is the same kind of test recommended above for two index implementations, applied across two languages.

The evaluator is a script over judged queries. evaluate.py measures mean reciprocal rank and success at 1 and 3 on a file of known-item queries, each paired with the one article that should come first. The BM25F weights were tuned on the first half of the file and checked on the held-out second half. That is the controlled comparison described at the start of this article, in miniature.

Nothing depends on the presenter. The same SearchIndex serves three presenters: the results page, the instant results in the browser, and a JSON interface (/api/search and /api/page, described for tool use at /openapi.json) through which a language-model assistant can search the site and read a page section by section. How this site's search works traces the engine on its real index.

How production systems divide the work

Are these boundaries a matter of taste? Not only: the same divisions appear in established search libraries, which is good evidence that they reflect real boundaries in the problem. Apache Lucene, the library beneath Elasticsearch and Solr, separates three things:

  • an Analyzer, a tokenizer followed by a chain of token filters;
  • the index writer;
  • the scoring model, a pluggable Similarity class.

Switching between classic TF-IDF scoring and BM25 means choosing a different Similarity, without rebuilding the index, provided the index stores the statistics the new model needs. Research toolkits built on Lucene, such as Anserini (Yang, Fang, and Lin, 2017), exploit this separation to make retrieval experiments reproducible. The same index can be searched with many ranking models, and every result can be regenerated from a documented configuration. Implementing BM25 returns to Anserini as a source of reproducible BM25 baselines.

Worked problems

The course's project for this topic asked for the skeleton of a search engine that the later topics would fill in. It had four parts: a repository with a sensible layout; a shell through which the engine is run, on the command line or in a window; abstract base classes for the core components; and conventions for code and documentation, with a scaffold for tests. The four problems below are those parts, restated in our own words and solved with this article's sketch. The script tools/experiments/foundations/modular_sketch.py contains every class and test shown here and asserts every number.

Problem 1 (the layout). Arrange the components as files so that the dependencies run in one direction.

Solution. One file per component, with imports that follow the arrows of the component figure, satisfies the rule:

searchengine/
    analysis.py     Analyzer
    index.py        Index (interface), InMemoryIndex, SortedListIndex
    ranking.py      Ranker (interface), BooleanAnd, TfIdf, BM25
    engine.py       SearchEngine
    cli.py          the command-line shell
tests/
    test_engine.py  hand-computed scores and property tests
  • analysis.py imports nothing from the package.
  • index.py imports nothing from the package either. An index is handed an analyzer when it is built and calls its analyze method.
  • ranking.py imports nothing from the package. A ranker receives an index as an argument and uses only the methods of the Index interface.
  • engine.py uses an analyzer, an index and a ranker, all passed to it.
  • cli.py is the only file that names concrete classes, because it is where the choice among them is made.

No file imports from a file below it in the list, so there is no cycle, and each of the first three files can be tested with nothing else present.

The course code is organized on the same lines, one folder per assignment. The third assignment's folder has a main.py that parses command-line options, a src/index/ package with base.py (the abstract BaseIndex), factory.py, standard_index.py and parallel_index.py, a src/vsm/ package built the same way for the vector space models, and a profiler. The fourth keeps the index package and adds the Binary Independence Model beside it. The layout above differs in one respect, which is the lesson of the section on that code: the analyzer is a file of its own, where the course code makes text processing a method of the index.

Problem 2 (the shell). Write a command-line shell that builds an index from a file of documents and answers a query with a chosen ranker.

Solution. The shell is the presenter, and it needs about twenty lines. It reads one document per line, as an identifier, a tab and the text:

RANKERS = {"boolean": BooleanAnd, "tfidf": TfIdf, "bm25": BM25}
STOP = ["a", "and", "as", "in", "is", "of", "the", "their"]


def cli(argv=None):
    parser = argparse.ArgumentParser(
        description="Search a file of documents, one 'id<TAB>text' per line.")
    parser.add_argument("docs")
    parser.add_argument("query", nargs="+")
    parser.add_argument("--ranker", choices=sorted(RANKERS), default="tfidf")
    parser.add_argument("-k", type=int, default=10)
    args = parser.parse_args(argv)
    analyzer = Analyzer(STOP)
    index = InMemoryIndex(analyzer)
    for line in Path(args.docs).read_text(encoding="utf-8").splitlines():
        doc_id, text = line.split("\t", 1)
        index.add(doc_id, text)
    engine = SearchEngine(analyzer, index, RANKERS[args.ranker]())
    hits = engine.search(" ".join(args.query), args.k)
    for rank, (doc_id, score) in enumerate(hits, 1):
        print(f"{rank}. {doc_id}  {score:.4f}")

On a file holding the four Arctic documents, cli.py arctic.tsv --ranker tfidf arctic climate warming prints

1. d1  0.5509
2. d2  0.5509
3. d3  0.1249
4. d4  0.1249

and with --ranker boolean it prints 1. d1 1.0000 and 2. d2 1.0000. These are the sketch's two results to four places: 0.5509 is the 0.551 of the earlier output, the sum $2\log_{10}(4/3) + \log_{10} 2 = 2 \times 0.1249 + 0.3010$. The ranker is chosen by name from a table, so adding a model means adding one entry. Nothing else in the shell refers to a particular model.

Problem 3 (the base classes, extended for BM25). Add what BM25 needs to the Index interface, write the ranker, and check it on the four documents against the scores of the architecture article, 0.6182 for d1 and d2 and 0.1678 for d3 and d4.

Solution. The interface gains one property, the ranker is one class, and the scores match the architecture article's once document length is defined as that article's engine defines it.

The interface gains avg_doc_length, and each index class implements it:

class Index(ABC):
    ...
    @property
    @abstractmethod
    def avg_doc_length(self): ...


class InMemoryIndex(Index):
    ...
    @property
    def avg_doc_length(self):
        return sum(self._lengths.values()) / len(self._lengths)

The ranker uses the formula of the architecture article, with $k_1 = 1.2$ and $b = 0.5$:

class BM25(Ranker):
    def __init__(self, k1=1.2, b=0.5):
        self.k1, self.b = k1, b

    def score(self, query_terms, index):
        scores = defaultdict(float)
        n, avg = index.num_docs, index.avg_doc_length
        for t in query_terms:
            df = index.doc_freq(t)
            if df == 0:
                continue
            idf = math.log(1 + (n - df + 0.5) / (df + 0.5))
            for doc_id, tf in index.postings(t):
                norm = 1 - self.b + self.b * index.doc_length(doc_id) / avg
                pseudo = tf / norm
                scores[doc_id] += idf * pseudo / (self.k1 + pseudo)
        return dict(scores)

Run on the sketch's index, it gives

BM25 [('d1', 0.6238), ('d2', 0.6238), ('d4', 0.1752), ('d3', 0.1582)]

These are not the architecture article's scores, and d4 is now ahead of d3 where that article had them tied. The ranker is the same. The difference is in what the index reports as a document's length. InMemoryIndex counts index terms, after stop words are removed: 6, 6, 6 and 4, with an average of 5.5. The site's engine counts every token, stop words included: 9, 9, 7 and 7, with an average of 8. By hand, for the sketch's lengths:

  • d1 and d2: the divisor is $1 - 0.5 + 0.5 \times 6/5.5 = 1.0455$, so $tf' = 1/1.0455 = 0.9565$ and $tf'/(k_1 + tf') = 0.9565/2.1565 = 0.4435$. The three terms have IDF 0.3567, 0.3567 and 0.6931, which sum to 1.4065, and $0.4435 \times 1.4065 = 0.6238$.
  • d3 has the same length as d1, so its one term, climat, gives $0.4435 \times 0.3567 = 0.1582$.
  • d4: the divisor is $1 - 0.5 + 0.5 \times 4/5.5 = 0.8636$, so $tf' = 1.1579$ and $tf'/(k_1 + tf') = 1.1579/2.3579 = 0.4911$. Its one term, arctic, gives $0.4911 \times 0.3567 = 0.1752$.

d3 and d4 have 7 tokens each, but d4 loses three of them to the stop list (of, the, a) and d3 loses one (in). Counted in index terms, d4 is the shorter document, and BM25 rewards it.

A second index class that counts tokens changes one method:

class TokenLengthIndex(InMemoryIndex):
    """Counts every token, stop words included, as this site's engine does."""

    def add(self, doc_id, text):
        super().add(doc_id, text)
        self._lengths[doc_id] = len(re.findall(r"[a-z]+", text.lower()))

With it, the same BM25 class gives

BM25 [('d1', 0.6182), ('d2', 0.6182), ('d3', 0.1678), ('d4', 0.1678)]

which is the architecture article's table to four places. The result of the problem is therefore two things. The BM25 ranker is correct against an independent implementation, the site's own. And "document length" turned out to be part of the index's contract that the interface's name did not settle. Two indexes that both satisfy the interface gave two different rankings of d3 and d4. A docstring on doc_length that says which tokens are counted is not decoration.

Problem 4 (conventions and the test scaffold). State the conventions the code follows and write the tests that hold the skeleton together.

Solution. Six tests, each a plain function with assert statements, cover the sketch; all six pass. The conventions are the ones the sketch already shows:

  • every interface method has a docstring that states what it returns, including units and order (postings returns pairs sorted by document identifier);
  • a ranker touches an index only through the interface;
  • every result is deterministic, with ties broken by identifier, so that a test can compare whole outputs;
  • a number in a test comes from a hand computation that is written down, here the architecture article's tables.

The tests:

Test What it asserts on the four documents
test_tfidf_matches_hand_computation d1 scores 0.551 and d3 scores 0.125, to within 0.001
test_no_query_term_no_result for three queries and all three rankers, every document returned contains at least one query term
test_analyzer_is_the_same_on_both_paths warming, Warms, CLIMATE and seabirds, analyzed as queries, each give a term that is in the index
test_duplicate_identifier_is_rejected a second add of d1 raises an error and leaves postings, document count and average length unchanged
test_save_and_load_change_nothing an index saved to a file and loaded back has the same vocabulary, postings, lengths and average, and gives the same results under all three rankers
test_two_index_implementations_agree InMemoryIndex and SortedListIndex return identical postings for every term and identical results under all three rankers

The fifth test needs the index to save and load itself, which is two short methods:

    def save(self, path):
        data = {"postings": self._postings, "lengths": self._lengths}
        Path(path).write_text(json.dumps(data, sort_keys=True), encoding="utf-8")

    @classmethod
    def load(cls, path, analyzer):
        data = json.loads(Path(path).read_text(encoding="utf-8"))
        index = cls(analyzer)
        index._lengths = dict(data["lengths"])
        for term, docs in data["postings"].items():
            index._postings[term] = dict(docs)
        return index

The analyzer is passed to load and not stored in the file. That keeps the file format simple, and it is the gap this article named earlier: nothing checks that the analyzer handed to load is the one the index was built with. A fuller version writes the analyzer's configuration (stop list, stemmer and its mode) into the file and rebuilds the analyzer from it.

The sixth test needs a second implementation. SortedListIndex keeps each postings list as a sorted list of pairs instead of a dictionary, and implements the same five members of the interface. It exists to make the test possible, and the test is what would make it safe to replace the dictionary index by a compressed or on-disk one later.

Together the four parts are the project's result: a layout whose imports run one way, a shell that selects a ranker by name, an index interface with five members and three implementations, three rankers that agree with hand computation and with the site's engine, and six tests that pass. Each later topic of the course adds to one file of the layout.

What we have learned

The design in this article is a small version of the same idea. It divides the system along the pipeline described in the architecture article, connects the parts through narrow interfaces, and keeps one analyzer for both documents and queries. The four Arctic documents showed what the boundaries protect. A query path that skipped stemming returned nothing, without raising an error. A test on the score 0.551, not just the order, catches a change of logarithm that a ranking comparison would miss. A system built this way can grow through the whole course: each later topic adds or replaces one component, and the evaluator shows whether each change helped.

That growth starts at the first component. The sketch's analyzer assumed clean English sentences, split on letters. Real collections arrive as files, in many encodings, formats, and languages, and someone must first decide what counts as a document at all. The next topic, Text Processing and Indexing, begins there: From Bytes to Documents shows how bytes on disk become the text an analyzer can work with.

References

  • Manning, C. D., Raghavan, P., and Schütze, H. (2008). Introduction to Information Retrieval, chapters 1–2 and 6. Cambridge University Press. record · 102 pages
  • Porter, M. F. (1980). An algorithm for suffix stripping. Program, 14(3), 130–137. record · 6 pages
  • Yang, P., Fang, H., and Lin, J. (2017). Anserini: Enabling the use of Lucene for information retrieval research. In Proceedings of SIGIR 2017, 1253–1256. record · 2 pages
  • Apache Lucene documentation: org.apache.lucene.analysis.Analyzer and org.apache.lucene.search.similarities.Similarity. https://lucene.apache.org/

Reviewed: verified, 16 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 11 revisions