Say a support team has 50,000 help articles and wants a search box, or a retrieval step for a RAG chatbot, that returns the right article in milliseconds. A popular pure-Python BM25 library works on a sample but slows to a crawl on the full set, and setting up Elasticsearch feels like a lot for one feature.
BM25S is built for this gap. BM25S is an open-source Python library by Xing Han Lù that implements the BM25 ranking function with sparse matrices: it computes every word’s score for every document once, at indexing time, so a search only has to look up and add precomputed numbers. In the author’s benchmarks it answers queries orders of magnitude faster than the rank-bm25 library and faster than Elasticsearch on a single CPU thread, with NumPy as its only required dependency. This guide explains how BM25 scores documents, what BM25S does differently, and runs a working example.
Key Takeaways
- BM25 ranks documents by how often they contain the query’s words, giving more weight to rare words and less to long documents.
- BM25S computes all word-document scores at indexing time and stores them in a sparse matrix, so a query is a fast lookup and sum.
- On the author’s single-thread benchmarks, BM25S reached 573.91 queries per second on the ArguAna dataset, against 2 for rank-bm25 and 13.67 for Elasticsearch.
- BM25S supports five BM25 variants, uses Lucene’s version by default, and can save, load and memory-map indexes.
- Like all keyword search, BM25 misses synonyms and paraphrases, which is why it is often paired with embedding search.
What Is BM25?
BM25 (Best Matching 25) is a ranking function that scores how relevant a document is to a search query based on the query words it contains. It grew out of the Okapi information retrieval system and was introduced by Stephen Robertson and colleagues at the TREC-3 conference in 1994. Three decades later it is still the default ranking in search engines such as Lucene, Elasticsearch and OpenSearch.
BM25 combines three ideas:
- Term frequency. A document that mentions a query word more often scores higher, but with diminishing returns. The parameter
k1(often 1.2 to 2.0) controls how fast the extra mentions stop counting. - Inverse document frequency (IDF). Rare words count more than common ones. Matching “prorated” says more about a document than matching “plan”.
- Length normalization. A long document contains more words by chance, so its score is scaled down. The parameter
b(usually 0.75) controls how strongly.
A document’s score for a query is the sum of these per-word scores over the query words it contains.
What Makes BM25S Different?
Most Python BM25 implementations, such as rank-bm25, compute scores at query time. For every query, they loop over the documents and compute term frequency, IDF and length normalization from scratch. That is simple, but the work grows with the size of the collection on every single query.
BM25S, described in the technical report “BM25S: Orders of magnitude faster lexical search via eager sparse scoring” (2024), moves that work to indexing time. Eager sparse scoring means it computes the full BM25 score of every word in every document once and stores the results in a sparse matrix, with one row per vocabulary word and one column per document. Most entries are zero, because most words do not appear in most documents, so the matrix stays compact.
At query time, BM25S takes the rows for the query’s words and adds them up. That is one sparse-matrix operation in NumPy instead of a Python loop over documents. Recent versions also offer an optional Numba backend for extra speed on large collections.
How Fast Is BM25S?
The BM25S repository reports throughput in queries per second on BEIR benchmark datasets, measured on a single thread of an Intel Xeon CPU at 2.70GHz:
| Dataset | BM25S | Elasticsearch | BM25-PT | rank-bm25 |
|---|---|---|---|---|
| ArguAna | 573.91 | 13.67 | 110.51 | 2 |
| FiQA | 507.03 | 16.96 | 20.52 | 4.46 |
| SciFact | 952.92 | 20.81 | 184.3 | 47.6 |
| NQ | 41.85 | 12.16 | out of memory | 0.1 |
| MS MARCO | 12.2 | 11.88 | out of memory | 0.07 |
Two patterns stand out. The gap with rank-bm25 is largest on big collections, where rank-bm25’s per-query loop is slowest: on NQ, BM25S answers about 400 queries in the time rank-bm25 answers one. And on the biggest collection, MS MARCO, BM25S and Elasticsearch are close, so the advantage over Elasticsearch shrinks as collections grow. These are the author’s measurements, so test on your own data before deciding.
A Working BM25S Example in Python
This example indexes six help-center snippets and runs three queries. It uses BM25S 0.3.15 from PyPI with the optional PyStemmer package for stemming:
pip install bm25s PyStemmer import bm25s
import Stemmer # from the PyStemmer package
corpus = [
"To reset your password, open Settings and choose Security.",
"Invoices are emailed on the first business day of each month.",
"You can export reports as CSV or PDF from the Reports page.",
"Two-factor authentication adds a code from your phone at sign-in.",
"Refunds for annual plans are prorated after the first 30 days.",
"Change your billing email under Settings, then Billing.",
]
stemmer = Stemmer.Stemmer("english")
# Tokenize: lowercase, split into words, drop English stopwords, stem.
corpus_tokens = bm25s.tokenize(corpus, stopwords="en", stemmer=stemmer)
# Index: BM25S computes the score of every word in every document up front.
retriever = bm25s.BM25() # default: Lucene's BM25 variant, k1=1.5, b=0.75
retriever.index(corpus_tokens)
queries = ["how do I change my billing settings", "refund annual plan", "get paid by invoice"]
query_tokens = bm25s.tokenize(queries, stopwords="en", stemmer=stemmer)
docs, scores = retriever.retrieve(query_tokens, corpus=corpus, k=2)
for q, (doc_row, score_row) in enumerate(zip(docs, scores)):
print(f"Query: {queries[q]}")
for doc, score in zip(doc_row, score_row):
print(f" {score:.2f} {doc}") Output (BM25S also prints progress bars, omitted here):
Query: how do I change my billing settings
1.99 Change your billing email under Settings, then Billing.
0.43 To reset your password, open Settings and choose Security.
Query: refund annual plan
1.83 Refunds for annual plans are prorated after the first 30 days.
0.00 Change your billing email under Settings, then Billing.
Query: get paid by invoice
0.65 Invoices are emailed on the first business day of each month.
0.00 Change your billing email under Settings, then Billing. Stemming is doing real work here. “Refund”, “plan” and “invoice” in the queries match “Refunds”, “plans” and “Invoices” in the documents because all are reduced to the same stems (“refund”, “plan”, “invoic”). Without a stemmer, the third query would find nothing.
Checking the Score by Hand
The 1.83 for the refund query can be reproduced with Lucene’s BM25 formula. The collection has 6 documents, and each of the three query words appears in exactly one, so each gets an IDF of ln(1 + 5.5 / 1.5) = 1.540. The refund document has 8 tokens after stopword removal, against an average of 7.83, so each word’s term-frequency part is 1 / (1 + 1.5 × (0.25 + 0.75 × 8 / 7.83)) = 0.396. Each word contributes 1.540 × 0.396 = 0.610, and three words give 1.83.
That arithmetic is exactly what BM25S stores in its sparse matrix during indexing. At query time it only looks up the three 0.610 entries and adds them.
Saving and Loading an Index
For anything beyond a demo, save the index once and reload it, rather than reindexing on every start:
retriever.save("help_index", corpus=corpus)
reloaded = bm25s.BM25.load("help_index", load_corpus=True)
# For very large indexes, memory-map the files instead of loading them into RAM:
# reloaded = bm25s.BM25.load("help_index", mmap=True) The repository’s own test on the Natural Questions dataset (over 2 million documents) shows why memory mapping matters: with the index loaded into memory, RAM use was 4.36 GB, against 0.49 GB with mmap=True, while retrieval took about the same time (21.09 seconds against 20.22).
BM25 Variants and Parameters
BM25S implements five published variants, chosen with the method argument: "robertson" (the original), "atire", "bm25l", "bm25+" and "lucene", the default. The differences are mostly in how IDF is computed and how very long documents are handled. For most projects the default is a sensible choice, since it matches the scoring in Lucene-based search engines and makes results easy to compare.
retriever = bm25s.BM25(method="robertson", k1=1.2, b=0.75) Tune k1 and b only with a set of test queries and known good answers. Without one, you cannot tell whether a change helped.
When BM25S Is Not Enough
BM25 matches words, not meaning. A user who types “get my money back” will not match a document about “refunds” unless the words overlap, and no stemmer fixes that. This is the main reason teams combine BM25 with embedding-based search, which matches by meaning, and merge the two result lists. Our guide to hybrid search for RAG retrieval walks through that setup.
BM25 also works well as the first, fast stage in a larger system: retrieve a few hundred candidates by keyword, then rerank them with a slower, smarter model. The same retrieve-then-rank pattern appears in our article on multi-stage recommender systems.
Finally, BM25S is a library, not a search server. If you need real-time updates to the index, access control, distributed search across machines or a query language, a search engine such as Elasticsearch or OpenSearch is still the right tool.
Back to the Help Center
For the support team with 50,000 articles, BM25S turns the search box into a few lines of Python: tokenize with stemming, index once, save the index and load it at startup. Each query becomes a sparse lookup instead of a loop over every article. If users start searching in their own words rather than the articles’ words, that is the signal to add embedding search next to it, not to replace it.
Frequently Asked Questions
Is BM25S the Same as BM25?
BM25S is an implementation of BM25, not a new ranking function. With the same variant and parameters, it produces BM25 scores; what changes is when and how they are computed. The “S” refers to the sparse matrices it uses to store precomputed scores.
Does BM25S Need a GPU?
No. BM25S runs on a CPU and needs only NumPy. Optional extras add stemming, progress bars and a Numba backend for more speed on large collections.
Can I Use BM25S for RAG?
Yes. BM25S works well as the keyword retriever in a retrieval-augmented generation pipeline, either alone or combined with embedding search. Index your document chunks, retrieve the top results for each question and pass them to the model as context.
How Does BM25S Compare to rank-bm25?
Both are pure-Python BM25 libraries, but rank-bm25 scores documents at query time while BM25S precomputes scores at indexing time. In the author’s benchmarks, that makes BM25S faster on every dataset tested, by factors of hundreds on larger collections.




