Velamuvi AIAcademy

Lesson 9 of 16 · Retrieval

Hybrid Search

Hybrid search for RAG: why exact terms matter, combining BM25 and embeddings with Reciprocal Rank Fusion, and measuring each method on your own questions.

  • 5 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain why RAG systems often need keyword search as well as embeddings
  • Combine keyword and semantic rankings with Reciprocal Rank Fusion
  • Compare retrievers on a test set with hit rate
  • Decide whether hybrid search is worth it for your data

Why RAG questions need both

People ask RAG systems two kinds of questions, often in the same day:

  • Meaning questions: “Can I take time off when my partner has a baby?” Words differ from the documents; embeddings shine.
  • Exact-term questions: “What does error E-4021 mean?”, “What's in plan PRO-200?”, “Clause 14.3”. Exact strings matter; keyword search shines.

The Hybrid Search lesson of the Vector Databases course showed how BM25 and Reciprocal Rank Fusion (RRF) work. This lesson applies them to the handbook and does what matters most in practice: measuring which retriever works best.

Three retrievers, one test set

The program below builds a keyword retriever (BM25), a semantic retriever (the see-inside embeddings) and a hybrid of both (RRF), then checks each against eight questions whose correct section we know:

Try it yourselfPython
import math, re

# ---- A tiny see-inside embedding model: one dimension per concept ----
CONCEPTS = {
    "leave":     "leave holiday holidays vacation annual time-off carried",
    "sick":      "sick ill illness unwell doctor self-certify",
    "remote":    "remote home hybrid office hours",
    "expenses":  "expenses expense claim reimbursed receipt receipts meals",
    "equipment": "laptop laptops monitor headset equipment lost stolen",
    "security":  "password passwords 2fa two-factor login phishing security",
    "parental":  "parental maternity paternity baby birth adoption adoptive",
    "training":  "training course courses learning books conferences",
    "travel":    "travel trip trips flight flights train trains journeys",
    "pay":       "pay paid salary payroll",
}
WORDS = {c: set(words.split()) for c, words in CONCEPTS.items()}

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

def embed(text):
    v = [sum(w in WORDS[c] for w in words(text)) for c in CONCEPTS]
    length = math.sqrt(sum(x * x for x in v))
    return [x / length for x in v] if length else v

def cosine(a, b):
    return sum(x * y for x, y in zip(a, b))       # vectors are unit length

# ---- The knowledge base: sections of a company handbook ----
HANDBOOK = {
    "Annual leave": "Full-time employees get 25 days of paid annual leave per year, plus public holidays. Book holiday in the HR portal at least two weeks ahead. Up to 5 unused days can be carried over to next year.",
    "Sick leave": "If you are ill, tell your manager before 10am on your first day off. You can self-certify for up to 7 days; after that you need a note from a doctor. Sick pay is your full salary for up to 10 days per year.",
    "Remote work": "You can work from home up to 3 days a week, with your manager's agreement. Core hours are 10am to 4pm. The office is open from 7am to 8pm.",
    "Expenses": "Claim expenses within 30 days in the finance app, with a photo of each receipt. Meals on work trips are reimbursed up to 40 euros per day. Approved expenses are paid with your next salary.",
    "Equipment": "New starters get a laptop, a monitor and a headset. Report a lost or stolen laptop to IT within 24 hours. Laptops are replaced every 4 years.",
    "Security": "Use a password manager and turn on two-factor login (2FA) for every work account. Never share your password. Report phishing emails with the Report button in your mail app.",
    "Parental leave": "Birth parents get 26 weeks of paid parental leave and partners get 4 weeks. Adoptive parents get the same leave as birth parents.",
    "Training": "Every employee has a learning budget of 1,000 euros per year for courses, books and conferences. Courses over 300 euros need your manager's approval.",
    "Business travel": "Book work trips in the travel portal. Fly economy for flights under 6 hours and premium economy for longer flights. Take the train for journeys under 4 hours.",
}

# ---- Keyword retriever: BM25 ----
DOCS = {t: words(t + " " + text) for t, text in HANDBOOK.items()}
AVG = sum(len(w) for w in DOCS.values()) / len(DOCS)

