Introduction
The retrieval layer is the single most impactful component of any RAG system, yet most implementations rely on a single retrieval strategy either pure vector search or pure keyword matching. This is like hiring a detective who only looks at fingerprints OR only interviews witnesses, but never both. Hybrid search combines the precision of lexical matching with the semantic understanding of neural embeddings, delivering retrieval quality that neither approach can achieve alone. In enterprise RAG deployments, hybrid search has become the default architecture because real-world queries demand both capabilities: users search for specific identifiers (error codes, clause numbers, product SKUs) AND express conceptual intent ("how do I fix slow performance"). This article presents an enterprise-grade multi-agent LangGraph system that implements hybrid search with adaptive fusion strategies, score normalization, cross-encoder reranking, and persistent memory that learns optimal weighting per query type over time.
What is Hybrid Search in RAG?
Hybrid search is a retrieval strategy that combines two complementary approaches:
Sparse retrieval (BM25/TF-IDF): Matches exact terms using lexical overlap. Represents documents as high-dimensional sparse vectors where each dimension corresponds to a vocabulary term.
Dense retrieval (neural embeddings): Matches semantic meaning using learned vector representations. Represents documents as low-dimensional dense vectors where every dimension carries meaning.
The hybrid pipeline executes both retrievers in parallel, normalizes their scores to a common scale, fuses the results using a combination strategy, and optionally reranks with a cross-encoder for final precision.
Why Hybrid Wins: The Complementarity Principle
Each retrieval method has blind spots that the other covers:
Query Type | Sparse (BM25) | Dense (Vector) | Hybrid |
|---|---|---|---|
"ERR-4042 database timeout" | ✅ Exact match | ❌ May miss code | ✅ BM25 dominates |
"how to fix slow performance" | ❌ No term overlap | ✅ Semantic match | ✅ Dense dominates |
"Section 8.3 indemnification" | ✅ Clause number | ⚠️ Partial | ✅ Both contribute |
"best practices for API security" | ❌ Vague terms | ✅ Conceptual | ✅ Dense dominates |
"SKU-78234 wireless keyboard" | ✅ Exact SKU | ❌ SKU is noise | ✅ BM25 dominates |
In production benchmarks, hybrid search consistently outperforms either method alone by 15-40% on NDCG@10, with the gap widening on mixed-domain corpora.
Fusion Strategies
1. Reciprocal Rank Fusion (RRF): Combines results by rank position, not score. RRF_score(d) = Σ 1/(k + rank_i(d)). Robust to score scale differences. Default choice for most systems.
2. Convex Combination: Weighted sum of normalized scores. final_score = α × sparse_norm + (1-α) × dense_norm. Requires score normalization (min-max or z-score). α can be fixed or learned.
3. Learned Fusion: A classifier (often logistic regression or small neural net) predicts relevance using features from both retrievers. Highest accuracy but requires training data.
4. Cross-Encoder Reranking: After fusion, a cross-encoder model rescores the top-K candidates by jointly encoding query+document. Highest quality but expensive—applied only to the fused top-K.
Step-by-Step Implementation
1. Hybrid Search State Schema with Memory
from typing import List, Dict, Any, TypedDict, Optional, Literal
from langgraph.graph import StateGraph, END
from langchain_core.messages import HumanMessage
import redis
import json
import time
import numpy as np
from datetime import datetime
FusionStrategy = Literal["rrf", "convex", "learned"]
class HybridSearchState(TypedDict):
messages: List
conversation_id: str
query: str
# Preprocessing
normalized_query: str
query_type: str # "exact", "semantic", "mixed"
# Retrieval results (pre-fusion)
sparse_results: List[Dict]
dense_results: List[Dict]
# Normalization
sparse_normalized: List[Dict]
dense_normalized: List[Dict]
# Fusion
fusion_strategy: FusionStrategy
fused_results: List[Dict]
sparse_weight: float
dense_weight: float
# Reranking
reranked_results: List[Dict]
# Metrics
total_latency_ms: float
sparse_latency_ms: float
dense_latency_ms: float
fusion_latency_ms: float
rerank_latency_ms: float
# Memory
historical_weights: Dict[str, List[float]]
successful_strategies: List[Dict]
2. Query Preprocessor Agent
from langchain_openai import ChatOpenAI
import re
class QueryPreprocessorAgent:
"""Normalizes query and classifies type to guide fusion weighting"""
def __init__(self):
self.llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0.0)
def preprocess(self, state: HybridSearchState) -> HybridSearchState:
query = state["query"]
# Detect identifiers (favor sparse)
identifier_patterns = [
r'\b[A-Z]{2,5}-\d{3,6}\b',
r'\b[A-Z]{3,}-[A-Z0-9-]+\b',
r'\b\d{4,}\b',
r'Section\s+\d+',
r'Clause\s+\d+'
]
has_identifiers = any(re.search(p, query) for p in identifier_patterns)
# Detect conceptual terms (favor dense)
conceptual_words = {'how', 'why', 'what', 'best', 'practice', 'optimize',
'improve', 'troubleshoot', 'explain'}
query_words = set(query.lower().split())
has_conceptual = bool(query_words & conceptual_words)
if has_identifiers and has_conceptual:
state["query_type"] = "mixed"
elif has_identifiers:
state["query_type"] = "exact"
elif has_conceptual or len(query.split()) > 5:
state["query_type"] = "semantic"
else:
state["query_type"] = "mixed"
# Normalize: lowercase, remove punctuation but preserve identifiers
state["normalized_query"] = query.strip()
return state
3. Sparse Retriever Agent (BM25)
from rank_bm25 import BM25Okapi
class SparseRetrieverAgent:
"""BM25-based lexical retrieval with timing"""
def __init__(self):
# Sample legal corpus
self.corpus = [
{"id": "contract_001", "title": "MSA - TechCorp Inc",
"content": "Section 8.3 Indemnification. Provider shall indemnify Client against all third-party claims arising from Provider's negligence. Liability cap: $15M aggregate."},
{"id": "contract_002", "title": "MSA - DataFlow LLC",
"content": "Section 8.3 Indemnification. Each party shall indemnify the other against claims arising from breach. No liability cap applies for willful misconduct."},
{"id": "contract_003", "title": "NDA - SecureNet",
"content": "Confidential Information means all non-public data disclosed between parties. Excludes information independently developed or publicly available."},
{"id": "contract_004", "title": "SOW - CloudOps Migration",
"content": "Scope of Work: Migration of on-premise infrastructure to AWS. Timeline: 90 days. Payment: milestone-based, net-30 terms."},
{"id": "err_doc_001", "title": "Error Reference ERR-4042",
"content": "ERR-4042: Database connection timeout after 30s. Resolution: check connection pool, network config, and database server health."},
{"id": "err_doc_002", "title": "Error Reference AUTH-1103",
"content": "AUTH-1103: Invalid credentials. Resolution: reset password via admin console, verify account not locked."},
]
tokenized = [doc["content"].lower().split() for doc in self.corpus]
self.bm25 = BM25Okapi(tokenized)
def retrieve(self, state: HybridSearchState) -> HybridSearchState:
start = time.time()
tokens = state["normalized_query"].lower().split()
scores = self.bm25.get_scores(tokens)
top_k = 10
top_indices = np.argsort(scores)[::-1][:top_k]
results = []
for idx in top_indices:
if scores[idx] > 0:
results.append({
"id": self.corpus[idx]["id"],
"title": self.corpus[idx]["title"],
"content": self.corpus[idx]["content"],
"raw_score": float(scores[idx]),
"source": "sparse"
})
state["sparse_results"] = results
state["sparse_latency_ms"] = (time.time() - start) * 1000
return state
4. Dense Retriever Agent (Vector Search)
from langchain_huggingface import HuggingFaceEmbeddings
from sklearn.metrics.pairwise import cosine_similarity
class DenseRetrieverAgent:
"""Embedding-based semantic retrieval with timing"""
def __init__(self):
self.embeddings = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)
self.corpus = [
{"id": "contract_001", "title": "MSA - TechCorp Inc",
"content": "Section 8.3 Indemnification. Provider shall indemnify Client against all third-party claims arising from Provider's negligence. Liability cap: $15M aggregate."},
{"id": "contract_002", "title": "MSA - DataFlow LLC",
"content": "Section 8.3 Indemnification. Each party shall indemnify the other against claims arising from breach. No liability cap applies for willful misconduct."},
{"id": "contract_003", "title": "NDA - SecureNet",
"content": "Confidential Information means all non-public data disclosed between parties. Excludes information independently developed or publicly available."},
{"id": "contract_004", "title": "SOW - CloudOps Migration",
"content": "Scope of Work: Migration of on-premise infrastructure to AWS. Timeline: 90 days. Payment: milestone-based, net-30 terms."},
{"id": "err_doc_001", "title": "Error Reference ERR-4042",
"content": "ERR-4042: Database connection timeout after 30s. Resolution: check connection pool, network config, and database server health."},
{"id": "err_doc_002", "title": "Error Reference AUTH-1103",
"content": "AUTH-1103: Invalid credentials. Resolution: reset password via admin console, verify account not locked."},
]
texts = [doc["content"] for doc in self.corpus]
self.doc_embeddings = np.array(self.embeddings.embed_documents(texts))
def retrieve(self, state: HybridSearchState) -> HybridSearchState:
start = time.time()
query_embedding = np.array(self.embeddings.embed_query(state["normalized_query"]))
similarities = cosine_similarity(
query_embedding.reshape(1, -1),
self.doc_embeddings
)[0]
top_k = 10
top_indices = np.argsort(similarities)[::-1][:top_k]
results = []
for idx in top_indices:
if similarities[idx] > 0.15:
results.append({
"id": self.corpus[idx]["id"],
"title": self.corpus[idx]["title"],
"content": self.corpus[idx]["content"],
"raw_score": float(similarities[idx]),
"source": "dense"
})
state["dense_results"] = results
state["dense_latency_ms"] = (time.time() - start) * 1000
return state
5. Score Normalizer Agent
class ScoreNormalizerAgent:
"""Normalizes sparse and dense scores to [0, 1] using min-max scaling"""
def normalize(self, state: HybridSearchState) -> HybridSearchState:
# Normalize sparse scores
sparse = state["sparse_results"]
if sparse:
sparse_scores = [r["raw_score"] for r in sparse]
s_min, s_max = min(sparse_scores), max(sparse_scores)
s_range = s_max - s_min if s_max > s_min else 1.0
state["sparse_normalized"] = [
{**r, "norm_score": (r["raw_score"] - s_min) / s_range}
for r in sparse
]
else:
state["sparse_normalized"] = []
# Normalize dense scores
dense = state["dense_results"]
if dense:
dense_scores = [r["raw_score"] for r in dense]
d_min, d_max = min(dense_scores), max(dense_scores)
d_range = d_max - d_min if d_max > d_min else 1.0
state["dense_normalized"] = [
{**r, "norm_score": (r["raw_score"] - d_min) / d_range}
for r in dense
]
else:
state["dense_normalized"] = []
return state
6. Fusion Agent with Multiple Strategies
class FusionAgent:
"""Fuses sparse and dense results using configurable strategy"""
def __init__(self, redis_client: redis.Redis):
self.redis = redis_client
def _select_weights(self, state: HybridSearchState) -> tuple:
"""Select weights based on query type and historical success"""
query_type = state["query_type"]
# Default weights per query type
defaults = {
"exact": (0.75, 0.25),
"semantic": (0.25, 0.75),
"mixed": (0.50, 0.50)
}
sparse_w, dense_w = defaults.get(query_type, (0.5, 0.5))
# Adjust based on historical success (memory-driven)
history = state.get("historical_weights", {}).get(query_type, [])
if len(history) >= 5:
# Use average of last 5 successful weights for this query type
avg_sparse = np.mean([h[0] for h in history[-5:]])
avg_dense = np.mean([h[1] for h in history[-5:]])
sparse_w, dense_w = avg_sparse, avg_dense
return sparse_w, dense_w
def _rrf_fusion(self, sparse: List[Dict], dense: List[Dict], k: int = 60) -> List[Dict]:
"""Reciprocal Rank Fusion"""
doc_scores = {}
for rank, doc in enumerate(sparse):
doc_id = doc["id"]
if doc_id not in doc_scores:
doc_scores[doc_id] = {"doc": doc, "rrf_score": 0.0, "sparse_rank": rank+1, "dense_rank": None}
doc_scores[doc_id]["rrf_score"] += 1.0 / (k + rank + 1)
for rank, doc in enumerate(dense):
doc_id = doc["id"]
if doc_id not in doc_scores:
doc_scores[doc_id] = {"doc": doc, "rrf_score": 0.0, "sparse_rank": None, "dense_rank": rank+1}
else:
doc_scores[doc_id]["dense_rank"] = rank + 1
doc_scores[doc_id]["rrf_score"] += 1.0 / (k + rank + 1)
return sorted(doc_scores.values(), key=lambda x: x["rrf_score"], reverse=True)
def _convex_fusion(self, sparse: List[Dict], dense: List[Dict],
sparse_w: float, dense_w: float) -> List[Dict]:
"""Convex combination of normalized scores"""
doc_scores = {}
for doc in sparse:
doc_id = doc["id"]
if doc_id not in doc_scores:
doc_scores[doc_id] = {"doc": doc, "convex_score": 0.0, "sparse_contrib": 0.0, "dense_contrib": 0.0}
doc_scores[doc_id]["convex_score"] += sparse_w * doc["norm_score"]
doc_scores[doc_id]["sparse_contrib"] = doc["norm_score"]
for doc in dense:
doc_id = doc["id"]
if doc_id not in doc_scores:
doc_scores[doc_id] = {"doc": doc, "convex_score": 0.0, "sparse_contrib": 0.0, "dense_contrib": 0.0}
doc_scores[doc_id]["convex_score"] += dense_w * doc["norm_score"]
doc_scores[doc_id]["dense_contrib"] = doc["norm_score"]
return sorted(doc_scores.values(), key=lambda x: x["convex_score"], reverse=True)
def fuse(self, state: HybridSearchState) -> HybridSearchState:
start = time.time()
sparse_w, dense_w = self._select_weights(state)
state["sparse_weight"] = sparse_w
state["dense_weight"] = dense_w
# Select strategy: RRF for mixed, convex for typed queries
if state["query_type"] == "mixed":
state["fusion_strategy"] = "rrf"
fused = self._rrf_fusion(state["sparse_normalized"], state["dense_normalized"])
state["fused_results"] = [
{
"id": item["doc"]["id"],
"title": item["doc"]["title"],
"content": item["doc"]["content"],
"score": item["rrf_score"],
"sparse_rank": item["sparse_rank"],
"dense_rank": item["dense_rank"],
"sources": ["sparse"] if item["sparse_rank"] and not item["dense_rank"] else
["dense"] if item["dense_rank"] and not item["sparse_rank"] else
["sparse", "dense"]
}
for item in fused[:10]
]
else:
state["fusion_strategy"] = "convex"
fused = self._convex_fusion(
state["sparse_normalized"], state["dense_normalized"],
sparse_w, dense_w
)
state["fused_results"] = [
{
"id": item["doc"]["id"],
"title": item["doc"]["title"],
"content": item["doc"]["content"],
"score": item["convex_score"],
"sparse_contrib": round(item["sparse_contrib"], 3),
"dense_contrib": round(item["dense_contrib"], 3),
"sources": ["sparse", "dense"] if item["sparse_contrib"] > 0 and item["dense_contrib"] > 0 else
["sparse"] if item["sparse_contrib"] > 0 else ["dense"]
}
for item in fused[:10]
]
state["fusion_latency_ms"] = (time.time() - start) * 1000
return state

Join the conversation! Your thoughts help the community grow.