Understand why repeated terms stop adding much score, why long fields are discounted and how to test lexical settings against judged queries.
BM25 ranking: tune term saturation and document length by field
BM25 scores terms within a field
BM25 is a lexical ranking function built from term frequency, document frequency and field length. A query term receives more weight when it is uncommon in the indexed corpus; repeated occurrences in one document help, but their marginal gain shrinks. A length factor limits the advantage of a long document that mentions many terms by chance. The exact implementation depends on the search backend, its analyzer, field mapping and shard statistics. Do not treat a BM25 score as a probability or compare it directly with an embedding cosine score. Fusion calibration needs a separate contract for combining those branches.
Separate title and body behavior
A short title and a long manual chapter should not share an unquestioned relevance policy. A repeated word in the chapter is less surprising than the same word in the title, while a title may contain only three useful tokens. Tune fields separately and establish whether title boosts, body norms and exact identifier fields serve different intents. Field scoring and identifier safety covers the mapping boundary: a serial number belongs in an exact field even when nearby descriptive words use BM25. Otherwise a nearly matching serial can outscore the literal one.
What the two controls actually change
The parameter k1 controls term-frequency saturation. A larger k1 lets repeated appearances continue contributing for longer; a smaller one reaches a plateau sooner. The parameter b controls the strength of field-length normalization, from no length adjustment at zero to full adjustment at one. Both interact with average field length and the analyzer's token stream. If you change stemming, stopwords or synonym expansion, the underlying frequencies and lengths change too. Hold the analyzer fixed while testing k1 and b, then retest after an analyzer revision. Shadow evaluation can expose unintended ranking movement.
Use judged queries, not one convincing result
Build query slices for brief titles, long procedures, rare exact terms, repeated boilerplate and misspelled language. Compare recall at the candidate cutoff, nDCG after ranking and the downstream answer support rate. Repeated footer text can inflate term counts; remove it at extraction or use a separate low-weight field before adjusting k1 to compensate. Watch the rank of a passage that contains the entire answer once versus a long page that repeats one query word many times. Judged labels make the comparison inspectable rather than anecdotal.
Keep the scoring boundary visible
The example below computes a small-corpus BM25 term score so the parameter effect is observable. It is not a substitute for your engine's explain output: production engines may use field-specific norms, shard-local statistics, overlap-token rules or different treatment of query-term frequency. Record the index generation, analyzer revision, field, k1 and b with every experiment. Run the same permissions and filters in both variants. Otherwise a relevance regression may actually be a candidate-set change. If BM25 recall is weak for paraphrases, add a vector branch and judge its contribution; do not force lexical tuning to solve semantic mismatch.
Worked contract
from collections import Counter
from math import log
def bm25_rank(query: str, manuals: dict[str, str],
k1: float = 1.3, b: float = 0.68) -> list[tuple[str, float]]:
if not manuals or k1 <= 0 or not 0 <= b <= 1:
raise ValueError("invalid corpus or BM25 settings")
tokens = {manual_id: text.casefold().split()
for manual_id, text in manuals.items()}
average_length = sum(map(len, tokens.values())) / len(tokens)
query_terms = set(query.casefold().split())
scores = []
for manual_id, words in tokens.items():
counts = Counter(words)
length_factor = 1 - b + b * len(words) / average_length
score = 0.0
for term in query_terms:
document_frequency = sum(term in other for other in tokens.values())
if not document_frequency or not counts[term]:
continue
idf = log(1 + (len(tokens) - document_frequency + .5)
/ (document_frequency + .5))
score += idf * counts[term] * (k1 + 1) / (
counts[term] + k1 * length_factor)
scores.append((manual_id, score))
return sorted(scores, key=lambda item: (-item[1], item[0]))
manuals = {"pump-47": "seal pressure service",
"pump-81": "seal seal seal inventory inventory inventory"}
ranked = bm25_rank("seal pressure", manuals)
assert ranked[0][0] == "pump-47"
assert ranked[0][1] > ranked[1][1]Performance and operating cost
This deliberately small implementation tokenizes T total words in O(T) time and stores O(T) tokens. It scans all N documents for document frequency inside every document/query-term pair, so scoring takes O(N squared times Q plus T) time for Q distinct query terms; sorting adds O(N log N). A real inverted index stores document frequency once and scores only candidate postings. Field norms and postings use storage, while larger candidate windows increase latency. Tune on measured queries before spending search capacity on a larger window.
Common Mistakes
- Treating a BM25 score as a calibrated probability or adding it directly to a vector score.
- Tuning k1 to hide repeated footer text instead of cleaning the indexed field.
- Changing the analyzer and BM25 parameters in the same evaluation run.
- Applying body-field length settings to short titles and exact identifiers without separate tests.
Validation drill
For 83 judged maintenance queries, compare two k1/b pairs while holding tokenization and filters fixed. Report candidate recall at 24, nDCG at 8 and the number of exact identifiers displaced. Inspect at least ten individual ranking explanations before release.
