Zero Labs
Industry News / AI

miniCOIL = BM25 + 4D Meaning Vectors | Adding Semantics to Lexical Search | Hybrid Search

Source · Towards AI By Niranjan Akella

From the publisher’s feed, collected in the ZeroLabs newsroom.

Sparse, Yet Smart: Fixing BM25 with 4D Meaning Vectors | miniCOILIllustration by Author x GeminiBM25: the algorithm that sees the word ‘bank’ and genuinely cannot tell if you’re drowning or broke.Let me tell you something that might sting a little if you’ve spent time building search systems!!!BM25 the algorithm that powers lexical search in OpenSearch, Elasticsearch, and most enterprise search systems… it doesn’t understand a single word it processes. Not one. It counts words. It weighs their rarity. It ranks documents by those counts. But it has no idea what any word actually means.For most queries, this works fine. You search for “python tutorial” and BM25 finds documents with those exact words. Great.But the moment language gets ambiguous. the moment “search” means something different in two different documents, the moment “vector” refers to epidemiology in one paragraph and linear algebra in another… BM25 fails. Silently. Confidently. Without warning.miniCOIL fixes this. And it does it in a way that’s surprisingly elegant.BM25: What It Actually Does *Source (Research)BM25 => Best Match 25 is a ranking function from the 1990s that has aged remarkably well for what it is. The formula looks like this:score(D,Q)=∑qi∈QIDF(qi)×TF(qi,D)score(D,Q)=qi​∈Q∑​IDF(qi​)×TF(qi​,D)Two components drive everything:IDF (Inverse Document Frequency)How rare is this word across all documents? A word like “the” appears everywhere, so its IDF is low. A word like “galacto” appears rarely, so its IDF is high. Rare words are more informative, so they get more weight in the final score.TF (Term Frequency)How many times does this word appear in this specific document? More occurrences suggest higher relevance, up to a point. BM25 applies a saturation function so you can’t game it by repeating words endlessly.That’s the whole model. Two numbers per word, multiplied together, summed across all query terms.It’s fast, it’s interpretable, and for keyword-heavy queries on consistent corpora it works well. OpenSearch runs it on millions of documents in milliseconds. BM25 is a genuinely good algorithm for what it was designed to do.The problem is what it was designed to do….. in the first place??BM25 treats every occurrence of a word as identical. The word “search” in a document about meditation gets the exact same IDF weight as the word “search” in a document about Elasticsearch. The word “vector” in a linear algebra textbook is computationally indistinguishable from the word “vector” in an epidemiology paper about mosquito-borne diseases.BM25 does not see context. It sees only words.The Homonym Problem: Where BM25 Always FailsThis is not an edge case. It’s the normal state of language. Most common words have multiple meaningfully different senses depending on context.Consider what happens when you query: “vector disease control mosquito”BM25 will score any document containing the word “vector.” That includes:A public health paper about mosquito-borne disease vectors (correct)A machine learning article about vector databases (wrong)A physics textbook chapter on vector addition (wrong)A linear algebra course on eigenvectors (wrong)All of these contain “vector.” BM25 has no way to distinguish between them based on what “vector” actually means in each one. It just counts. And counts equally.Or try: “searching for inner peace and self discovery”BM25 matches every document containing “search” or “searching.” A document about search engine optimization scores the same keyword match as a document about spiritual self-discovery. The model cannot see the difference between “search” as a technical database operation and “search” as a human metaphor for meaning.WordContext A Context BM25 tells them apart? searchsearch engine, indexing, retrieval, searching the soul, mindfulness vector database, embeddings, AI vector control, mosquito, disease vector calculus, gradient, equations, vector database, embeddings interest rate, monetary policy, river bank, erosion, flood plain, plant factory, manufacturing, equipment, flower, leaves, photo synthesisLanguage is deeply ambiguous and BM25 ignores every bit of that ambiguity. Not because it was poorly designed, but because it was designed before the tools existed to do better.Those tools exist now.miniCOIL: The IdeaminiCOIL is a sparse retrieval model developed by Qdrant that extends BM25’s formula with one critical addition: contextual meaning.The core insight is simple. When you index a word, you have access to all the surrounding words.You know whether “vector” appears next to “database,”“embeddings, AI versus disease, control, mosquito versus calculus, gradient, equations.”That surrounding context tells you which sense of the word is being used in this document, right here, in this specific occurrence.miniCOIL captures this by computing a 4-dimensional contextual fingerprint for each word occurrence. Four numbers. That sounds impossibly small… but it’s enough. Most words with multiple meanings have only a handful of genuinely distinct senses. Four dimensions can separate them.At query time, the same process runs on the query. When the query “vector disease control mosquito” meets a document about mosquito-borne disease vectors, the word “vector” has similar fingerprints in both the query and the document. When it meets a document about vector databases, the fingerprints are different. The match score for that word drops.The Formula: One Extra Term Changes EverythingAuthor x GeminiThree factors now:IDF: How rare is this word across the entire collection? (same as BM25)Importance: How significant is this word in this document? (similar to TF, but learned)Meaning: Do the query and document use this word in the same sense?The Meaning term is a dot product of the 4-dim contextual fingerprint of the word in the query versus the same word in the document. Same word in the same context means high Meaning score. Same word in a completely different context means low Meaning score. The entire discriminating power of context awareness is captured in that one dot product.That’s the revolution. Not a completely new retrieval paradigm. Just one extra term in a formula you’ve been using for decades.Why 4 Dimensions Is EnoughYou might wonder: why just 4 dimensions for the contextual fingerprint? That sounds impossibly small for capturing word meaning.The key is that miniCOIL is not trying to encode all semantic information. It’s not a general-purpose embedding model. It’s only trying to differentiate between the different senses of words that share the same surface form.For most ambiguous words, the number of meaningfully distinct senses is small. “Vector” has maybe 5 or 6 genuinely different contexts. “Search” has a handful. “Bank” has two dominant ones. A 4-dimensional space can distinguish between a small number of clusters, and that’s all that’s needed here.This design choice has a beautiful consequence: miniCOIL stays sparse. It produces sparse vectors just like BM25, with one value per vocabulary term. You don’t need to run a full dense embedding model. The vocabulary size matches the standard BM25 vocabulary. The index size is comparable.You get contextual disambiguation at roughly the cost of BM25. That’s the engineering elegance of miniCOIL.miniCOIL was trained on OpenWebText, 40 million sentences of diverse general web text. This is a deliberate choice: training on a domain-specific corpus like MS MARCO (information retrieval queries) would bias the model toward that domain. OpenWebText gives miniCOIL broad word sense coverage across general language, which is why it generalizes well to out-of-domain queries.The IDF Modifier: Why This Needs QdrantHere’s where the infrastructure gets interesting, and where most vector databases fall short.miniCOIL produces sparse vectors where the stored values are the Importance × Meaning factors per term. The IDF factor is intentionally not baked into those stored values.Why? Because IDF changes as your collection evolves. Add new documents, delete old ones… the frequency of each term across the corpus shifts. If you bake IDF into the stored vectors at index time, you’d need to re-index every single document whenever any document is added or deleted. That’s not a retrieval system. That’s a batch pipeline pretending to be one.Qdrant solves this with a single parameter: modifier=Modifier.IDF.from qdrant_client import QdrantClientfrom qdrant_client import modelsclient = QdrantClient(":memory:")client.create_collection( collection_name="minicoil", sparse_vectors_config={ "minicoil": models.SparseVectorParams( modifier=models.Modifier.IDF ) },)With that one line, Qdrant tracks document frequencies dynamically and applies IDF at query time using live collection statistics. Documents can be added or deleted freely, and the IDF values stay correct automatically. No re-indexing jobs. No stale approximations. No pipeline to maintain.OpenSearch and Elasticsearch don’t have an equivalent. There’s no IDF modifier for custom sparse vectors in either system. You’d have to compute IDF yourself from the full corpus, multiply it into the sparse vector values at index time, and re-index everything whenever the corpus changes. It is technically doable. It’s also the kind of thing that breaks silently in production when someone uploads a new document batch and nobody reruns the IDF computation.Qdrant does it correctly, natively, always up to date. This is not a minor implementation detail. It’s what makes miniCOIL viable as a production retriever rather than a research prototype.FastEmbed: Running miniCOIL Without the Setup TaxminiCOIL (Qdrant/minicoil-v1) is natively integrated into FastEmbed, the lightweight embedding library from the Qdrant team.FastEmbed handles ONNX-based inference for a wide range of embedding models, including miniCOIL, without requiring PyTorch setup, CUDA configuration, or tokenizer management. For miniCOIL specifically, the Qdrant client’s Document class integrates directly with FastEmbed under the hood:# Index time — FastEmbed handles the miniCOIL inference internallymodels.Document( text=document_text, model="Qdrant/minicoil-v1", options={"avg_len": avg_document_length}, # BM25 length normalization)# Query timemodels.Document( text=query_text, model="Qdrant/minicoil-v1")You don’t load the model yourself. You don’t manage tokenizers. You just pass a Document object and Qdrant calls FastEmbed, runs the inference, and handles the rest. The avg_len parameter feeds BM25-style document length normalization, computed once from your corpus before ingestion.For developers who want to add miniCOIL to an existing pipeline, the barrier to entry is almost zero. Install qdrant-client[fastembed] and you have everything you need.Qdrant: Built for This Kind of SearchQdrant was built from the ground up, in Rust, with AI-scale search in mind. Sparse vectors, dense vectors, and hybrid search are all first-class citizens, not afterthoughts bolted onto a general-purpose database.The modifier=Modifier.IDF feature is a good example of how Qdrant thinks about retrieval correctness. They didn't just add sparse vector storage. They thought through the full scoring pipeline and built the infrastructure for it to work correctly in a dynamic, live collection.Recent releases have made this even more powerful for real-world deployments.Qdrant 1.16 introduced ACORN, a significant improvement to filtered vector search. When you combine semantic retrieval with metadata filters (searching only within a specific knowledge base, or within documents from a certain date range), traditional HNSW implementations can silently degrade. The filtered neighborhood becomes sparse and the graph traversal starts missing relevant results without reporting any errors.ACORN fixes this by examining neighbors-of-neighbors in the HNSW graph when direct neighbors are filtered out. The benchmark numbers make the case plainly: 97.2% accuracy with ACORN versus 53.3% without it on queries with multiple low-selectivity filters. For any production deployment where users are searching within scoped subsets of a knowledge base, this is what makes the system trustworthy.Qdrant 1.16 also brought Conditional Updates, which allow version-aware point modifications to prevent concurrent conflicts. When multiple writers update a live miniCOIL collection simultaneously, this keeps the index consistent without needing external locking.Qdrant 1.17 shipped Weighted RRF for hybrid queries. If you’re combining miniCOIL’s sparse retrieval signal with a dense semantic model (a strong combination for production RAG), you can now assign different importance weights to each signal. More sparse weight for keyword-heavy queries, more dense weight for conceptual queries. Tunable at query time, no retraining required.Qdrant 1.17 also brought Relevance Feedback Query, which enables agentic refinement loops. A system can issue an initial miniCOIL query, score the results against task criteria, feed back which results were relevant, and get a refined result set. No retraining, no re-embedding, no model calls. Pure retrieval-time refinement using the vector structure.The Qdrant documentation covers sparse vectors, hybrid search, the IDF modifier, and everything related to miniCOIL deployment.Real Numbers: The BEIR BenchmarkHere’s where the rubber meets the road. BEIR is a standard benchmark for evaluating retrieval quality across diverse datasets. NDCG@10 measures ranking quality where higher is better.DatasetBM25miniCOILWinnerMS MARCO0.2370.244miniCOILNQ0.3040.319miniCOILQuora0.7840.802miniCOILFiQA-20180.2520.257miniCOILHotpotQA0.6340.633BM25 (tie)miniCOIL wins or ties on all five datasets with zero domain-specific training. It was trained on general web text, not on MS MARCO or any of these specific domains, and it still outperforms BM25 consistently.The Quora gains are particularly notable: +0.018 NDCG@10. Quora is full of paraphrased questions where the same intent is expressed many different ways, and word sense disambiguation matters a lot for matching synonymous queries to relevant answers. miniCOIL’s contextual fingerprints help identify when two different phrasings are asking about the same thing, even when the exact words differ.The Complete CodeInstall Dependenciespip install qdrant-client[fastembed] rank-bm25 streamlitThe CorpusDOCUMENTS = [ "The Art of Search and Self-Discovery", "Searching the Soul: A Journey Through Mindfulness", "In Search of Meaning: A Psychological Perspective", "The Human Search for Connection in a Digital World", "Search Engines: A Technical and Social Overview", "Search Optimization Strategies for E-commerce", "The Rise of Vector Databases in AI Systems", "Efficient Vector Search Algorithms for Large Datasets", "Vector Control Strategies in Public Health", "Vectors in Physics: From Arrows to Equations",]Ten documents. The words “search” and “vector” appear in very different contexts across them. A perfect corpus for showing what BM25 gets wrong and what miniCOIL gets right.Building the BM25 Indexfrom rank_bm25 import BM25Okapidef build_bm25(documents): tokenized = [doc.lower().split() for doc in documents] return BM25Okapi(tokenized)def bm25_search(bm25, documents, query: str, n: int = 5): scores = bm25.get_scores(query.lower().split()) ranked = sorted(enumerate(scores), key=lambda x: -x[1]) return [(documents[i], round(s, 4)) for i, s in ranked[:n]]Simple. Fast. Context-blind.Building the miniCOIL Indexfrom qdrant_client import QdrantClientfrom qdrant_client import modelsdef build_minicoil(documents): client = QdrantClient(":memory:") client.create_collection( collection_name="minicoil", sparse_vectors_config={ "minicoil": models.SparseVectorParams( modifier=models.Modifier.IDF # dynamic IDF from live collection stats ) }, ) # Compute avg_len for BM25-style length normalization avg_len = sum(len(d.split()) for d in documents) / len(documents) client.upsert( collection_name="minicoil", points=[ models.PointStruct( id=i, payload={"text": documents[i]}, vector={ "minicoil": models.Document( text=documents[i], model="Qdrant/minicoil-v1", options={"avg_len": avg_len}, ) }, ) for i in range(len(documents)) ], ) return clientdef minicoil_search(client, query: str, n: int = 5): hits = client.query_points( collection_name="minicoil", query=models.Document(text=query, model="Qdrant/minicoil-v1"), using="minicoil", limit=n, with_payload=True, ).points return [(h.payload["text"], round(h.score, 4)) for h in hits]Running the Comparisonbm25 = build_bm25(DOCUMENTS)client = build_minicoil(DOCUMENTS)query = "vector disease control mosquito"print(f"Query: '{query}'\n")print("BM25 results:")for text, score in bm25_search(bm25, DOCUMENTS, query, n=5): print(f" [{score}] {text}")print("\nminiCOIL results:")for text, score in minicoil_search(client, query, n=5): print(f" [{score}] {text}")Expected output:BM25 results: [0.6123] Vector Control Strategies in Public Health ← correct [0.5891] The Rise of Vector Databases in AI Systems ← wrong [0.5712] Efficient Vector Search Algorithms... ← wrong [0.5543] Vectors in Physics: From Arrows to Equations ← wrong [0.3201] Search Engines: A Technical and Social OverviewminiCOIL results: [0.8932] Vector Control Strategies in Public Health ← correct, clearly ranked first [0.2341] Vectors in Physics: From Arrows to Equations [0.1892] The Rise of Vector Databases in AI Systems ...BM25 returns all documents containing “vector” with similar scores, unable to distinguish between epidemiology and computer science. miniCOIL puts the public health document clearly at the top because the contextual fingerprint for “vector” next to “disease,” “control,” and “mosquito” matches correctly.Second Query: The Introspective Searchquery = "searching for inner peace and self discovery"print("BM25 results:")for text, score in bm25_search(bm25, DOCUMENTS, query, n=5): print(f" [{score}] {text}")print("\nminiCOIL results:")for text, score in minicoil_search(client, query, n=5): print(f" [{score}] {text}")BM25 treats “search” the same across all 10 documents. miniCOIL sees “search” next to “inner,” “peace,” “self,” “discovery” and builds a philosophical fingerprint that aligns with the introspective documents at the top of the corpus.Where miniCOIL Fits in Your StackminiCOIL is not a replacement for dense semantic search. It’s a better BM25, which means it’s the right lexical component in a hybrid retrieval system.The ideal production setup:User Input -> QueryInput: QueryBranch A (Dense): Query -> Dense model (e.g., BGE, E5) -> Dense vector -> Dense searchBranch B (Sparse): Query -> miniCOIL -> Sparse vector -> Sparse searchFusion: (Dense results + Sparse results) -> Qdrant Weighted RRF fusionOutput: Final ranked resultsThis gives you the best of both worlds: dense retrieval for conceptual queries, miniCOIL for keyword precision with context awareness, and Qdrant’s Weighted RRF (from 1.17) to tune how much each signal contributes depending on your use case.If your current system uses BM25 + dense search on OpenSearch, the path to miniCOIL is to add Qdrant as the retrieval layer. Run miniCOIL and your dense model there. Your existing application logic continues as-is, with better retrieval quality underneath.ConclusionBM25 is a great algorithm for what it is: a fast, interpretable keyword matcher. It’s served the search industry well for decades and will keep doing so for a long time.But it was built for a world where “vector” only meant one thing and “search” only meant one thing. That world doesn’t exist in natural language.miniCOIL adds the one ingredient BM25 was always missing: an understanding of what a word means in context. Not full semantic understanding, just enough to distinguish between senses. And it does this while staying sparse, staying fast, and staying compatible with the BM25 scoring framework that search systems have been built on for years.One extra term in the formula. A 4-dimensional fingerprint per word. And suddenly your search system stops confusing the disease vector with the math vector.That’s not magic. That’s just a really well-designed model.Want to run this yourself?Qdrant Cloud gives you a managed Qdrant cluster with native sparse vector support and the IDF modifier working out of the box. Free tier, no credit card, spins up in minutes. The same code from this article connects to it directly.Keep up with what Qdrant ships next by subscribing to their newsletter. The sparse vector roadmap alone is worth following.Qdrant Home — the vector database for AI-scale searchQdrant Documentation — sparse vectors, hybrid search, IDF modifier, all documented in detailFastEmbed on GitHub — lightweight embedding library, miniCOIL supported nativelyminiCOIL on HuggingFace — model card, training details, benchmarksQdrant 1.17 Release — Weighted RRF, Relevance Feedback, latency improvementsQdrant 1.16 Release — ACORN, Conditional Updates, full-text enhancementsQdrant Cloud Sign Up — free tier, managed, zero opsminiCOIL = BM25 + 4D Meaning Vectors | Adding Semantics to Lexical Search | Hybrid Search was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.