LLM engineering · Medium · 15 min

BM25 by hand: the keyword search that still wins

Embeddings miss part numbers and proper names. BM25 does not: it scores by the rare words shared with the query. Write its two formulas.

DOCS holds five chunks from a workshop's knowledge base, and tokenize(text) already turns them into lower-case words without accents. search(query, docs, k) is written; it lacks the two functions that do the scoring:

idf(term, docsTokens): how much a word weighs. With N documents, n of which contain the term, return Math.log(1 + (N - n + 0.5) / (n + 0.5)). A word found in nearly every document weighs little; one found in a single document weighs a lot.

bm25(queryTokens, docTokens, docsTokens): the score of one document. For each distinct query term that appears tf times in the document, add

idf × tf × (K1 + 1) / (tf + K1 × (1 - B + B × length / averageLength))

where length is the number of words in the document and averageLength the mean over all of them. K1 = 1.2 and B = 0.75 are already defined.

Two effects the challenges check:

  • saturation: ten occurrences are not worth ten times one;
  • length: the same word counts for less in a long document.

Challenges 0/6

  • idf: a rare word weighs more than a common one
  • bm25 of one term: frequency and document length
  • Saturation: ten occurrences are not worth ten times one
  • Length: the same word counts for less in a long document
  • A term repeated in the query counts once
  • The search finds the exact part number and ranks by score

function idf(term, docsTokens) {
  // N = number of documents, n = how many of them contain the term
  // return Math.log(1 + (N - n + 0.5) / (n + 0.5))
  return 1;
}

function bm25(queryTokens, docTokens, docsTokens) {
  // for each distinct query term with tf > 0 in the document, add
  // idf * tf * (K1 + 1) / (tf + K1 * (1 - B + B * docTokens.length / averageLength))
  let score = 0;
  for (const term of new Set(queryTokens)) {
    score += docTokens.filter((t) => t === term).length;
  }
  return score;
}

function search(query, docs, k) {
  const tokens = docs.map((d) => tokenize(d.text));
  const q = tokenize(query);
  return docs
    .map((d, i) => ({ id: d.id, score: bm25(q, tokens[i], tokens) }))
    .filter((r) => r.score > 0)
    .sort((a, b) => b.score - a.score || a.id.localeCompare(b.id))
    .slice(0, k);
}

console.log(search('recambio RX-200', DOCS, 3));

Tab indents, Ctrl+Z undoes. To leave the editor with the keyboard: Esc, then Tab.

Console output appears here (console.log).

Why this matters

Semantic search understands synonyms, but it misses exactly the queries a business makes most: a part number, an order number, a surname. To an embedding model, "RX-200" and "RX-300" are almost the same vector; to BM25 they are different words. That is why Elasticsearch, OpenSearch and the hybrid modes of vector databases still carry this formula inside. Writing it shows you what k1 and b control when you meet them in a configuration. How embeddings behave on Spanish text is measured in best local embedding model for Spanish.

Go deeper: the related guide →

This in production, with your data? Let's talk for 15 minutes →