def bm25_rank(query, k1=1.5, b=0.75):
    scores = {}
    for title, doc in DOCS.items():
        s = 0.0
        for term in set(words(query)):
            df = sum(term in d for d in DOCS.values())
            if df and term in doc:
                idf = math.log((len(DOCS) - df + 0.5) / (df + 0.5) + 1)
                tf = doc.count(term)
                s += idf * tf * (k1 + 1) / (tf + k1 * (1 - b + b * len(doc) / AVG))
        if s > 0:
            scores[title] = s
    return sorted(scores, key=scores.get, reverse=True)

# ---- Semantic retriever: embeddings ----
VECS = {t: embed(t + ". " + text) for t, text in HANDBOOK.items()}

def semantic_rank(query):
    q = embed(query)
    scores = {t: cosine(q, v) for t, v in VECS.items() if cosine(q, v) > 0}
    return sorted(scores, key=scores.get, reverse=True)

# ---- Hybrid: Reciprocal Rank Fusion ----
def hybrid_rank(query):
    fused = {}
    for ranking in (bm25_rank(query), semantic_rank(query)):
        for pos, title in enumerate(ranking, start=1):
            fused[title] = fused.get(title, 0) + 1 / (60 + pos)
    return sorted(fused, key=fused.get, reverse=True)

# ---- A small test set: question -> the section that answers it ----
tests = {
    "How many vacation days do I get?": "Annual leave",
    "Can I work from home?": "Remote work",
    "What is the 2FA rule?": "Security",
    "Who approves an expensive course?": "Training",
    "When can I fly premium economy?": "Business travel",
    "Where do I submit receipts?": "Expenses",
    "When must I tell my manager I'm unwell?": "Sick leave",
    "How often are laptops replaced?": "Equipment",
}

for name, retriever in [("keyword", bm25_rank), ("semantic", semantic_rank), ("hybrid", hybrid_rank)]:
    hits = sum(retriever(q)[:1] == [answer] for q, answer in tests.items())
    misses = [q for q, answer in tests.items() if retriever(q)[:1] != [answer]]
    print(f"{name:<8} right section first: {hits}/{len(tests)}   missed: {misses}")

Each retriever fails differently:

  • Keyword missed “expensive course” (the handbook says “courses”) and “submit receipts” (it says “receipt”). Exact matching is literal.
  • Semantic missed “fly premium economy”: the embedding model has no notion of seat classes, while the words appear verbatim in the travel section.
  • Hybrid got all eight, because when one method misses, the other usually doesn't.

Building hybrid retrieval in practice

  1. Run both retrievers, each returning more candidates than you need (say 20 each).
  2. Fuse with RRF (or weighted scores, tuned on your test set).
  3. Optionally rerank the fused list (next lesson), then keep the top few for the prompt.

Most vector databases can do steps 1 and 2 in a single query (Qdrant, Weaviate, Pinecone, Elasticsearch and OpenSearch all offer hybrid search), and in PostgreSQL you can combine pgvector with built-in full-text search.

Common mistakes

Practice exercise

Score a retriever on a small test set. These two numbers are how you compare keyword, semantic and hybrid retrieval on your own questions.

Your solutionPython
# For each test question: the right section, and the top 3 sections a retriever returned
results = [
    ("Annual leave",    ["Annual leave", "Parental leave", "Sick leave"]),
    ("Expenses",        ["Business travel", "Expenses", "Training"]),
    ("Security",        ["Security", "Equipment", "Remote work"]),
    ("Business travel", ["Expenses", "Training", "Remote work"]),
]

# Count how often the right section is first (hit@1) and anywhere in the top 3 (hit@3).
# Print:
# Hit@1: 2/4
# Hit@3: 3/4
Knowledge check

Which question is a keyword retriever likely to handle better than an embedding retriever?

Summary

  • RAG gets both meaning questions (embeddings win) and exact-term questions (keywords win).
  • Hybrid search runs both and fuses the rankings, usually with RRF.
  • Measure retrievers with hit rate@k on a test set of real questions.
  • Each method has different blind spots, which is why combining them so often helps.

Next: reranking, the most effective way to put the best chunks first.

Finished reading? Tick it off to track your progress.