Since version 2.5, Milvus has scored keyword relevance with BM25 inside the same engine that holds your dense vectors. It runs raw text through an analyzer, stores the resulting terms as a sparse vector in a dedicated field, and ranks matches with BM25 at query time. With LangChain Milvus (the langchain-milvus package), hybrid search comes from passing a BM25BuiltInFunction alongside a dense embedding model. Milvus then merges the two candidate lists with either Reciprocal Rank Fusion (RRF) or a weighted ranker.
This matters when the query hinges on one exact token. Picture a search for a defect code that returns visually similar images carrying the wrong label: the embeddings worked as designed, but the retrieval was blind to the one token that mattered. Retrieval that is blind to the token that matters quietly corrupts dataset curation.
How Does BM25 Work in Milvus, and How Does Raw Text Become a Sparse Vector?
BM25 (Best Match 25) is a relevance-ranking function designed as an improvement on TF-IDF. It comes from the probabilistic relevance framework, which ranks each document by its estimated probability of being relevant to the query. Two properties set it apart from plain TF-IDF. Term frequency saturates, so one term’s contribution can never pass an asymptotic limit however often the term repeats. A parameter b also sets how strongly document length is normalised, where b = 1 gives full normalisation and b = 0 switches it off.
The scoring function sums over terms that appear in both the query and the document, so a document containing none of the query terms never needs to be scored. That fits sparse vectors naturally: each dimension corresponds to one vocabulary token, and only the tokens present in a document get a non-zero value.
The Milvus pipeline has five stages:
- Raw text input. You insert plain text and query with plain text, and no embedding model is involved.
- Text analysis. An analyzer (a tokenizer plus optional filters) breaks the text into terms.
- BM25 function. A schema-level
Functionturns those terms into a sparse vector written to aSPARSE_FLOAT_VECTORfield. - Storage and indexing. A
SPARSE_INVERTED_INDEXbuilds an inverted structure over the non-zero dimensions. - Scoring. At search time Milvus converts the query text into a sparse vector itself and ranks matches with BM25.
Milvus also updates its corpus statistics (term frequency and inverse document frequency) as data is inserted, so scores follow the collection as it grows. Full-text search integrates the Tantivy search library with a built-in Sparse-BM25 algorithm. One operational detail: the generated sparse field works as an internal index, so you cannot include it in output_fields. You get back the original text and metadata only.
Is a “BM25 embedding” Really an Embedding?
Only loosely. A BM25 sparse vector is a weighted bag of words: each dimension is a specific token, and its weight comes from corpus statistics, not from a trained model. The Milvus documentation still calls these vectors “sparse embeddings”. LangChain’s Milvus integration does the same, naming a class BM25SparseEmbedding.
Sparse vectors come either from statistical techniques or from learned models. Learned sparse models such as SPLADE and BGE-M3 also produce sparse vectors that Milvus can store and search. SPLADE trains term weights with explicit sparsity regularisation while keeping exact term matching and inverted-index efficiency. When you just want something to complement dense semantic search, the Milvus documentation recommends BM25 full-text search over SPLADE because it is simpler. Our judgement is the same: start with BM25, and only bring in a learned sparse model once you have evidence that vocabulary mismatch is costing recall that dense vectors are not already recovering.
There is a practical difference too. With built-in BM25 you leave the sparse field out of your inserts and Milvus generates it. With SPLADE or any other external model, you compute the sparse vectors yourself and supply them.
How Can BM25 over Image Metadata and Annotation Tags Cut Mis-Curated Training Samples?
BM25 helps because sparse vectors match special terms and textual identifiers more predictably. Sparse vectors give more predictable matches on special terms and textual identifiers, while dense vectors are better at semantic understanding. Full-text search complements semantic search, which can overlook precise terms.
So the split between the two is simple. Use BM25 when the query is an identifier or needs an exact match. Use dense vectors when the query describes something (“hairline crack near the weld seam”) and the stored captions may phrase it differently. The SCOUT paper on PayPal’s MCP Hub motivates its hybrid design this way: BM25 matches exact tool names such as create_pull_request, while dense retrieval handles paraphrases. In its worked example, a query naming “Slack” returned nothing from BM25 alone, and the dense branch found the right tool under a different product name.
For dataset curation, treating the vector database as a pure dense-embedding store quietly corrupts the results. Catching this kind of silent regression is reliability engineering work, separate from model accuracy, and part of the computer vision systems TechnoLynx builds and deploys.
How Does Milvus BM25 Work in Practice? A Minimal Pymilvus Example
A minimal BM25 setup needs a text field with an analyzer enabled, a sparse vector field, a BM25 Function linking the two, and a SPARSE_INVERTED_INDEX with metric type BM25. The sketch below follows the pattern in the Milvus documentation, with a dense field added so the same collection can serve hybrid search later.
from pymilvus import MilvusClient, DataType, Function, FunctionType
client = MilvusClient(uri="http://localhost:19530")
schema = client.create_schema()
schema.add_field("id", DataType.INT64, is_primary=True, auto_id=True)
schema.add_field("text", DataType.VARCHAR, max_length=2000, enable_analyzer=True)
schema.add_field("sparse", DataType.SPARSE_FLOAT_VECTOR)
schema.add_field("dense", DataType.FLOAT_VECTOR, dim=768)
schema.add_function(Function(
name="text_bm25",
function_type=FunctionType.BM25,
input_field_names=["text"],
output_field_names=["sparse"],
))
index_params = client.prepare_index_params()
index_params.add_index(
field_name="sparse",
index_type="SPARSE_INVERTED_INDEX",
metric_type="BM25",
params={"inverted_index_algo": "DAAT_MAXSCORE", "bm25_k1": 1.2, "bm25_b": 0.75},
)
index_params.add_index(field_name="dense", index_type="HNSW", metric_type="COSINE")
client.create_collection("labels", schema=schema, index_params=index_params)
# Insert text and dense vectors only; Milvus generates "sparse" itself.
# client.insert("labels", [{"text": "scratch, DC-1042, line 3", "dense": vec}, ...])
res = client.search(
collection_name="labels",
data=["DC-1042 scratch"], # raw text, not a vector
anns_field="sparse",
limit=10,
search_params={"params": {"drop_ratio_search": 0.2}},
output_fields=["text"],
)
Three things are worth noticing. The query is raw text, and the documentation says explicitly not to pass precomputed vectors. You do not supply the sparse field at insert time. And full-text search runs on Milvus Standalone and Distributed but not on Milvus Lite, so a quick prototype on Lite will not work for this feature.
k1, B, Analyzers and drop_ratio_search: What to Tune and What It Costs
BM25 in Milvus has two scoring parameters, both set on the sparse index. bm25_k1 controls term-frequency saturation: the default is 1.2, the recommended range is 1.2 to 2.0, and higher values give repeated terms more weight. bm25_b controls length normalisation within the range 0 to 1, with a default of 0.75. Those defaults match Elasticsearch’s BM25 similarity, which also uses k1 = 1.2 and b = 0.75. Robertson and Zaragoza (2009) report that values around 0.5 < b < 0.8 and 1.2 < k1 < 2 work reasonably well in many settings, while noting that the best values depend on the kind of documents and queries.
For short label strings and tag lists, we would leave the defaults alone at first. Documents that are all a few tokens long give length normalisation little to work with. Treat any published “BM25” result with care as well. Kamphuis et al. (ECIR 2020) document many variants of the scoring function and note that papers often leave out the parameter settings.
The Analyzer Is Where Identifiers Live or Die
By default, BM25BuiltInFunction uses the standard analyzer, which tokenizes on punctuation, and the built-in standard analyzer also applies lowercase filtering. The english analyzer adds English stop words, and its output reduces “simplifies” to simplifi. A custom analyzer combines one tokenizer with filters such as lowercase, stop, length and stemmer, and Milvus offers multi-language analyzers for mixed corpora.
Hyphenated codes, underscores in filenames and version strings are exactly the tokens that punctuation splitting and stemming can mangle, so we would check them with run_analyzer before indexing anything at scale. Analyzers are configured when the collection is created. The TEXT_MATCH filter, a related feature, needs enable_match and builds an extra inverted index that takes additional storage.
Query-Time Knobs
drop_ratio_search sets the share of low-importance terms ignored during search, with values in [0.0, 1.0). For the index, the Milvus documentation recommends DAAT_MAXSCORE (the default) for high k values or many-term queries, and DAAT_WAND for small k or short queries. Short identifier lookups with a small limit fit the DAAT_WAND description, but we would measure on real queries before switching.
How Do I Set up Hybrid Search in Milvus with BM25 and Dense Embeddings, and Should It Fuse with RRF or Weighted Ranking?
Hybrid search in Milvus sends one AnnSearchRequest per vector field and merges the results with a ranker inside hybrid_search. The sparse request takes the raw query text, and every vector field must be indexed and loaded, otherwise the call fails.
from pymilvus import AnnSearchRequest, RRFRanker, WeightedRanker
dense_req = AnnSearchRequest(data=[query_vec], anns_field="dense", param={}, limit=15)
sparse_req = AnnSearchRequest(data=["DC-1042 scratch"], anns_field="sparse", param={}, limit=15)
res = client.hybrid_search(
"labels", [dense_req, sparse_req],
ranker=RRFRanker(60), # or WeightedRanker(0.4, 0.6)
limit=5, output_fields=["text"],
)
In SCOUT, each branch fetching more than the final top-k is deliberate. The SCOUT system retrieves top_k × 3 candidates per branch so that a document ranked 2nd by BM25 but 10th by dense search still reaches the fusion step, accepting a modest amount of extra retrieval work per query. Its reported server-side latency (average 572 ms, P95 936 ms over 1,921 requests) covers schema resolution and response formatting as well as the Milvus hybrid search, so it is not a figure for Milvus alone. The same system falls back to BM25-only search when its embedding API call fails, which preserves partial functionality.
RRF Versus WeightedRanker
| RRFRanker | WeightedRanker | |
|---|---|---|
| Fuses on | Rank position in each list | Normalised scores per path |
| Formula | Sum over lists of 1 / (k + rank) | Scores normalised (typically with arctan) to [0, 1], then weighted |
| Parameter | k: default 60, range (0, 16384), recommended 10 to 100; higher k reduces sensitivity to top ranks |
One weight per request, each in [0, 1] |
| Score-scale problem | Avoided, since BM25’s unbounded scores never meet cosine’s 0 to 1 range | Handled by normalisation, but the weights still need choosing |
| Fits when | No labelled queries, or no reason to favour one path | You want to give each search path an explicit importance weight |
RRF is often described as a parameter-free choice, the SCOUT paper among them, but one study disagrees. Bruch et al. found RRF sensitive to its parameters, and found that a convex combination of lexical and semantic scores beat RRF both in-domain and out-of-domain while needing only a small training set to tune its one parameter. Our reading: start with RRF at k = 60 because it needs no explicit weights, then build a small labelled set of curation queries and test weights against it. Switch only if the weighted ranker wins on your own queries.
How Do I Use Milvus BM25 and Hybrid Search Through Langchain-Milvus?
In LangChain Milvus you pass a BM25BuiltInFunction through the vector store’s builtin_function parameter, next to a dense embedding model. The function is a thin wrapper around the Milvus Function, and it needs no corpus or training from the client because tokenization and statistics are handled on the server.
from langchain_milvus import Milvus, BM25BuiltInFunction
from langchain_openai import OpenAIEmbeddings
vectorstore = Milvus.from_documents(
documents=docs,
embedding=OpenAIEmbeddings(),
builtin_function=BM25BuiltInFunction(), # defaults: input "text", output "sparse"
vector_field=["dense", "sparse"],
connection_args={"uri": "http://localhost:19530"},
drop_old=True,
)
hits = vectorstore.similarity_search(
"DC-1042 scratch on housing", k=5,
ranker_type="weighted", ranker_params={"weights": [0.6, 0.4]},
)
The function’s input_field_names defaults to text and output_field_names to sparse. At query time you pass the query text plus optional top-k and reranker settings, and the store handles both the embedding and the built-in function. The weighted reranking call above follows the LangChain documentation’s own example. For BM25 only, set embedding=None and keep just the built-in function. The analyzer can be customised too. We would do that before the first ingest for any corpus full of codes, for the reasons given in the tuning section.
Older code may use BM25SparseEmbedding, a client-side class constructed from a corpus list and a language. That class takes the corpus from your code, while the built-in function needs no client corpus, keeps statistics on the server and updates them as data arrives. For a collection that grows continuously, as labelled datasets do, the built-in function is the one we would choose. If the store sits under a question-answering chain, the retrieval augmented generation examples and guidance piece covers the generation side. How a vector database adds to end-to-end latency is covered separately.
Should I Use Milvus’s Built-in BM25 or Run Elasticsearch Alongside My Vector Database?
For most production AI infrastructure teams adding keyword recall to a vector store they already run, built-in BM25 is the better default, because it removes a second engine and the fusion code between the two. Milvus’s built-in full-text search removes the need for a separate search engine, and the SCOUT system fuses sparse and dense lists inside Milvus with no external merge step.
The next points come from a Milvus vendor post, so read them as vendor claims. Its comparison of Milvus 3.0 with Elasticsearch says the Milvus BM25 index is about 3× smaller than Elasticsearch’s. It notes that Elasticsearch’s rrf and linear retrievers are Platinum-tier features, while Milvus’s rankers ship in the free build. The same post concedes that Milvus trails on aggregation maturity and fuzzy matching.
| Situation | Lean towards |
|---|---|
| Keyword recall to complement dense search, Milvus already in place | Built-in BM25 |
| Need for in-database rank fusion without paid licensing | Built-in BM25 |
| Heavy faceted aggregations, fuzzy or typo-tolerant matching | Elasticsearch, or keep it alongside |
| Large existing Elasticsearch estate with tuned analyzers and dashboards | Keep Elasticsearch; the migration cost is real |
| Prototyping on Milvus Lite | Built-in BM25 is unavailable in Lite; use Standalone or Distributed |
FAQ
Is BM25 Just TF-IDF?
No, though it uses the same ingredients. Both BM25 and classic TF-IDF scoring use term frequency and inverse document frequency. BM25 adds term-frequency saturation and tunable document-length normalisation on a probabilistic foundation.
What Is Milvus Used For?
Milvus is a vector database for vector similarity search and metadata filtering. Since version 2.5 it also provides BM25 full-text search. That lets one collection serve semantic, keyword and hybrid queries.