AI Agents & LLMsMedium
What are hybrid search and reranking, and why do they improve RAG?
Learning path, stage 3 of 5: RAG and fine-tuning · question 4 of 10Hybrid search runs keyword search (BM25) and vector search together and merges the results, so you catch both exact terms (error codes, names, SKUs) and paraphrases. A reranker, usually a cross-encoder model, then rescores the top ~50 candidates against the query and keeps the best few. Together they usually give much better retrieval than embeddings alone.
Why embeddings alone aren't enough
- Dense vectors are good at meaning but weak on exact tokens. "Error E1042" and "Error E1043" look nearly identical as vectors.
- BM25 is good at exact terms but misses synonyms ("cancel subscription" vs "end my plan").
Merging results
- Reciprocal Rank Fusion (RRF): score = Σ 1/(k + rank) across result lists, with k ≈ 60. It needs no score normalisation, which is why it's popular.
- Weighted score blending is the alternative, but it needs normalised scores.
Reranking
- Bi-encoders (embeddings) encode the query and the doc separately. Fast, used for recall.
- Cross-encoders read query and doc together. Slower but much more precise.
- The usual setup: retrieve the top 50–150 with hybrid search, rerank, keep 5–20 for the prompt.
Sources
Code example
tsx
1// Reciprocal Rank Fusion of keyword and vector results, then rerank.2type Hit = { id: string; text: string };34export function rrf(lists: Hit[][], k = 60): Hit[] {5 const scores = new Map<string, { hit: Hit; score: number }>();6 for (const list of lists) {7 list.forEach((hit, rank) => {8 const cur = scores.get(hit.id) ?? { hit, score: 0 };9 cur.score += 1 / (k + rank + 1);10 scores.set(hit.id, cur);11 });12 }13 return [...scores.values()].sort((a, b) => b.score - a.score).map((s) => s.hit);14}1516declare function bm25Search(q: string, n: number): Promise<Hit[]>;17declare function vectorSearch(q: string, n: number): Promise<Hit[]>;18declare function rerank(q: string, hits: Hit[]): Promise<Hit[]>; // cross-encoder1920export async function hybridRetrieve(query: string) {21 const [kw, vec] = await Promise.all([bm25Search(query, 50), vectorSearch(query, 50)]);22 const fused = rrf([kw, vec]).slice(0, 50);23 return (await rerank(query, fused)).slice(0, 8);24}
To run it: follow the one-time setup guide, add npm i @anthropic-ai/sdk zod pg, save the code as a .ts file and run npx tsx file.ts. Anything marked declare is a part you supply.
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the AI Agents & LLMs set.