Generative AI Part 13: Better RAG with Hybrid Search, Re-ranking and Query Rewriting

Generative AI Part 13 banner: hybrid search with BM25 and vector search, RRF fusion, re-ranking and query rewriting
PART 13 Generative AI Series · DevDojo Better RAG Hybrid Search & Re-ranking Find the right chunk first: keyword + vector search, re-ranking, query rewriting 1 · Rewrite"money backfor it?" Keyword (BM25)exact words, codes Vector searchmeaning, synonyms 2 · FuseRRF 3 · Re-rankcross-encoder Top 3 → LLM refund-1 refund-2 billing-1 devdojo.co.in · Beginner friendly · Python + Node.js examples
Series: Generative AI Part 13 of 30

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.

Quick Summary
  • 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

  1. What Is Generative AI and How Do LLMs Work?
  2. Tokens, Context Windows and Model Parameters
  3. Your First LLM API Calls in Python and Node.js (OpenAI, Anthropic, Gemini)
  4. Prompt Engineering Basics: Roles, Instructions and Examples
  5. Temperature, Top-p and Controlling Model Output
  6. Run LLMs Locally with Ollama
  7. Streaming Responses and Building a Simple Chat UI
  8. Structured Outputs: Getting Reliable JSON from LLMs

Intermediate

  1. Embeddings Explained: Turning Text into Vectors
  2. Vector Databases: pgvector, Chroma and Pinecone
  3. RAG Fundamentals: Retrieval-Augmented Generation
  4. Document Loading and Chunking Strategies
  5. Better RAG: Hybrid Search, Re-ranking and Query RewritingYou are here
  6. Function Calling and Tool UseComing soon
  7. Conversation Memory and Long Context ManagementComing soon
  8. Multimodal AI: Vision, Images and Audio InputsComing soon
  9. How Image Generation Works: Diffusion Models BasicsComing soon
  10. LangChain vs LlamaIndex: When to Use a FrameworkComing soon
  11. Testing LLM Apps: Evals, Metrics and Test SetsComing soon
  12. Cutting Cost and Latency: Caching, Batching and Model ChoiceComing soon

Advanced

  1. Fine-Tuning vs Prompting vs RAG: Choosing the Right ToolComing soon
  2. Fine-Tuning an Open Model with LoRAComing soon
  3. Transformers Deep Dive: Attention Explained SimplyComing soon
  4. Reasoning Models and Thinking TimeComing soon
  5. Guardrails, Safety and Prompt Injection DefenceComing soon
  6. Monitoring and Tracing LLM Apps in ProductionComing soon
  7. Serving Open Models: vLLM, Quantization and GPUsComing soon
  8. Building a Production GenAI App End to EndComing soon
  9. Responsible AI: Privacy, Licensing and BiasComing soon
  10. 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.

Two searches, two different blind spots Keyword (BM25) "error E-1042"found "money back?"half Matches exact words.Does not know "refund"means "money back". Vector search "error E-1042"risky "money back?"found Matches meaning.Codes, IDs and rare namescan get blurred. Hybrid search "error E-1042"found "money back?"found Runs both searches andmerges the ranked lists,so each covers the other.
Keyword search and vector search fail in different places. Hybrid search combines them.

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:

1. Rare words count more“E-1042” appears in one chunk, so it is a strong signal. “plan” appears everywhere, so it is weak. This is called IDF (inverse document frequency).
2. Repeats help, but less each timeA word that appears 3 times scores higher than once, but not 3× higher. The k1 setting controls this.
3. Short chunks get a boostA match in a 10-word chunk is more focused than the same match in a 500-word chunk. The 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:

docs.json — devdojo-better-rag — Visual Studio Code
devdojo-better-rag › 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."}
]
⎇ mainLn 10, Col 1Spaces: 4UTF-8LFJSON

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:

bm25_search.py — devdojo-better-rag — Visual Studio Code
devdojo-better-rag › bm25_search.py
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)}")
TERMINALOUTPUTPROBLEMS
$ 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)]
⎇ mainLn 36, Col 1Spaces: 4UTF-8LFPython
devdojo-better-rag › bm25_search.mjs
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)));
}
TERMINALOUTPUTPROBLEMS
$ 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]]
⎇ mainLn 34, Col 1Spaces: 2UTF-8LFJavaScript

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.

Library option: in Python, pip install rank-bm25 gives you BM25Okapi with the same idea. Writing it yourself once helps you understand what the scores mean.

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.

How RRF merges two ranked lists Keyword list #1 refund-2 (BM25 found only one) Vector list #1 refund-1 #2 refund-2 #3 billing-1 RRF1 / (60 + rank) Fused list 1. refund-2 = 0.03251/61 + 1/62 (in both lists) 2. refund-1 = 0.01641/61 (vector #1) 3. billing-1 = 0.01591/63 (vector #3) Both refund chunks now make the top 2.
RRF only uses positions, so you never need to compare BM25 scores with cosine similarity.

RRF is only a few lines of code:

rrf.py — devdojo-better-rag — Visual Studio Code
devdojo-better-rag › rrf.py
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}")
TERMINALOUTPUTPROBLEMS
$ python rrf.py
refund-2   0.0325
refund-1   0.0164
billing-1  0.0159
⎇ mainLn 15, Col 1Spaces: 4UTF-8LFPython
devdojo-better-rag › rrf.mjs
function 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));
}
TERMINALOUTPUTPROBLEMS
$ node rrf.mjs
refund-2   0.0325
refund-1   0.0164
billing-1  0.0159
⎇ mainLn 17, Col 1Spaces: 2UTF-8LFJavaScript

Click ▶ 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:

Terminal — install for hybrid search and re-ranking
# 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:

hybrid_search.py — devdojo-better-rag — Visual Studio Code
devdojo-better-rag › hybrid_search.py
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))
TERMINALOUTPUTPROBLEMSExample output – your vector ranking may differ
$ 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']
⎇ mainLn 33, Col 1Spaces: 4UTF-8LFPython

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.

Weighting: if your users mostly type codes and names, give the keyword list more weight: multiply its RRF part by 1.5, or fetch more keyword results. Many vector databases call this setting 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.

Bi-encoder (vector search) question chunk model → vector model → vector cosine similarity Fast: search millions of chunks Cross-encoder (re-ranker) question + chunk (read together) model reads both relevance score Accurate: use on the top 20–50 only
Use the fast bi-encoder to find candidates, then the careful cross-encoder to order them.

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:

rerank.py — devdojo-better-rag — Visual Studio Code
devdojo-better-rag › rerank.py
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]}...")
TERMINALOUTPUTPROBLEMSExample output – order shown, scores vary by model version
$ 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...
⎇ mainLn 15, Col 1Spaces: 4UTF-8LFPython

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.

Hosted options: if you prefer an API, Cohere Rerank, Voyage AI and Jina AI offer re-ranking endpoints. The pattern is the same: send the query plus 20–50 candidate texts, get back scores, keep the top few. Bigger open models like 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.
rewrite_query.py — devdojo-better-rag — Visual Studio Code
devdojo-better-rag › rewrite_query.py
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], "...")
TERMINALOUTPUTPROBLEMSExample output – LLM wording will differ
$ 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 ...
⎇ mainLn 26, Col 1Spaces: 4UTF-8LFPython
Watch out: the HyDE answer is only used for searching. Never show it to the user, because the LLM may invent details. The final answer must still come from the real chunks you retrieve.

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:

  1. Rewrite the user’s question into a clear, stand-alone query (optional: create 2–3 variations).
  2. Search wide: BM25 top 20 + vector top 20 for each query.
  3. Fuse all lists with RRF.
  4. Re-rank the top 20–50 fused results with a cross-encoder.
  5. Send the top 3–5 chunks (with their source and section) to the LLM, as in Part 11.
StepExtra time per questionExtra costWhen to add it
Hybrid search (BM25 + vector + RRF)Very smallNoneAlmost always. Start here.
Re-ranking (cross-encoder)Small to medium (depends on model and number of candidates)Free locally, or a small API feeWhen the right chunk is often in the top 10 but not the top 3.
Stand-alone rewriteOne extra LLM callOne small LLM callAny chat app with follow-up questions.
Multi-query / HyDEOne LLM call + extra searchesOne small LLM callShort or vague questions; test it first.
Measure, don’t guess: reuse the test questions from Part 12. Count how often the correct chunk appears in the top 3 (this is called hit rate @3) for: vector only, hybrid, and hybrid + re-rank. Keep a step only if it improves the number. We will build proper evaluations in Part 19.

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:

DatabaseHow hybrid search works
PostgreSQL + pgvectorRun 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 / OpenSearchBM25 is built in; add a vector field and combine both with their hybrid or RRF features.
WeaviateHas a hybrid query with an alpha setting to balance keyword and vector results.
QdrantStore dense and sparse vectors together and fuse them with RRF in its query API.
PineconeSupports 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

ProblemWhy it happensFix
BM25 finds nothing for “E-1042”The tokenizer split the code into “e” and “1042”, or removed itUse a regex that keeps hyphenated words, like [a-z0-9]+(?:-[a-z0-9]+)*
Hybrid results look worse than vector onlyYou 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 ollamaThe Ollama app or server is not runningStart Ollama (ollama serve) and run ollama list to check models
model "nomic-embed-text" not foundThe model was never pulledollama pull nomic-embed-text
Re-ranking is very slowToo many candidates, or a large model on CPURe-rank only the top 20–50; use a small model like MiniLM; use a GPU or a hosted API
Re-ranker downloads failNo internet access to Hugging Face, or a firewallDownload the model once on a machine with access and load it from a local folder
Multi-query returns the same query 3 timesThe prompt doesn’t ask for different wordsAsk for “different words in each query” and use temperature 0–0.3
The LLM answer quotes the HyDE textThe fake answer was sent to the LLM as contextUse 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:

  1. 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).
  2. Run bm25_search.py and hybrid_search.py with 5 questions. Write down which chunk each method puts first.
  3. Change the RRF k from 60 to 10. Does the order change?
  4. Add rerank.py after hybrid search. Count how often the correct chunk is in the top 3 before and after re-ranking.
  5. 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.

Next part → Part 14: Function Calling and Tool Use. So far our LLM can only read text we give it. Next, you will let it call your own functions to check order status, do maths or fetch live data, and return the results in its answer.

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.

Share