RAG Hybrid Search Pattern
Combine keyword (BM25) and semantic (vector) search to improve retrieval accuracy in RAG pipelines. Fuse ranked results using reciprocal rank fusion.
Overview
Hybrid search runs BM25 and a vector retriever side by side. BM25 is good at exact strings such as ERR-4021, but it misses paraphrases. Embeddings match meaning, yet can rank a document about the same topic above one containing the exact product code. Combining their ranked lists gives a query two routes to a useful result.
The fusion step uses Reciprocal Rank Fusion (RRF). It compares positions, not raw BM25 and cosine scores, so there’s no need to calibrate the two scales. A document found near the top of both lists gets a stronger fused score than one that appears in only one. The local Chroma RAG recipe shows where this step fits in a runnable pipeline.
When to Use
Use the RAG Hybrid Search Pattern when:
- Your RAG pipeline serves queries that mix exact terms with conceptual language
- Pure semantic search misses specific names, codes, or identifiers users search for
- Pure keyword search fails on paraphrased or reworded questions
- You need higher retrieval precision without retraining embedding models
- Examples: documentation search, product catalogs, internal knowledge bases, legal document retrieval
Skip it when:
- Your corpus is small (a few hundred documents); BM25 alone is usually enough
- Queries are always exact identifiers (order IDs, SKUs); keyword search already wins every time
- Your vector database already supports hybrid search and you don’t need custom fusion logic
- Your latency budget can’t accommodate two searches and the retrievers can’t run in parallel
Solution
The vectors below are fixed demo values, not embeddings for the sample text. Replace them with output from your embedding model before using this pattern with real documents.
Python
import math
from typing import List, Dict
from dataclasses import dataclass
@dataclass
class Document:
id: str
text: str
@dataclass
class SearchResult:
id: str
score: float
def bm25_search(
query: str, documents: List[Document], top_k: int = 10
) -> List[SearchResult]:
"""Simplified BM25 keyword search."""
query_terms = query.lower().split()
scores: Dict[str, float] = {}
doc_count = len(documents)
avg_len = sum(len(d.text.split()) for d in documents) / max(doc_count, 1)
k1, b = 1.5, 0.75
for doc in documents:
doc_terms = doc.text.lower().split()
doc_len = len(doc_terms)
score = 0.0
for term in query_terms:
tf = doc_terms.count(term)
df = sum(1 for d in documents if term in d.text.lower())
idf = math.log((doc_count - df + 0.5) / (df + 0.5) + 1)
score += idf * (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * doc_len / avg_len))
if score > 0:
scores[doc.id] = score
ranked = sorted(scores.items(), key=lambda x: x[1], reverse=True)[:top_k]
return [SearchResult(id=did, score=score) for did, score in ranked]
def vector_search(
query_embedding: List[float],
doc_embeddings: Dict[str, List[float]],
top_k: int = 10,
) -> List[SearchResult]:
"""Cosine similarity vector search."""
def cosine(a: List[float], b: List[float]) -> float:
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(x * x for x in b))
return dot / (norm_a * norm_b + 1e-10)
scores = {
did: cosine(query_embedding, emb)
for did, emb in doc_embeddings.items()
}
ranked = sorted(scores.items(), key=lambda x: x[1], reverse=True)[:top_k]
return [SearchResult(id=did, score=score) for did, score in ranked]
def reciprocal_rank_fusion(
result_lists: List[List[SearchResult]],
k: int = 60,
top_k: int = 10,
) -> List[SearchResult]:
"""Fuse multiple ranked lists using RRF."""
fused: Dict[str, float] = {}
for results in result_lists:
for rank, result in enumerate(results):
fused[result.id] = fused.get(result.id, 0) + 1.0 / (k + rank + 1)
ranked = sorted(fused.items(), key=lambda x: x[1], reverse=True)[:top_k]
return [SearchResult(id=did, score=score) for did, score in ranked]
# Usage
documents = [
Document("d1", "Python async programming with asyncio"),
Document("d2", "JavaScript event loop and promises"),
Document("d3", "Concurrent task execution in Python"),
Document("d4", "Node.js worker threads for CPU tasks"),
]
query = "python async tasks"
bm25_results = bm25_search(query, documents, top_k=5)
query_emb = [0.12, 0.85, 0.33, 0.41]
doc_embeddings = {
"d1": [0.11, 0.82, 0.30, 0.45],
"d2": [0.05, 0.20, 0.71, 0.10],
"d3": [0.13, 0.79, 0.35, 0.38],
"d4": [0.02, 0.15, 0.60, 0.05],
}
vector_results = vector_search(query_emb, doc_embeddings, top_k=5)
hybrid_results = reciprocal_rank_fusion(
[bm25_results, vector_results], k=60, top_k=5
)
for r in hybrid_results:
print(f"{r.id}: {r.score:.4f}")
JavaScript
class Document {
constructor(id, text) {
this.id = id;
this.text = text;
}
}
function bm25Search(query, documents, topK = 10) {
const queryTerms = query.toLowerCase().split(" ");
const scores = {};
const docCount = documents.length;
const avgLen = documents.reduce((s, d) => s + d.text.split(" ").length, 0) / Math.max(docCount, 1);
const k1 = 1.5, b = 0.75;
for (const doc of documents) {
const docTerms = doc.text.toLowerCase().split(" ");
const docLen = docTerms.length;
let score = 0;
for (const term of queryTerms) {
const tf = docTerms.filter(t => t === term).length;
const df = documents.filter(d => d.text.toLowerCase().includes(term)).length;
const idf = Math.log((docCount - df + 0.5) / (df + 0.5) + 1);
score += idf * (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * docLen / avgLen));
}
if (score > 0) scores[doc.id] = score;
}
return Object.entries(scores)
.sort((a, b) => b[1] - a[1])
.slice(0, topK)
.map(([id, score]) => ({ id, score }));
}
function cosineSimilarity(a, b) {
const dot = a.reduce((s, x, i) => s + x * b[i], 0);
const normA = Math.sqrt(a.reduce((s, x) => s + x * x, 0));
const normB = Math.sqrt(b.reduce((s, x) => s + x * x, 0));
return dot / (normA * normB + 1e-10);
}
function vectorSearch(queryEmbedding, docEmbeddings, topK = 10) {
const scores = {};
for (const [id, emb] of Object.entries(docEmbeddings)) {
scores[id] = cosineSimilarity(queryEmbedding, emb);
}
return Object.entries(scores)
.sort((a, b) => b[1] - a[1])
.slice(0, topK)
.map(([id, score]) => ({ id, score }));
}
function reciprocalRankFusion(resultLists, k = 60, topK = 10) {
const fused = {};
for (const results of resultLists) {
results.forEach((result, rank) => {
fused[result.id] = (fused[result.id] || 0) + 1 / (k + rank + 1);
});
}
return Object.entries(fused)
.sort((a, b) => b[1] - a[1])
.slice(0, topK)
.map(([id, score]) => ({ id, score }));
}
// Usage
const docs = [
new Document("d1", "Python async programming with asyncio"),
new Document("d2", "JavaScript event loop and promises"),
new Document("d3", "Concurrent task execution in Python"),
new Document("d4", "Node.js worker threads for CPU tasks"),
];
const query = "python async tasks";
const bm25Results = bm25Search(query, docs, 5);
const queryEmb = [0.12, 0.85, 0.33, 0.41];
const docEmbs = {
d1: [0.11, 0.82, 0.30, 0.45],
d2: [0.05, 0.20, 0.71, 0.10],
d3: [0.13, 0.79, 0.35, 0.38],
d4: [0.02, 0.15, 0.60, 0.05],
};
const vectorResults = vectorSearch(queryEmb, docEmbs, 5);
const hybrid = reciprocalRankFusion([bm25Results, vectorResults], 60, 5);
console.log(hybrid);
Java
import java.util.*;
public class HybridSearch {
record Document(String id, String text) {}
record SearchResult(String id, double score) {}
public static List<SearchResult> bm25Search(
String query, List<Document> documents, int topK) {
String[] queryTerms = query.toLowerCase().split(" ");
Map<String, Double> scores = new HashMap<>();
int docCount = documents.size();
double avgLen = documents.stream()
.mapToInt(d -> d.text().split(" ").length)
.average().orElse(1);
double k1 = 1.5, b = 0.75;
for (Document doc : documents) {
String[] docTerms = doc.text().toLowerCase().split(" ");
int docLen = docTerms.length;
double score = 0;
for (String term : queryTerms) {
long tf = Arrays.stream(docTerms).filter(t -> t.equals(term)).count();
long df = documents.stream()
.filter(d -> d.text().toLowerCase().contains(term))
.count();
double idf = Math.log((docCount - df + 0.5) / (df + 0.5) + 1);
score += idf * (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * docLen / avgLen));
}
if (score > 0) scores.put(doc.id(), score);
}
return scores.entrySet().stream()
.sorted(Map.Entry.<String, Double>comparingByValue().reversed())
.limit(topK)
.map(e -> new SearchResult(e.getKey(), e.getValue()))
.toList();
}
public static List<SearchResult> vectorSearch(
double[] queryEmb, Map<String, double[]> docEmbs, int topK) {
Map<String, Double> scores = new HashMap<>();
for (var entry : docEmbs.entrySet()) {
scores.put(entry.getKey(), cosine(queryEmb, entry.getValue()));
}
return scores.entrySet().stream()
.sorted(Map.Entry.<String, Double>comparingByValue().reversed())
.limit(topK)
.map(e -> new SearchResult(e.getKey(), e.getValue()))
.toList();
}
static double cosine(double[] a, double[] b) {
double dot = 0, normA = 0, normB = 0;
for (int i = 0; i < a.length; i++) {
dot += a[i] * b[i];
normA += a[i] * a[i];
normB += b[i] * b[i];
}
return dot / (Math.sqrt(normA) * Math.sqrt(normB) + 1e-10);
}
public static List<SearchResult> reciprocalRankFusion(
List<List<SearchResult>> resultLists, int k, int topK) {
Map<String, Double> fused = new HashMap<>();
for (List<SearchResult> results : resultLists) {
for (int rank = 0; rank < results.size(); rank++) {
String id = results.get(rank).id();
fused.merge(id, 1.0 / (k + rank + 1), Double::sum);
}
}
return fused.entrySet().stream()
.sorted(Map.Entry.<String, Double>comparingByValue().reversed())
.limit(topK)
.map(e -> new SearchResult(e.getKey(), e.getValue()))
.toList();
}
public static void main(String[] args) {
var docs = List.of(
new Document("d1", "Python async programming with asyncio"),
new Document("d2", "JavaScript event loop and promises"),
new Document("d3", "Concurrent task execution in Python"),
new Document("d4", "Node.js worker threads for CPU tasks")
);
var bm25Results = bm25Search("python async tasks", docs, 5);
var vectorResults = vectorSearch(
new double[]{0.12, 0.85, 0.33, 0.41},
Map.of(
"d1", new double[]{0.11, 0.82, 0.30, 0.45},
"d2", new double[]{0.05, 0.20, 0.71, 0.10},
"d3", new double[]{0.13, 0.79, 0.35, 0.38},
"d4", new double[]{0.02, 0.15, 0.60, 0.05}
),
5
);
var hybrid = reciprocalRankFusion(
List.of(bm25Results, vectorResults), 60, 5);
hybrid.forEach(r -> System.out.printf("%s: %.4f%n", r.id(), r.score()));
}
}
Explanation
BM25 returns one ordered list; vector search returns another. The example keeps each document ID and its position, then adds 1/(k + rank) for every list containing that ID. The code uses zero-based indexes, so +1 makes the first result rank 1. With the default k=60, a document ranked first in both lists scores higher than one appearing near the bottom of just one list.
The fused scores aren’t probabilities. They order candidate documents, and top_k trims the list before the next RAG step. BM25 and cosine similarity use different score scales, so averaging their raw scores can let one retriever dominate. The complete guide to RAG in production covers the surrounding retrieval pipeline, including chunking, indexing, and evaluation.
Variants
| Variant | Description | Use Case |
|---|---|---|
| Weighted RRF | Give keyword and semantic results different weights | When evaluation shows one retriever works better for a domain |
| Score-based fusion | Normalize and combine raw scores instead of ranks | When scores are comparable (same model family) |
| Multi-vector fusion | Fuse results from two or more embedding models | Cross-lingual or multi-modal retrieval |
| Reranker pipeline | Apply a cross-encoder after fusion | When top-result precision matters more than the extra latency |
What Works
- Tune the RRF
kparameter. Lower values (e.g., 20) favor top ranks; higher values (e.g., 100) smooth differences. I start at 60 and change it only when one retriever dominates in evaluation. - Pre-filter candidates. On a large corpus, metadata filters can shrink both candidate sets and reduce compute.
- Cache embeddings. Re-embedding unchanged documents wastes API budget; see embedding caching.
- Use BM25 for structured fields. Product codes, identifiers, and exact names benefit from keyword matching.
- Compare retrieval metrics. Track recall@k and precision@k for BM25, vector search, and the fused list. If fusion loses to either baseline, inspect candidate overlap and the RRF
kvalue. - Index incrementally. Update the BM25 index and vector store separately as new documents arrive.
Common Mistakes
- Using score-based fusion without normalization, causing one search method to dominate
- Ignoring the
kparameter in RRF, which defaults to 60 but may need tuning per dataset - Firing the two searches sequentially instead of in parallel, which doubles latency for zero benefit
- Not deduplicating documents that appear in both result lists before fusion
- Re-embedding the entire corpus when only a few documents change
See Also
- Original Reciprocal Rank Fusion paper (Cormack, Clarke & Buettcher, SIGIR 2009): the original RRF formulation and the k=60 recommendation.
- Elasticsearch hybrid search docs: how a production engine combines full-text and vector retrieval with RRF.
- Complete guide to RAG in production: chunking, indexing, and evaluation around the retrieval step.
Companion files: Runnable Python, JavaScript, and Java examples.
Frequently Asked Questions
Why not just use semantic search for everything?
For a query like ERR_4021, BM25 can match the code directly while vector search still retrieves documents that describe the same error without using that exact string.
How do I choose the RRF k parameter?
The original RRF paper used k=60, which is a sensible starting point. Compare recall@k against the BM25 and vector baselines before changing it. A larger value gives lower-ranked results more influence; a smaller one emphasizes the top of each list.
Can I add another retriever?
Yes. The function accepts a list of ranked result lists. Add a third, such as a knowledge-graph lookup, and RRF includes it in the same sum.
Should I use a reranker on top of hybrid search?
A cross-encoder can improve precision, but it adds a model pass. Use one when the top three or five results feed an LLM and evaluation shows the extra reranking step is worth its latency.
When does weighted RRF help?
Plain RRF gives both lists equal weight. Weighted RRF scales each list's contribution, which helps when evaluation shows one retriever works better for a domain. Legal search may favor keyword results because statute numbers and citations need exact matches. A support chatbot may favor semantic results because users often paraphrase.
My vector database already offers hybrid search. Should I still implement this?
If your database supports hybrid retrieval natively, start there. You avoid maintaining fusion code, and the implementation is tested against that engine's indexes. Build your own when the retrievers live in separate systems or you need custom weights or three-way fusion.
Why not average the raw scores?
BM25 and cosine similarity use different scales. A cosine value of 0.9 isn't comparable to a BM25 score of 12.4, so averaging them can favor whichever retriever returns larger numbers. RRF avoids that by using each document's position instead.
Related Resources
Local RAG Pipeline with ChromaDB and Sentence Transformers
Implement retrieval-augmented generation locally with ChromaDB, sentence-transformers embeddings, and LLM generation without external API dependencies
RecipeStore and Query Embeddings in Pinecone Vector Database
Use Pinecone to store, query, and filter vector embeddings for semantic search with metadata filtering and namespace isolation
RecipeCompare Text Semantic Similarity with OpenAI Embeddings
Generate text embeddings with OpenAI and compute cosine similarity to measure semantic similarity between texts for search, dedup, and clustering
PatternEmbedding Cache Pattern
Cache LLM embeddings to reduce API calls and cost. Store embeddings with a content hash key and serve from cache on repeated inputs.
GuideComplete Guide to RAG in Production
Take RAG to production: chunking strategies, vector store selection, hybrid retrieval, reranking, RAGAS evaluation, and deployment patterns.