Suryanand/ Bootcamp
suryanand.com ↗Let's talk
Frame · dsa / ai-algorithms / 04-bm25-keyword-scoring.jsJavaScript

BM25 Keyword Relevance Scoring

Use the tabs to read the prompt, implementation, and tests separately. Syntax uses Shiki; tests can be executed on the server with node --test.

Same file as in the repo · ~20s timeout

From file header (JSDoc)

BM25 Keyword Relevance Scoring

Problem: Implement Okapi BM25, the classic sparse ranking function used for
keyword search and as the lexical half of hybrid retrieval. Given a list of
documents (strings) and a query, return the BM25 score of every document:

  score(D, Q) = sum over terms t in Q of
    IDF(t) * tf(t, D) * (k1 + 1) / (tf(t, D) + k1 * (1 - b + b * |D| / avgdl))
  IDF(t) = ln((N - df(t) + 0.5) / (df(t) + 0.5) + 1)

Tokenise by lowercasing and taking runs of letters/digits. Defaults are
k1 = 1.2 and b = 0.75. Also provide `rankBM25` returning document indices
sorted by score descending (ties by lower index).

Constraints:
- 1 <= docs.length <= 10^5, total tokens <= 10^7

Example:
  docs = ["cat dog", "cat cat"], query = "dog"
  -> scores [ln 2, 0]

Approach: Pre-compute term frequencies per document, document lengths, the
average length and document frequencies in one pass. Scoring a query is a
sum over its (deduplicated) terms. Indexing O(total tokens), each query
O(|Q| * N) here (an inverted index would make it O(postings)), space
O(total tokens).
@param {string[]} docs
@param {string} query
@param {{ k1?: number, b?: number }} [opts]
@returns {number[]}
Why this exists README

I learn best by explaining things, so I record the explanations. Everything here is free, with no sign-up. If a lesson helps you ship something, I'd love to hear about it.