Ranking documents with BM25

File: bm25.lisp

Search engines have used BM25 to rank documents for decades. This program implements it from scratch in about forty lines: tokenize a small corpus, score documents against a query, and return ranked hits.

For term Code Test occurring in Code Test of Code Test documents, the inverse document frequency is:

math

and the score of document Code Test for query Code Test is:

math

with the standard defaults Code Test and Code Test.

The code

 1 ;; sbcl --script bm25.lisp   (Okapi BM25 document ranking)
 2 
 3 (defun tokenize (text)
 4   (loop with len = (length text) and words = nil and acc = nil
 5         for i from 0 below len
 6         for ch = (char text i)
 7         do (if (alphanumericp ch)
 8                (push (char-downcase ch) acc)
 9                (when acc
10                  (push (coerce (nreverse acc) 'string) words)
11                  (setf acc nil)))
12         finally (when acc (push (coerce (nreverse acc) 'string) words))
13                 (return (nreverse words))))
14 
15 (defun bm25-search (corpus query &key (k1 1.5) (b 0.75))
16   (let* ((docs (mapcar #'tokenize corpus))
17          (n (length corpus))
18          (lens (mapcar #'length docs))
19          (avgdl (/ (reduce #'+ lens) (float (max 1 n))))
20          (idfs                          ; ((term . idf) ...), once per term
21            (loop for term in (remove-duplicates (tokenize query)
22                                                 :test #'string=)
23                  for df = (count-if (lambda (d)
24                                       (member term d :test #'string=))
25                                     docs)
26                  collect (cons term
27                                (log (+ 1.0 (/ (+ (- n df) 0.5)
28                                               (+ df 0.5))))))))
29     (sort (loop for doc in docs
30                 for raw in corpus
31                 for len in lens
32                 for score =
33                 (loop for (term . idf) in idfs
34                       for tf = (count term doc :test #'string=)
35                       when (> tf 0)
36                       sum (* idf
37                              (/ (* tf (+ k1 1.0))
38                                 (+ tf (* k1
39                                          (+ (- 1.0 b)
40                                             (* b (/ len avgdl))))))))
41                 when (> score 0.0)
42                 collect (list score raw))
43           #'> :key #'car)))
44 
45 ;; Demo: Document corpus search
46 (let ((corpus
47         (list
48          (concatenate 'string
49           "Common Lisp is a general-purpose programming language "
50           "with powerful macros.")
51          (concatenate 'string
52           "Python is an interpreted language known for data science "
53           "and machine learning.")
54          (concatenate 'string
55           "Deep learning models require automatic differentiation "
56           "and gradient optimization.")
57          (concatenate 'string
58           "Macros in Common Lisp enable syntactic metaprogramming "
59           "and DSL design.")
60          (concatenate 'string
61           "Okapi BM25 is an information retrieval ranking function "
62           "used in search engines."))))
63   (format t "Corpus size: ~a documents~%" (length corpus))
64   (dolist (query '("Common Lisp macros" "search ranking" "learning"))
65     (format t "~%Query: ~s~%" query)
66     (dolist (hit (bm25-search corpus query))
67       (format t "  [score: ~5,3f] ~a~%" (first hit) (second hit)))))

How it works

  • tokenize is a hand-written scanner built with loop: it collects alphanumeric characters (downcased) and emits a word whenever a non-alphanumeric character ends the run.
  • The function computes idfs once per query, before any scoring: an alist of (term . idf) pairs, where count-if counts the documents that contain each term. Computing it per document would rescan the whole corpus for every document and turn a linear pass into a quadratic one.
  • The scoring loop steps through documents, raw strings, and lengths in parallel (for ... for ... for ...) and computes each document’s score as a sum over unique query terms. The inner loop for (term . idf) in idfs destructures each pair. remove-duplicates on the query terms stops a repeated word from counting twice.
  • The division by avgdl is safe even for a corpus of empty strings: it runs only when tf > 0, which means the document, and so the average length, is non-empty.
  • The Code Test parameter controls term-frequency saturation, and Code Test controls how much the score penalizes documents longer than the average length Code Test.

Running it

1 $ sbcl --script bm25.lisp

Actual output:

 1 Corpus size: 5 documents
 2 
 3 Query: "Common Lisp macros"
 4   [score: 2.717] Macros in Common Lisp enable syntactic metaprogramming and DSL design.
 5   [score: 2.605] Common Lisp is a general-purpose programming language with powerful macros.
 6 
 7 Query: "search ranking"
 8   [score: 2.641] Okapi BM25 is an information retrieval ranking function used in search engines.
 9 
10 Query: "learning"
11   [score: 0.946] Deep learning models require automatic differentiation and gradient optimization.
12   [score: 0.834] Python is an interpreted language known for data science and machine learning.

The output shows length normalization at work. For “learning”, both matching documents contain the word once, but the 9-token deep-learning sentence beats the 12-token Python sentence: the same match counts for more in a shorter document. Length also decides “Common Lisp macros”: both documents contain all three query words, and the 10-token sentence scores higher than the 11-token one. “search” and “ranking” each appear in only one document, so they get the highest idf weight, and that document scores high on a two-word query.

Using it

BM25 is a strong baseline for any local keyword search: your notes, a set of docs, log files. It also pairs well with the vector-store chapter; hybrid search systems often merge BM25 (exact keyword match) with embedding similarity (semantic match). The (score document) lists come back sorted, ready to cut to a top-Code Test list.