Velamuvi AIAcademy

Lesson 8 of 9 · Tools

Hybrid Search

Build hybrid search that finds exact terms and meaning: BM25, sparse vectors, Reciprocal Rank Fusion, weighted fusion and hybrid queries in Qdrant and Postgres.

  • 7 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • Explain how BM25 keyword scoring works and when it beats embeddings
  • Combine keyword and vector rankings with Reciprocal Rank Fusion
  • Describe sparse vectors and how vector databases run hybrid queries
  • Decide when hybrid search is worth the extra complexity

Two kinds of search, two kinds of strength

The Embeddings course showed that semantic search finds “low-cost airline tickets” for “cheap flights”, but can blur exact strings such as product codes, names and error numbers. Keyword search has the opposite strengths.

Hybrid search in Python

The program below scores a small help centre both ways: BM25 for keywords and the see-inside embedding model from the Embeddings course for meaning. It then fuses the two rankings:

Try it yourselfPython
import math

# A tiny, hand-made "embedding model". Each dimension is a topic.
# A real model learns thousands of dimensions from data; ours uses a word list
# so you can see exactly where the numbers come from.
TOPICS = ["travel", "food", "money", "tech", "health", "weather"]
LEXICON = {
    "flight": {"travel": 1}, "flights": {"travel": 1}, "airline": {"travel": 1},
    "plane": {"travel": 1}, "airport": {"travel": 1}, "trip": {"travel": 1},
    "holiday": {"travel": 1}, "hotel": {"travel": 1, "money": 0.3},
    "train": {"travel": 1}, "tickets": {"travel": 0.8, "money": 0.5},
    "recipe": {"food": 1}, "cook": {"food": 1}, "dinner": {"food": 1},
    "pasta": {"food": 1}, "rice": {"food": 1}, "curry": {"food": 1},
    "vegetarian": {"food": 1, "health": 0.3}, "restaurant": {"food": 1, "travel": 0.3},
    "cheap": {"money": 1}, "budget": {"money": 1}, "low-cost": {"money": 1},
    "price": {"money": 1}, "save": {"money": 1}, "salary": {"money": 1},
    "bank": {"money": 1}, "loan": {"money": 1}, "expensive": {"money": 1},
    "laptop": {"tech": 1}, "phone": {"tech": 1}, "app": {"tech": 1},
    "battery": {"tech": 1}, "wifi": {"tech": 1}, "password": {"tech": 1},
    "python": {"tech": 1}, "doctor": {"health": 1}, "sleep": {"health": 1},
    "exercise": {"health": 1}, "fever": {"health": 1}, "headache": {"health": 1},
    "diet": {"health": 1, "food": 0.5}, "rain": {"weather": 1},
    "sunny": {"weather": 1}, "forecast": {"weather": 1}, "storm": {"weather": 1},
    "umbrella": {"weather": 1}, "snow": {"weather": 1, "travel": 0.2},
}

def embed(text):
    vector = [0.0] * len(TOPICS)
    for word in text.lower().replace(",", " ").replace(".", " ").replace("?", " ").split():
        for topic, weight in LEXICON.get(word, {}).items():
            vector[TOPICS.index(topic)] += weight
    length = math.sqrt(sum(v * v for v in vector))
    if length == 0:
        return vector
    return [v / length for v in vector]          # unit length, so dot product = cosine

def cosine(a, b):
    return sum(x * y for x, y in zip(a, b))

# ---------- Keyword scoring: BM25, the classic search-engine formula ----------
def tokens(text):
    return [w.strip(".,:?!") for w in text.lower().split()]

docs = {
    "Error E-4021: card declined": "Payment error E-4021 means your bank declined the card.",
    "Getting your money back": "How refunds work if you cancel an order.",
    "Cheap flight deals": "Find low-cost airline tickets and budget flights.",
    "App closes on start": "If the app crashes, update your phone and reinstall it.",
    "Ways to pay": "Pay by card, bank transfer or wallet. The price includes tax.",
}
doc_tokens = {t: tokens(t + " " + body) for t, body in docs.items()}
avg_len = sum(len(w) for w in doc_tokens.values()) / len(doc_tokens)

