What you should know first: read Part 11: RAG Fundamentals and Part 12: Document Loading and Chunking. You need Python 3.10+ or Node.js 20+. The keyword search and fusion examples need no API key and no downloads.
In Part 12 our test showed something worrying: sometimes the retriever picks the wrong chunk, and then even the best LLM gives a wrong answer. In this post you will fix that with three upgrades that real RAG systems use every day. Hybrid search runs keyword search (BM25) and vector search together and merges the results, so you catch both exact words like error codes and similar meanings like “money back” = “refund”. Re-ranking uses a second, more careful model to put the best chunk on top. Query rewriting turns vague or follow-up questions into clear search queries. You will build each one in Python and Node.js, step by step.
- Vector search understands meaning but can miss exact words (error codes, product names). Keyword search (BM25) finds exact words but misses synonyms.
- Hybrid search runs both and merges the two ranked lists, usually with Reciprocal Rank Fusion (RRF): score = sum of 1 / (60 + rank).
- Re-ranking: take the top 20–50 results and let a cross-encoder score each (question, chunk) pair. Slower, but much more accurate.
- Query rewriting: let an LLM turn “what about it?” into a full question, create several search queries (multi-query) or write a fake answer to search with (HyDE).
- Good order: rewrite → hybrid search (wide) → re-rank (narrow) → send the top 3–5 chunks to the LLM. Measure each step with your test questions.
Full Generative AI roadmap (30 parts)
Beginner
- What Is Generative AI and How Do LLMs Work?
- Tokens, Context Windows and Model Parameters
- Your First LLM API Calls in Python and Node.js (OpenAI, Anthropic, Gemini)
- Prompt Engineering Basics: Roles, Instructions and Examples
- Temperature, Top-p and Controlling Model Output
- Run LLMs Locally with Ollama
- Streaming Responses and Building a Simple Chat UI
- Structured Outputs: Getting Reliable JSON from LLMs
Intermediate
- Embeddings Explained: Turning Text into Vectors
- Vector Databases: pgvector, Chroma and Pinecone
- RAG Fundamentals: Retrieval-Augmented Generation
- Document Loading and Chunking Strategies
- Better RAG: Hybrid Search, Re-ranking and Query RewritingYou are here
- Function Calling and Tool UseComing soon
- Conversation Memory and Long Context ManagementComing soon
- Multimodal AI: Vision, Images and Audio InputsComing soon
- How Image Generation Works: Diffusion Models BasicsComing soon
- LangChain vs LlamaIndex: When to Use a FrameworkComing soon
- Testing LLM Apps: Evals, Metrics and Test SetsComing soon
- Cutting Cost and Latency: Caching, Batching and Model ChoiceComing soon
Advanced
- Fine-Tuning vs Prompting vs RAG: Choosing the Right ToolComing soon
- Fine-Tuning an Open Model with LoRAComing soon
- Transformers Deep Dive: Attention Explained SimplyComing soon
- Reasoning Models and Thinking TimeComing soon
- Guardrails, Safety and Prompt Injection DefenceComing soon
- Monitoring and Tracing LLM Apps in ProductionComing soon
- Serving Open Models: vLLM, Quantization and GPUsComing soon
- Building a Production GenAI App End to EndComing soon
- Responsible AI: Privacy, Licensing and BiasComing soon
- Final Project: Build Your Own AI Knowledge AssistantComing soon
Why basic RAG retrieval misses
The RAG app from Part 11 used only vector search: turn the question into an embedding and return the chunks whose embeddings are closest. That works well for questions phrased in normal language. But it has blind spots:
- Exact words get blurred. An embedding stores the meaning of a text, not its exact letters. “Error E-1042” and “Error E-1024” look almost the same to an embedding model, but they are two different problems for your users.
- Rare names and new terms. Product names, function names, invoice numbers or internal team words may not mean anything to the embedding model.
- Vague questions. “Can I still do that?” has no useful meaning on its own. The real question is hidden in the chat history.
- Close-but-wrong chunks. The top result is often about the right topic but does not contain the answer, while the chunk with the answer sits at position 6.
Keyword search has the opposite problem: it finds exact words perfectly, but a user who writes “money back” will not match a chunk that only says “refund”. The good news: these two methods fail in different places, so combining them works much better than either one alone.
Keyword search with BM25
BM25 (“Best Matching 25”) is the classic keyword ranking formula used by search engines like Elasticsearch, OpenSearch and Lucene. You do not need to memorise the maths. It follows three simple ideas:
k1 setting controls this.b setting controls this.We will use the same small help-centre knowledge base for every example in this post. Save it as docs.json:
[
{"id": "refund-1", "text": "Refund policy: you can ask for a full refund within 14 days of buying DevDojo Pro."},
{"id": "refund-2", "text": "After 14 days money back is not possible, but you can pause your plan for one month."},
{"id": "billing-1", "text": "To cancel your subscription, open Settings, then Billing, and click Cancel plan."},
{"id": "pay-1", "text": "Error E-1042 means the bank declined your payment card. Try another card or pay with UPI."},
{"id": "pay-2", "text": "We accept UPI, credit cards, debit cards and net banking for all payments."},
{"id": "mentor-1", "text": "Mentors review your project and reply within 48 hours on weekdays."},
{"id": "cert-1", "text": "You get a certificate after you finish all lessons and the final project."},
{"id": "support-1", "text": "Support chat is open from 10 AM to 7 PM IST, Monday to Saturday."}
]
Now a complete BM25 search in about 30 lines, with no libraries. Click the tabs to switch between Python and Node.js, and click ▶ Run to see the real output:
import json, math, re
from collections import Counter
STOP = {"a", "an", "the", "is", "are", "to", "of", "and", "or", "for", "you", "your", "my", "i", "can", "how", "do", "what", "with", "on", "in", "after", "all", "get"}
def tokenize(text):
return [w for w in re.findall(r"[a-z0-9]+(?:-[a-z0-9]+)*", text.lower()) if w not in STOP]
class BM25:
def __init__(self, docs, k1=1.5, b=0.75):
self.docs = docs
self.toks = [tokenize(d["text"]) for d in docs]
self.avg_len = sum(len(t) for t in self.toks) / len(self.toks)
df = Counter(w for t in self.toks for w in set(t))
n = len(docs)
self.idf = {w: math.log(1 + (n - f + 0.5) / (f + 0.5)) for w, f in df.items()}
self.k1, self.b = k1, b
def score(self, query, i):
tf, dl = Counter(self.toks[i]), len(self.toks[i])
s = 0.0
for w in tokenize(query):
if w in tf:
f = tf[w]
s += self.idf[w] * f * (self.k1 + 1) / (f + self.k1 * (1 - self.b + self.b * dl / self.avg_len))
return s
def search(self, query, k=3):
scored = [(self.score(query, i), d["id"]) for i, d in enumerate(self.docs)]
return [(doc_id, round(s, 2)) for s, doc_id in sorted(scored, reverse=True)[:k] if s > 0]
if __name__ == "__main__":
docs = json.load(open("docs.json"))
bm25 = BM25(docs)
for q in ["error E-1042", "can I get my money back?", "how do I get a refund"]:
print(f"{q!r:28} -> {bm25.search(q)}")
$ python bm25_search.py
'error E-1042' -> [('pay-1', 3.23)]
'can I get my money back?' -> [('refund-2', 3.37)]
'how do I get a refund' -> [('refund-1', 2.45)]import { readFileSync } from "node:fs";
const STOP = new Set(["a", "an", "the", "is", "are", "to", "of", "and", "or", "for", "you", "your", "my", "i", "can", "how", "do", "what", "with", "on", "in", "after", "all", "get"]);
const tokenize = (text) =>
(text.toLowerCase().match(/[a-z0-9]+(?:-[a-z0-9]+)*/g) ?? []).filter((w) => !STOP.has(w));
function buildBM25(docs, k1 = 1.5, b = 0.75) {
const toks = docs.map((d) => tokenize(d.text));
const avgLen = toks.reduce((sum, t) => sum + t.length, 0) / toks.length;
const df = new Map();
for (const t of toks) for (const w of new Set(t)) df.set(w, (df.get(w) ?? 0) + 1);
const idf = (w) => Math.log(1 + (docs.length - df.get(w) + 0.5) / (df.get(w) + 0.5));
return function search(query, k = 3) {
const results = docs.map((d, i) => {
const counts = new Map();
for (const w of toks[i]) counts.set(w, (counts.get(w) ?? 0) + 1);
let score = 0;
for (const w of tokenize(query)) {
const f = counts.get(w);
if (!f) continue;
score += idf(w) * (f * (k1 + 1)) / (f + k1 * (1 - b + (b * toks[i].length) / avgLen));
}
return [d.id, Number(score.toFixed(2))];
});
return results.filter(([, s]) => s > 0).sort((x, y) => y[1] - x[1]).slice(0, k);
};
}
const docs = JSON.parse(readFileSync("docs.json", "utf8"));
const search = buildBM25(docs);
for (const q of ["error E-1042", "can I get my money back?", "how do I get a refund"]) {
console.log(JSON.stringify(q).padEnd(28), "->", JSON.stringify(search(q)));
}
$ node bm25_search.mjs
"error E-1042" -> [["pay-1",3.23]]
"can I get my money back?" -> [["refund-2",3.37]]
"how do I get a refund" -> [["refund-1",2.45]]Tip: click the PY / JS tabs and then ▶ Run. This output is from a real run.
Look at the second query. “can I get my money back?” found refund-2 (it contains “money back”) but missed refund-1, the chunk that actually says you get a full refund within 14 days. That is the synonym problem, and it is exactly where vector search helps.
pip install rank-bm25 gives you BM25Okapi with the same idea. Writing it yourself once helps you understand what the scores mean.Hybrid search with Reciprocal Rank Fusion (RRF)
Hybrid search means: run keyword search and vector search for the same question, then merge the two result lists into one. The tricky part is merging. BM25 scores might be 3.37 while cosine similarities are 0.82, so you cannot simply add them. The most popular fix is Reciprocal Rank Fusion (RRF), introduced in a 2009 paper by Cormack, Clarke and Büttcher. RRF ignores the raw scores and only looks at positions:
RRF score(chunk) = ∑ 1 / (k + rank), with k = 60 by default
A chunk ranked #1 in a list gets 1/61, #2 gets 1/62, and so on. A chunk that appears in both lists adds both numbers together, so chunks that both searches like rise to the top.
RRF is only a few lines of code:
def reciprocal_rank_fusion(rankings, k=60):
"""rankings: lists of doc IDs, best first. Returns IDs sorted by fused score."""
scores = {}
for ranking in rankings:
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1 / (k + rank)
return sorted(scores.items(), key=lambda item: item[1], reverse=True)
if __name__ == "__main__":
# Query: "can I get my money back?"
keyword_hits = ["refund-2"] # BM25 (real result above)
vector_hits = ["refund-1", "refund-2", "billing-1"] # embeddings (example ranking)
for doc_id, score in reciprocal_rank_fusion([keyword_hits, vector_hits]):
print(f"{doc_id:10} {score:.4f}")
$ python rrf.py
refund-2 0.0325
refund-1 0.0164
billing-1 0.0159function reciprocalRankFusion(rankings, k = 60) {
const scores = new Map();
for (const ranking of rankings) {
ranking.forEach((docId, i) => {
scores.set(docId, (scores.get(docId) ?? 0) + 1 / (k + i + 1));
});
}
return [...scores].sort((a, b) => b[1] - a[1]);
}
// Query: "can I get my money back?"
const keywordHits = ["refund-2"]; // BM25 (real result above)
const vectorHits = ["refund-1", "refund-2", "billing-1"]; // embeddings (example ranking)
for (const [docId, score] of reciprocalRankFusion([keywordHits, vectorHits])) {
console.log(docId.padEnd(10), score.toFixed(4));
}
$ node rrf.mjs
refund-2 0.0325
refund-1 0.0164
billing-1 0.0159Click ▶ Run to see the fused list. The vector ranking here is an example list so the code runs without any model; the next example uses a real embedding model.
Full hybrid search with real embeddings (Ollama)
Now let’s combine the BM25 class with real vector search. We use the free local embedding model nomic-embed-text through Ollama, which you set up in Part 6. First install what you need:
# Python packages (Node.js users: npm install ollama)
$ pip install ollama sentence-transformers
# Free local models for embeddings and for query rewriting
$ ollama pull nomic-embed-text
$ ollama pull llama3.2
Put hybrid_search.py in the same folder as bm25_search.py, rrf.py and docs.json:
import json
import ollama
from bm25_search import BM25
from rrf import reciprocal_rank_fusion
docs = json.load(open("docs.json"))
bm25 = BM25(docs)
def embed(texts):
return ollama.embed(model="nomic-embed-text", input=texts)["embeddings"]
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
return dot / ((sum(x * x for x in a) ** 0.5) * (sum(y * y for y in b) ** 0.5))
doc_vectors = embed(["search_document: " + d["text"] for d in docs])
def vector_search(query, k=5):
q = embed(["search_query: " + query])[0]
scored = sorted(zip(docs, doc_vectors), key=lambda p: cosine(q, p[1]), reverse=True)
return [d["id"] for d, _ in scored[:k]]
def hybrid_search(query, k=3):
keyword_ids = [doc_id for doc_id, _ in bm25.search(query, k=5)]
vector_ids = vector_search(query, k=5)
fused = reciprocal_rank_fusion([keyword_ids, vector_ids])
return [doc_id for doc_id, _ in fused[:k]]
for q in ["error E-1042", "can I get my money back?"]:
print(q)
print(" keyword:", [i for i, _ in bm25.search(q, k=3)])
print(" vector: ", vector_search(q, k=3))
print(" hybrid: ", hybrid_search(q))
$ python hybrid_search.py
error E-1042
keyword: ['pay-1']
vector: ['pay-1', 'pay-2', 'support-1']
hybrid: ['pay-1', 'pay-2', 'support-1']
can I get my money back?
keyword: ['refund-2']
vector: ['refund-1', 'refund-2', 'billing-1']
hybrid: ['refund-2', 'refund-1', 'billing-1']The vector list catches refund-1 for “money back”, the keyword list makes sure the exact code E-1042 always wins, and RRF keeps the best of both. Notice the search_document: and search_query: prefixes: the nomic-embed-text model is trained to use them, and they improve results.
alpha (0 = only keyword, 1 = only vector).Re-ranking with a cross-encoder
Hybrid search gives you a good list of candidates, but the order is still rough. A re-ranker is a second model that reads the question and each candidate chunk together and gives a precise relevance score. Then you keep only the best few.
Why is that better? The embedding model you used for vector search is a bi-encoder: it turns the question and the chunk into vectors separately, and only compares them at the end. That is fast (chunk vectors are computed once and stored), but the model never sees both texts side by side. A cross-encoder reads “question + chunk” as one input, so it can notice details like “within 14 days” answering “can I get my money back?”. It is too slow to run on your whole database, but perfect for re-ordering the top 20–50 results.
The sentence-transformers library includes free cross-encoder models. cross-encoder/ms-marco-MiniLM-L6-v2 is small enough to run on a laptop CPU:
import json
from sentence_transformers import CrossEncoder
docs = {d["id"]: d["text"] for d in json.load(open("docs.json"))}
# A small, free re-ranker model (downloads about 90 MB the first time)
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
query = "can I get my money back?"
candidates = ["refund-2", "refund-1", "billing-1", "pay-2", "support-1"] # top 5 from hybrid search
results = reranker.rank(query, [docs[i] for i in candidates], top_k=3)
for place, r in enumerate(results, start=1):
doc_id = candidates[r["corpus_id"]] # r["score"] holds the relevance score
print(f"{place}. {doc_id:10} {docs[doc_id][:52]}...")
$ python rerank.py
1. refund-1 Refund policy: you can ask for a full refund within ...
2. refund-2 After 14 days money back is not possible, but you ca...
3. billing-1 To cancel your subscription, open Settings, then Bil...The re-ranker moves refund-1 (“full refund within 14 days”) to the top, because it directly answers the question. Our hybrid list had it in second place. That one change can be the difference between a correct and a wrong answer from the LLM.
BAAI/bge-reranker-v2-m3 are more accurate and support many languages, including Hindi.Query rewriting: multi-query and HyDE
Sometimes the problem is not the search but the question. Users type short, vague or follow-up questions like “can I still get my money back for it?”. What is “it”? Query rewriting asks an LLM to fix the question before searching. Three common techniques:
- Stand-alone rewrite: use the chat history to replace “it”, “that” or “the same” with the real subject (“DevDojo Pro bought last week”).
- Multi-query: create 3 different versions of the question (“refund policy”, “cancel and get money back”…), search with each, and fuse all result lists with RRF. Different words find different chunks.
- HyDE (Hypothetical Document Embeddings): ask the LLM to write a short fake answer, then search with that answer. A fake answer “looks like” a real help-centre chunk, so its embedding lands closer to the right chunks than the short question does.
import ollama
MODEL = "llama3.2"
def multi_query(question, history=""):
prompt = (
"Rewrite the user's question as 3 short search queries for a help-centre search.\n"
"Use the chat history to replace words like 'it' or 'that'. "
"Use different words in each query. Return one query per line, nothing else.\n\n"
f"Chat history:\n{history or '(none)'}\n\nQuestion: {question}"
)
reply = ollama.chat(model=MODEL, messages=[{"role": "user", "content": prompt}],
options={"temperature": 0})
lines = [l.strip("-• ").strip() for l in reply.message.content.splitlines()]
return [question] + [l for l in lines if l][:3]
def hyde(question):
"""HyDE: write a fake answer, then search with it instead of the question."""
reply = ollama.chat(model=MODEL, messages=[{"role": "user", "content":
f"Write a 2-sentence help-centre answer to: {question}"}])
return reply.message.content
history = "User: I bought DevDojo Pro last week.\nBot: Great! How can I help?"
for q in multi_query("can I still get my money back for it?", history):
print("query:", q)
print("hyde :", hyde("can I get my money back?")[:90], "...")
$ python rewrite_query.py
query: can I still get my money back for it?
query: DevDojo Pro refund policy
query: refund for DevDojo Pro bought last week
query: cancel DevDojo Pro and get money back
hyde : You can ask for a full refund within 14 days of buying DevDojo Pro. After that, you can ...Which fix solves which problem?
You don’t need every technique in every app. Pick the problem you see in your tests:
Symptom: users search for “E-1042”, an invoice number or a function name like useEffect, and the answer is wrong.
Fix: add BM25 keyword search and use hybrid search with RRF. Keep codes intact when you tokenize (do not split “E-1042” into “e” and “1042”).
Symptom: the right chunk is in your top 10, but not in the top 3 that you send to the LLM.
Fix: retrieve more candidates (20–50), then re-rank with a cross-encoder and keep the top 3–5.
Symptom: the first question works, but follow-ups like “and for the yearly plan?” return random chunks.
Fix: rewrite the question into a stand-alone query using the chat history before you search.
Symptom: the user’s words differ from your documents’ words (“money back” vs “refund”, “login issue” vs “authentication error”).
Fix: make sure vector search is part of your hybrid search, and try multi-query or HyDE for short questions.
The full retrieval pipeline
Put together, a strong retrieval step for RAG usually looks like this:
- Rewrite the user’s question into a clear, stand-alone query (optional: create 2–3 variations).
- Search wide: BM25 top 20 + vector top 20 for each query.
- Fuse all lists with RRF.
- Re-rank the top 20–50 fused results with a cross-encoder.
- Send the top 3–5 chunks (with their source and section) to the LLM, as in Part 11.
| Step | Extra time per question | Extra cost | When to add it |
|---|---|---|---|
| Hybrid search (BM25 + vector + RRF) | Very small | None | Almost always. Start here. |
| Re-ranking (cross-encoder) | Small to medium (depends on model and number of candidates) | Free locally, or a small API fee | When the right chunk is often in the top 10 but not the top 3. |
| Stand-alone rewrite | One extra LLM call | One small LLM call | Any chat app with follow-up questions. |
| Multi-query / HyDE | One LLM call + extra searches | One small LLM call | Short or vague questions; test it first. |
Hybrid search in vector databases
You don’t have to build everything by hand in production. Many databases from Part 10 support hybrid search directly:
| Database | How hybrid search works |
|---|---|
| PostgreSQL + pgvector | Run a full-text search query (tsvector / ts_rank) and a pgvector query, then combine them with RRF in SQL or in your app code. |
| Elasticsearch / OpenSearch | BM25 is built in; add a vector field and combine both with their hybrid or RRF features. |
| Weaviate | Has a hybrid query with an alpha setting to balance keyword and vector results. |
| Qdrant | Store dense and sparse vectors together and fuse them with RRF in its query API. |
| Pinecone | Supports sparse + dense vectors for hybrid search. |
Features change quickly, so check your database’s current docs. The idea is always the same as the code above: two ranked lists, one fused list.
Common errors and fixes
| Problem | Why it happens | Fix |
|---|---|---|
| BM25 finds nothing for “E-1042” | The tokenizer split the code into “e” and “1042”, or removed it | Use a regex that keeps hyphenated words, like [a-z0-9]+(?:-[a-z0-9]+)* |
| Hybrid results look worse than vector only | You added raw BM25 scores to cosine scores (different scales) | Use RRF on ranks, or normalise both scores to 0–1 first |
ConnectionError / connection refused from ollama | The Ollama app or server is not running | Start Ollama (ollama serve) and run ollama list to check models |
model "nomic-embed-text" not found | The model was never pulled | ollama pull nomic-embed-text |
| Re-ranking is very slow | Too many candidates, or a large model on CPU | Re-rank only the top 20–50; use a small model like MiniLM; use a GPU or a hosted API |
| Re-ranker downloads fail | No internet access to Hugging Face, or a firewall | Download the model once on a machine with access and load it from a local folder |
| Multi-query returns the same query 3 times | The prompt doesn’t ask for different words | Ask for “different words in each query” and use temperature 0–0.3 |
| The LLM answer quotes the HyDE text | The fake answer was sent to the LLM as context | Use HyDE text only for searching; send the real chunks |
Best practices
- Start with hybrid search. It is cheap, fast and fixes the most common failures.
- Retrieve wide, then narrow. Get 20–50 candidates, re-rank, then send only 3–5 chunks to the LLM. Fewer, better chunks give clearer answers and cost less.
- Keep metadata with every result (source, page, section) so the final answer can cite where it came from.
- Use the same tokenizer for indexing and searching in BM25, and lowercase both.
- Cache query rewrites and embeddings for common questions to save time and money.
- Test with real user questions, including typos, Hinglish (“refund kaise milega”) and follow-ups, not only the clean ones you wrote yourself.
- Add one technique at a time and measure hit rate @3 after each change.
Practice task
Upgrade your RAG app:
- Add 5 chunks of your own to
docs.json, including one with a code or ID (an order number, an error code or a version number). - Run
bm25_search.pyandhybrid_search.pywith 5 questions. Write down which chunk each method puts first. - Change the RRF
kfrom 60 to 10. Does the order change? - Add
rerank.pyafter hybrid search. Count how often the correct chunk is in the top 3 before and after re-ranking. - Bonus: plug the full pipeline (rewrite → hybrid → re-rank) into the Ollama RAG app from Part 11 and use the chunks from Part 12.
Conclusion
Most bad RAG answers are really retrieval problems. Hybrid search lets keyword search and vector search cover each other’s blind spots, RRF merges them without any score maths, a cross-encoder re-ranker puts the best chunk on top, and query rewriting turns vague follow-ups into clear searches. Add them one at a time, measure with your test questions, and your RAG app will find the right chunk far more often.
New posts every day on DevDojo
Follow the full Generative AI series from basics to production. Bookmark devdojo.co.in and open the roadmap above to see what is coming next.
FAQ
What is hybrid search in RAG?
Hybrid search runs keyword search (usually BM25) and vector search for the same question and merges the two result lists. Keyword search finds exact words like codes and names; vector search finds similar meanings. Together they retrieve the right chunk more often than either one alone.
What is Reciprocal Rank Fusion (RRF)?
RRF is a simple way to merge ranked lists. Each chunk gets 1 / (k + rank) from every list it appears in, with k usually 60, and the totals decide the final order. Because it uses positions instead of raw scores, it works even when the two searches score on different scales.
What is the difference between a bi-encoder and a cross-encoder?
A bi-encoder turns the question and each chunk into vectors separately and compares them, which is fast enough to search millions of chunks. A cross-encoder reads the question and one chunk together and outputs a relevance score. It is more accurate but slower, so it is used to re-rank the top 20–50 results.
Does re-ranking make RAG slower?
A little. A small cross-encoder re-ranking 20–50 short chunks adds a small delay on a CPU and very little on a GPU. Keep the candidate list short and the model small, and measure the delay in your own app.
What is HyDE in RAG?
HyDE stands for Hypothetical Document Embeddings. The LLM writes a short fake answer to the question, and you search with the embedding of that answer instead of the question. It often helps short or vague questions. The fake answer is only used for searching, never shown to users.
Do I need LangChain or LlamaIndex for hybrid search?
No. As shown above, BM25 and RRF are each about 20–30 lines of code. Frameworks offer ready-made retrievers (for example an ensemble retriever that uses RRF) which can save time in bigger projects. We compare them in Part 18.