AI Hints
Home›RAG Tutorial›Hybrid Search and Reranking
RAG · Lesson 55 of 120

Hybrid Search

Meaning plus keywords.

⏱ 2 min read▶ Video at 54:50🎓 Free
Watch this lesson in the RAG courseWatch on YouTube ↗Full RAG course

Hybrid search runs both searches, and merges the results. Keyword search catches the exact codes. Embeddings catch the meaning. Together, they miss much less.

Hybrid Search
From the video: Hybrid Search
  • Run both
  • Merge results
  • Miss much less

How hybrid works

The question goes to both searches at once. Embeddings return their top ten. Keywords return their top ten. A merge step combines the two lists. And we keep the best few.

  1. Question
  2. Embeddings
  3. Keywords
  4. Merge
  5. Top results
How hybrid works
From the video: How hybrid works

Hybrid in action

Hybrid from our kit runs both searches, and merges them. We try the code question, and the question with no shared words. Run it. Both questions now find the right chunk.

hybrid_search.pypython
from rag_kit import load_docs, make_chunks
from hybrid import Hybrid

search = Hybrid(make_chunks(load_docs()))

for q in ["What does E03 mean?",
          "How long until my money comes back?"]:
    print(q)
    for c in search.search(q, k=2):
        print("  ", c["text"][:60])
Output
What does E03 mean?
   E01: the battery is not connected properly. Remove the batte
   # E-bike battery guide
How long until my money comes back?
   ## Refund timing Refunds go back to the original payment met
   ## Change of mind You can return any unused item within 30 d

Also uses rag_kit.py
import warnings; warnings.filterwarnings("ignore")
from pathlib import Path
import numpy as np
from sentence_transformers import SentenceTransformer
import faiss  # after torch, so the two libraries load safely together
faiss.omp_set_num_threads(1)
from langchain_text_splitters import RecursiveCharacterTextSplitter

def load_docs(folder="data/rag/northwind"):
    return [{"source": p.name, "text": p.read_text()} for p in sorted(Path(folder).glob("*.md"))]

def make_chunks(docs, size=300, overlap=50):
    splitter = RecursiveCharacterTextSplitter(chunk_size=size, chunk_overlap=overlap)
    return [{"source": d["source"], "text": t.replace("\n", " ")}
            for d in docs for t in splitter.split_text(d["text"])]

embedder = SentenceTransformer("all-MiniLM-L6-v2", device="cpu")

def embed(texts):
    return embedder.encode(texts, normalize_embeddings=True)

class Index:
    def __init__(self, chunks):
        self.chunks = chunks
        self.vectors = embed([c["text"] for c in chunks])

    def search(self, query, k=3):
        scores = self.vectors @ embed([query])[0]
        top = np.argsort(-scores)[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]
Also uses llm.py
from langchain.chat_models import init_chat_model

llm = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)

PROMPT = """Answer the question using only the context below.
If the answer is not in the context, say "I don't know".

Context:
{context}

Question: {question}"""

def answer(question, chunks):
    context = "\n\n".join(f"[{c['source']}] {c['text']}" for c in chunks)
    return llm.invoke(PROMPT.format(context=context, question=question)).text.strip()
Also uses keyword_search.py
import re
from rank_bm25 import BM25Okapi

def words(text):
    return re.findall(r"[a-z0-9]+", text.lower())

class Keyword:
    def __init__(self, chunks):
        self.chunks = chunks
        self.bm25 = BM25Okapi([words(c["text"]) for c in chunks])

    def search(self, query, k=3):
        scores = self.bm25.get_scores(words(query))
        top = sorted(range(len(scores)), key=lambda i: -scores[i])[:k]
        return [(round(float(scores[i]), 2), self.chunks[i]) for i in top]
Also uses hybrid.py
from rag_kit import Index
from keyword_search import Keyword
from sentence_transformers import CrossEncoder

def rrf(*ranked_lists, k=60):
    scores, chunks = {}, {}
    for ranked in ranked_lists:
        for rank, chunk in enumerate(ranked):
            key = chunk["text"]
            scores[key] = scores.get(key, 0) + 1 / (k + rank + 1)
            chunks[key] = chunk
    return [chunks[t] for t in sorted(scores, key=lambda t: -scores[t])]

class Hybrid:
    def __init__(self, chunks):
        self.dense, self.sparse = Index(chunks), Keyword(chunks)

    def search(self, query, k=5):
        a = [c for _, c in self.dense.search(query, k=10)]
        b = [c for _, c in self.sparse.search(query, k=10)]
        return rrf(a, b)[:k]

reranker = CrossEncoder("cross-encoder/mmarco-mMiniLMv2-L12-H384-v1", device="cpu")

def rerank(query, chunks, k=3):
    scores = reranker.predict([(query, c["text"]) for c in chunks])
    order = sorted(range(len(chunks)), key=lambda i: -scores[i])[:k]
    return [chunks[i] for i in order]

Summary

Hybrid search runs embeddings and keywords, and merges their results. Next, how the merge works.

Key takeaways
  • Both searches
  • Merge lists
  • Fewer misses
Next up: Reciprocal Rank Fusion — merging ranked lists