Your RAG app has embeddings, a vector database and a reranker. Then a user pastes E-4021 into the chat and gets an answer about some other error code.
Embeddings match meaning. Error codes, SKUs, function names and ticket IDs have no "meaning" to match. They are exact strings, and for exact strings the old tool still wins: BM25 keyword search.
This post shows how to add BM25 to a Python RAG pipeline with bm25s. It is a small library that only needs NumPy and builds an index in milliseconds on a toy corpus. Every code block below comes from a script I actually ran, and every number is either from the bm25s docs/paper or from my own run (labelled).
When keyword search beats embeddings
BM25 is the ranking function from the probabilistic relevance framework (Robertson & Zaragoza, 2009). It scores a document by how often the query terms appear in it, weighted by how rare those terms are across the corpus and adjusted for document length. No training and no GPU.
Reach for it when queries contain:
- Identifiers: error codes (
E-4021), SKUs (RX-220-WHT), order or ticket IDs - Code and config: function names, flags, header names (
X-Signature) - Rare domain terms that your embedding model never saw much of
Embeddings still win on paraphrases ("my money never came back" vs "refund delays"). So you usually want both. More on that below.
Install
python -m venv venv && source venv/bin/activate pip install bm25s PyStemmer At the time of writing PyPI has bm25s 0.3.16 (uploaded 28 Oct 2026 UTC, MIT license per its classifiers, Python >= 3.8). PyStemmer is optional but recommended. The bm25s paper reports that adding a stemmer improves the score on average across BEIR, while stopwords have minimal impact on average. The README also offers pip install "bm25s[core]" if you want the optional extras (stemming, JIT via numba, progress bars).
Step 1: Tokenize and index
My toy corpus is 20 invented support-doc snippets (not real products), stored as dicts so retrieval hands back the id and text together:
import bm25s import Stemmer corpus = [ {"id": "kb-01", "text": "Error E-4012 means the payment gateway timed out. Retry after 30 seconds or switch to UPI."}, {"id": "kb-02", "text": "Error E-4021 appears when the card issuer declines the transaction. Ask the customer to call their bank."}, {"id": "kb-05", "text": "The SKU RX-220-BLK is the black RouterX 220. Firmware updates are installed from the admin panel."}, {"id": "kb-06", "text": "The SKU RX-220-WHT is the white RouterX 220. It ships with the same firmware as the black model."}, # ... 16 more toy snippets ] texts = [d["text"] for d in corpus] stemmer = Stemmer.Stemmer("english") corpus_tokens = bm25s.tokenize(texts, stopwords="en", stemmer=stemmer) retriever = bm25s.BM25(corpus=corpus) # corpus = what retrieve() returns retriever.index(corpus_tokens) You index the tokens, not the dicts. The corpus you pass to BM25(...) is just what comes back for each document ID. The README says retrieval is position-based: corpus[i] is returned for document i, so keep it in the same order as the texts you tokenized.
By default bm25s uses method="lucene" (Lucene's exact BM25). You can switch to robertson, atire, bm25l or bm25+, and set k1 and b.
Step 2: Retrieve top-k
query = "E-4021" q_tokens = bm25s.tokenize(query, stopwords="en", stemmer=stemmer) docs, scores = retriever.retrieve(q_tokens, k=3) for rank in range(docs.shape[1]): print(rank + 1, docs[0, rank]["id"], round(float(scores[0, rank]), 3)) retrieve returns two NumPy arrays of shape (n_queries, k), so index them as docs[0, rank] for a single query. Here is what my toy run returned (top-1 per query):
| Query | Top-1 | Score |
|---|---|---|
E-4021 | kb-02 (the E-4021 doc, not E-4012) | 0.996 |
RX-220-WHT firmware | kb-06 (white SKU), then kb-05 (black) | 3.770 / 2.679 |
how do I reset my password | kb-03 | 4.018 |
card declined by bank | kb-02 | 2.989 |
The stemmer is why "declined" matched "declines". Both become declin.
Step 3: Save and load the index
retriever.save("toy_index", corpus=corpus) reloaded = bm25s.BM25.load("toy_index", load_corpus=True) The folder holds the sparse matrix as .npy files plus params.index.json, vocab.index.json and corpus.jsonl. For big indexes the README shows BM25.load(path, mmap=True). On Natural Questions (2M+ docs) they report RAM after indexing dropping from 4.36 GB in memory to 0.49 GB with memory mapping.
My toy run on CPU (numbers)
All of this is my toy run on CPU (8-core Intel Xeon box, Python 3.13, bm25s 0.3.16, numpy 2.5.5). It is not a benchmark:
- Tokenizing and indexing 20 toy docs: 1.09 ms
- One query: 0.04–0.16 ms
- Synthetic corpus (50,000 random "docs" × 40 words, 100 queries × 4 words, k=10, single thread):
- bm25s: index 1.67 s, 100 queries in 120.2 ms → 832 QPS
- rank_bm25 (
BM25Okapi): index 0.50 s, 100 queries in 3,325.8 ms → 30 QPS - ~28x faster queries with bm25s. Indexing was slower, because bm25s precomputes the scores up front.
The speedup changed between runs (I saw 36x on an earlier run). Random synthetic text is also not real text. For real benchmarks, use the paper: on BEIR datasets bm25s gets over 100x higher throughput than Rank-BM25 on 10 of 14 datasets, and up to 500x (Lù, 2024). The README's single-threaded table lists, for example, 1196.16 QPS for bm25s vs 224.66 for Rank-BM25 and 45.84 for Elasticsearch on nfcorpus. The trick is eager scoring: bm25s computes every possible token-document score while indexing, stores them in a sparse matrix, and at query time just slices and sums.
Step 4: Combine with vector search (hybrid)
BM25 and embeddings make opposite mistakes, so run both and fuse the ranks, not the raw scores. BM25 scores and cosine similarities are on different scales. Reciprocal Rank Fusion (Cormack, Clarke & Büttcher, 2009) adds up 1 / (k + rank) across the lists, with k = 60:
def rrf(ranked_lists, k=60): scores = {} for ranking in ranked_lists: for rank, doc_id in enumerate(ranking, start=1): scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank) return sorted(scores, key=scores.get, reverse=True) bm25_ids = [d["id"] for d, s in zip(docs[0], scores[0]) if s > 0] vector_ids = my_vector_store.search(query, k=10) # your embedding retriever fused = rrf([bm25_ids, vector_ids])[:5] # send these chunks to the LLM Then measure recall@k on real user queries before and after. That is the only number that tells you whether it helped.
Gotchas I hit
- Hyphenated codes get split. The default
token_patternis(?u)\b\w\w+\b. My run turnedE-4021into['4021'](the single-letterEis dropped) andRX-220-WHTinto['rx', '220', 'wht']. Exact matching still worked on my toy set, butRX-220-WHTalso scored the blackRX-220-BLKdoc (2.967 vs 1.906) because they sharerxand220. To keep codes whole, pass the same custom pattern at index and query time:
CODE_PATTERN = r"(?u)\b\w[\w-]*\w\b" bm25s.tokenize(texts, token_pattern=CODE_PATTERN, stopwords="en", stemmer=stemmer) With that pattern the tokens become ['e-4021', 'rx-220-wht', 'hmac-sha256'], and RX-220-WHT returned only kb-06.
Top-k is always full. If only one doc matches, the other slots are filled with score 0.0 docs. A query with no matching words ("kubernetes helm chart") still returned 3 docs, all scoring 0. Filter
score > 0before handing chunks to your LLM.The English stopword list is short.
stopwords="en"is a 33-word list (a, the, is, to...).how,do,myandhasstayed in my queries. Pass your own list if that matters.Same tokenizer settings everywhere. The stemmer, stopwords and token_pattern must match between indexing and querying, or terms silently stop matching.
Return shapes. Results are 2-D arrays, even for one query, so use
docs[0, i]and notdocs[i].JAX users: the README notes that if JAX is installed, importing bm25s runs a small JAX op that can preallocate GPU memory. Set
XLA_PYTHON_CLIENT_PREALLOCATE=falsebefore importing.
Takeaway
If your RAG app ever sees error codes, SKUs or function names, add a BM25 retriever next to your vectors. With bm25s that takes about ten lines, a pip install and no extra service. Fuse the two lists with RRF and check recall on real queries.
What exact-match queries does your RAG pipeline get wrong today?
References
- bm25s GitHub README: https://github.com/xhluca/bm25s
- bm25s on PyPI (0.3.16, MIT): https://pypi.org/project/bm25s/
- Xing Han Lù (2024), BM25S: Orders of magnitude faster lexical search via eager sparse scoring, arXiv:2407.03618: https://arxiv.org/abs/2407.03618
- Robertson & Zaragoza (2009), The Probabilistic Relevance Framework: BM25 and Beyond, Foundations and Trends in IR 3(4): https://doi.org/10.1561/1500000019
- Cormack, Clarke & Büttcher (2009), Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods, SIGIR: https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf
- rank_bm25 (comparison baseline): https://github.com/dorianbrown/rank_bm25
