The Retrieval-Augmented Generation (RAG) landscape has rapidly evolved from simple keyword matching to sophisticated semantic understanding. However, pure dense vector search often falls short when exact keyword matches are crucial, while traditional sparse search (like BM25) lacks the contextual understanding of modern LLMs. The solution? Hybrid Search.
Milvus, the world's leading open-source vector database, has introduced robust support for sparse vectors, enabling developers to combine the precision of keyword matching with the recall power of semantic embeddings. This guide explores how to leverage both sparse and dense vectors in Milvus to build a highly accurate Multi-Modal RAG system.
Why Hybrid Search is the Game Changer
In a standard RAG pipeline, you retrieve documents based on semantic similarity (dense vectors). While effective for conceptual queries like "how to improve customer retention," it often fails on specific proper nouns, error codes, or unique technical terms. Conversely, sparse vectors (often generated by BM25 or SPLADE) excel at exact matches but miss the "vibe" of the question.
By combining these two approaches, Milvus allows you to score results based on both signals. The retrieval engine returns documents that are semantically relevant and contain the specific keywords the user typed. This dual approach significantly reduces hallucinations and improves citation accuracy.
Implementation Strategy in Milvus
Setting up hybrid search in Milvus involves creating a collection schema that includes both `DenseVector` and `SparseVector` fields. Below is a practical example using the Milvus Python SDK.
from pymilvus import (
connections,
FieldSchema, CollectionSchema, DataType,
Collection, utility
)
# Connect to Milvus
connections.connect(alias="default", host="localhost", port="19530")
# Define Schema with both Dense and Sparse fields
fields = [
FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=True),
FieldSchema(name="dense_embedding", dtype=DataType.FLOAT_VECTOR, dim=768),
FieldSchema(name="sparse_embedding", dtype=DataType.SPARSE_FLOAT_VECTOR),
FieldSchema(name="text", dtype=DataType.VARCHAR, max_length=1000)
]
schema = CollectionSchema(fields=fields, description="Hybrid RAG Collection")
collection = Collection("hybrid_rag", schema)
# Create Indexes
collection.create_index(
field_name="dense_embedding",
index_params={
"metric_type": "IP",
"index_type": "HNSW",
"params": {"M": 16, "efConstruction": 200}
}
)
# Note: Sparse vectors typically use an inverted index
collection.create_index(
field_name="sparse_embedding",
index_params={
"metric_type": "IP",
"index_type": "SPARSE_INVERTED_INDEX"
}
)
Executing Hybrid Queries
The magic happens during the query phase. Milvus supports the hybrid_search method, which allows you to pass multiple search requests and combine them using a Ranker. The RRFRanker (Reciprocal Rank Fusion) is often the best starting point as it merges result lists based on rank rather than raw scores, which can be normalized differently between sparse and dense methods.
from pymilvus import AnnSearchRequest, RRFRanker
import numpy as np
# Assume 'dense_query_vec' is your 768-dim embedding
# Assume 'sparse_query_dict' is your sparse vector dict (e.g., {token_id: weight})
dense_search_params = {
"data": [dense_query_vec],
"anns_field": "dense_embedding",
"param": {"metric_type": "IP", "params": {"ef": 100}},
"limit": 50,
"expr": ""
}
dense_req = AnnSearchRequest(dense_search_params, "dense_embedding", "dense_embedding")
sparse_search_params = {
"data": [sparse_query_dict],
"anns_field": "sparse_embedding",
"param": {"metric_type": "IP", "params": {}},
"limit": 50,
"expr": ""
}
sparse_req = AnnSearchRequest(sparse_search_params, "sparse_embedding", "sparse_embedding")
ranker = RRFRanker(k=60)
res = collection.hybrid_search(
reqs=[dense_req, sparse_req],
ranker=ranker,
limit=10,
output_fields=["text"]
)
for hit in res[0]:
print(f"Score: {hit.score:.4f} | Text: {hit.entity.get('text')[:50]}...")
Optimization Tips for Production
- Embedding Quality: Ensure your dense vectors come from a state-of-the-art model like BGE-Large or Sentence-Transformers. For sparse, consider using a modern learned sparse model like SPLADE rather than basic TF-IDF for better semantic coverage.
- Ranker Weighting: While RRF is robust, you can also use weighted combinations if you find one signal is consistently better for your domain. However, RRF is usually "set and forget."
- Partitioning: If your dataset is massive, partition by document type or date to reduce search latency, as hybrid search involves two separate lookups.
Conclusion
Multi-Modal RAG systems that rely solely on dense vectors are leaving performance on the table. By integrating sparse vectors into your Milvus pipeline, you create a retrieval layer that understands both the "meaning" and the "words" of the user's query. With Milvus's native support for hybrid search and flexible ranking strategies, implementing this powerful architecture is now more accessible than ever. Start small, test your ranking strategies, and watch your RAG accuracy soar.