21.1 Hybrid Search (Recommended Default)
Combine dense vector search with sparse keyword search (BM25):
Final Score = α × vector_similarity + (1 - α) × BM25_score
Particularly effective for domain-specific acronyms, exact numbers/dates, code search (variable/function names), and multi-language queries where BM25 catches transliterated terms that embeddings may miss.
Reciprocal Rank Fusion (RRF) — combine rankings from multiple retrievers without needing to tune a weighting hyperparameter:
RRF_score(d) = Σ 1 / (k + rank_i(d)) where k = 60 (constant)
21.2 Multi-Query Retrieval
LLM generates 3-5 variant phrasings of the user query; retrieve for each, de-duplicate, and merge — captures different facets of the underlying information need.
Original query: "What are the security implications of deploying LLMs?"
Generated variants:
1. "LLM deployment security risks and vulnerabilities"
2. "How to secure large language model applications"
3. "Data privacy concerns in GenAI deployment"
4. "Security best practices for AI systems in production"
21.3 HyDE (Hypothetical Document Embeddings)
Query: "What is the company's return policy?"
Step 1: LLM generates a hypothetical answer:
"Our return policy allows customers to return items within 30 days of
purchase for a full refund. Items must be in original condition..."
Step 2: Embed the hypothetical answer (not the raw query)
Step 3: Search the vector DB using that embedding
Why it works: a hypothetical answer is closer in embedding space to actual
documents than a short query is — bridges the query-document length/style gap.
21.4 Parent Document Retrieval
Index small chunks for precise matching, but return the parent (larger) chunk to the LLM for full context — balances retrieval precision against generation context sufficiency.
21.5 Contextual Compression
After retrieval, use an LLM to extract only the relevant portions of each retrieved chunk, reducing noise passed to the generation LLM.
21.6 Self-Query Retrieval
LLM extracts structured filters directly from the natural-language query:
"Find sales reports from Q3 2024"
→ metadata filter: {type: "sales_report", date_range: "2024-07-01 to 2024-09-30"}
21.7 Re-Ranking
Initial retrieval: Top-100 from vector search (fast, broad recall)
▼
Re-ranking: Score each of top-100 with a cross-encoder (slow, precise)
▼
Final: Top-5 re-ranked results → passed to LLM
| Re-Ranker | Type | Quality | Speed |
|---|---|---|---|
| Cohere Rerank | API | Excellent | Fast (API call) |
| BGE-reranker-v2 | Open-source | Very Good | Medium (self-host) |
| ColBERT v2 | Open-source | Excellent | Fast (pre-computed) |
| FlashRank | Open-source | Good | Very fast |
| LLM-based | LLM scoring | Best | Slowest, most expensive |
from sentence_transformers import CrossEncoder
reranker = CrossEncoder('cross-encoder/ms-marco-MiniLM-L-6-v2')
def retrieve_and_rerank(query, top_k=20, final_k=5):
candidates = vector_db.search(query, top_k=top_k) # Broad recall
pairs = [(query, doc.text) for doc in candidates]
scores = reranker.predict(pairs) # Precision re-score
ranked = sorted(zip(candidates, scores), key=lambda x: x[1], reverse=True)
return [doc for doc, score in ranked[:final_k]]
21.8 Contextual Retrieval (Advanced)
Prepend a short LLM-generated context summary to each chunk before embedding (describing where the chunk sits within the broader document) — significantly improves retrieval when chunks lack sufficient standalone context (e.g., a chunk that says “the fee is $50” without stating which fee). Reported to give 20-30% retrieval improvement in some implementations.
Section 21 — Interview Q&A
Q: Your RAG system has 60% answer accuracy. Walk through your debugging process. A: First classify failure modes on a sample of ~50 failed queries into four buckets: (A) retrieval failure — the relevant doc wasn’t retrieved at all; (B) ranking failure — it was retrieved but ranked too low to make the cut; © generation failure — correct context was provided but the LLM produced the wrong answer; (D) knowledge gap — the answer simply isn’t in the corpus. Then fix by dominant failure mode. If (A) dominates: check indexing correctness, test whether similar chunks are actually close in embedding space, try a different chunking strategy (chunks may be too large and diluting relevance), add hybrid search if missing, add query expansion/HyDE. If (B) dominates: add a re-ranking stage, tune the hybrid-search alpha weighting, increase initial retrieval K before re-ranking, add recency/metadata-based boosting. If © dominates: tighten the system prompt, reduce context noise (fewer but higher-quality chunks), add an explicit “if unsure, say so” instruction, or upgrade to a more capable generation model. If (D) dominates: expand the corpus, make “I don’t have this information” a valid response, and route unanswerable queries to a human expert.
Q: When does hybrid search outperform pure vector search, and how do you combine the two result sets?
A: Hybrid search wins whenever the query contains terms that need exact matching rather than semantic similarity — domain-specific acronyms, product codes, exact numbers/dates, or code identifiers — because dense embeddings can conflate semantically-similar-but-lexically-different terms in ways that lose precision on these exact-match cases. I combine dense (vector) and sparse (BM25) result sets using Reciprocal Rank Fusion, which sums 1/(k + rank) across each retriever’s ranked list — this avoids having to hand-tune a weighting coefficient (as a plain weighted-score fusion would require) and is robust across query types.