def bm25(query, title, k1=1.5, b=0.75):
    words = doc_tokens[title]
    score = 0.0
    for term in tokens(query):
        df = sum(1 for w in doc_tokens.values() if term in w)     # documents containing the term
        if df == 0:
            continue
        idf = math.log((len(docs) - df + 0.5) / (df + 0.5) + 1)  # rare words count more
        tf = words.count(term)
        score += idf * tf * (k1 + 1) / (tf + k1 * (1 - b + b * len(words) / avg_len))
    return score

# ---------- Fusion: combine two rankings with Reciprocal Rank Fusion ----------
def ranking(score_fn, query):
    scored = [(score_fn(query, t), t) for t in docs]
    return [t for s, t in sorted(scored, reverse=True) if s > 0]   # only real matches

def semantic(query, title):
    return cosine(embed(query), embed(title + ". " + docs[title]))

def rrf(rankings, k=60):
    fused = {}
    for ranked in rankings:
        for position, title in enumerate(ranked, start=1):
            fused[title] = fused.get(title, 0) + 1 / (k + position)
    return sorted(fused, key=fused.get, reverse=True)

for query in ["E-4021", "plane holiday ideas", "cheap flights"]:
    keyword = ranking(bm25, query)
    meaning = ranking(semantic, query)
    print(f"Query: {query}")
    print("  keyword :", keyword[:2])
    print("  semantic:", meaning[:2])
    print("  hybrid  :", rrf([keyword, meaning])[:2])

Look at each query:

  • “E-4021”: only keyword search finds the article. The code means nothing to the embedding model.
  • “plane holiday ideas”: no document contains those words, so keyword search finds nothing; semantic search finds the flights article by meaning.
  • “cheap flights”: both agree on the best article.

Hybrid search got the right article first every time, without anyone choosing which method to trust for each query.

Reciprocal Rank Fusion

BM25 scores (like 2.3) and cosine similarities (like 0.87) are on different scales, so adding them directly makes no sense. Reciprocal Rank Fusion ignores the scores and uses only positions:

DocumentKeyword positionSemantic positionRRF score
A121/61 + 1/62 = 0.0325
B2(not found)1/62 = 0.0161
C(not found)11/61 = 0.0164

A wins because both methods ranked it highly. The constant 60 stops the very top positions from dominating.

The alternative is weighted fusion: scale each method's scores to the range 0–1, then compute something like 0.3 × keyword + 0.7 × semantic. It allows fine control, but the weights need tuning on real queries, and score scaling can behave badly when one list has a single strong match.

Sparse vectors and hybrid queries in a database

Keyword scores can be stored as vectors too.

Qdrant can store a dense and a sparse vector for each point and fuse both searches in one call:

results = client.query_points(
    collection_name="articles",
    prefetch=[
        models.Prefetch(query=dense_query_vector, using="dense", limit=20),
        models.Prefetch(query=models.SparseVector(indices=word_ids, values=word_weights), using="keywords", limit=20),
    ],
    query=models.FusionQuery(fusion=models.Fusion.RRF),
    limit=5,
).points

Each Prefetch runs one search; FusionQuery merges them with RRF. Other systems offer the same idea in their own way: Pinecone and Weaviate support sparse-dense queries, Elasticsearch and OpenSearch combine their BM25 search with vector fields, and in PostgreSQL you can combine pgvector with the built-in full-text search and fuse the two result lists in SQL.

Common mistakes

Practice exercise

Fuse the two rankings with Reciprocal Rank Fusion. A document that ranks well in both lists should come first.

Your solutionPython
keyword_results  = ["Error E-4021", "Ways to pay", "Card limits"]
semantic_results = ["Card limits", "Error E-4021", "Bank transfers"]

# Reciprocal Rank Fusion: each list gives a document 1 / (60 + position),
# where position starts at 1. Add up the scores, then print the titles
# from highest to lowest fused score, one per line.
Knowledge check

Why does Reciprocal Rank Fusion use positions instead of the raw scores?

Summary

  • BM25 keyword search excels at exact terms (codes, names, rare words); vector search excels at meaning.
  • Hybrid search runs both and merges the results.
  • Reciprocal Rank Fusion merges by position: 1 / (60 + position), added across lists.
  • Keyword scores can be stored as sparse vectors, letting databases like Qdrant fuse both searches in one query.
  • Measure on real queries: hybrid search usually helps most where users type codes, names or jargon.

Next: how to choose a vector database for your project.

Finished reading? Tick it off to track your progress.