Two halves, multiplied
The first half says how much a term is used in this document. The second says how unusual the term is across all documents.
A word only scores highly if it is frequent here and rare elsewhere, which is a reasonable definition of "what this document is about".
Term frequency
- : the raw count of term in document .
Dividing by the document's length stops long documents from outscoring short ones on every term.
The log variant is often used instead, because a word appearing twenty times is not twenty times more indicative than one appearing once.
Inverse document frequency
- : total number of documents.
- : how many of them contain .
A term in every document has , so the log is zero and the term contributes nothing. That is how "the" is removed without a stopword list.
A term in one document out of a million scores .
The smoothed form is what libraries actually use.
The inner stops division by zero for a term in the query but not the corpus, and the trailing one keeps a universal term off exactly zero.
Why the logarithm
Without it, rarity would scale linearly and a term appearing in 1 document would be a thousand times more important than one in 1000.
The log compresses that to a factor of about 3, which matches how usefulness actually behaves: rare is good, vanishingly rare is often just a typo.
One document, in order
- Tokenise and count terms.
- Divide each count by the document length, or take its log.
- Look up each term's document frequency across the corpus.
- Multiply the two halves.
- Normalise the resulting vector to unit length, so cosine similarity behaves.
What it cannot do
Every term is its own dimension, so "car" and "automobile" are as unrelated as "car" and "banana". There is no notion of meaning anywhere in it.
It also cannot match a query whose words do not literally appear, which is the exact gap dense retrieval fills, and the exact reason hybrid search keeps both.
BM25 is the direct descendant and the better default: same two halves, with term frequency saturating and document length handled properly.