Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Lab · 25 min · revision 2

Filters and Hybrid Search with Rank Fusion

Add metadata filters to vector search and see why filtering after the search can return fewer than k results, write a small BM25 keyword search, and combine both rankings with reciprocal rank fusion.

Contentsand lesson path

What you will learn

  • Combine vector search with metadata filters and keyword search using rank fusion (hybrid retrieval).

Prerequisites: Embeddings

01. Goal and setup

Real retrieval rarely runs on vectors alone. Users belong to a team or ask about one product, so the search must respect metadata filters. And queries that hinge on exact strings, such as error codes or part numbers, suit keyword search better than embeddings. In this lab you build both over a 14-document help centre, then merge the two rankings with reciprocal rank fusion (RRF).

You need: Python 3.12 and NumPy 2 (tested with NumPy 2.5.4). Create a folder hybrid-lab, activate a virtual environment in it as in lesson 4, run python -m pip install numpy, and run every script from that folder.

Project layout
hybrid-lab/
├── corpus.py        step 1: documents, metadata, tokeniser, stand-in embedder
├── vector.py        step 2: exact vector search with an optional allow-list
├── bm25.py          step 4: BM25 keyword search
├── fusion.py        steps 5 and 6: RRF and hybrid_search()
└── demo_*.py        one small script per step

02. Step 1: the corpus and a stand-in embedder

Each document has an id, a platform field (web, mobile or api) and its text. So that the lab runs offline, embed() stands in for a real model: each known word adds the direction of its concept (money, access, export and so on) plus a little noise, so "refund" and "charged" point the same way and "password" elsewhere. Like real embeddings, only more so, it gives rare strings such as ERR-7702 no meaning. Swap in your real model when you finish.

Python · corpus.py
"""A small help-centre corpus with metadata, and a stand-in embedding model."""

import re
import zlib

import numpy as np

DOCS = [
    ("d01", "web", "Refunds for duplicate payments: if your card was billed twice "
                   "for one order, the extra payment is returned within five days."),
    ("d02", "web", "Change the card used for your subscription "
                   "under Settings, Billing."),
    ("d03", "web", "Download past invoices as PDF files from the Billing page."),
    ("d04", "web", "Reset a forgotten password from the sign-in page. "
                   "The reset link expires after one hour."),
    ("d05", "web", "Accounts are locked after five failed sign-in attempts. "
                   "Wait 15 minutes or ask an admin to unlock the account."),
    ("d06", "mobile", "Sign in to the mobile app with Face ID or a fingerprint "
                      "after your first login."),
    ("d07", "web", "Export reports to CSV or Excel from any dashboard "
                   "with the Export button."),
    ("d08", "web", "Error ERR-7702 means the export is larger than 100,000 rows. "
                   "Add a date filter and try again."),
    ("d09", "api", "The exports endpoint returns 413 when a report "
                   "exceeds the row limit."),
    ("d10", "mobile", "Push notifications stopped? Allow notifications for the app "
                      "in your phone settings."),
    ("d11", "mobile", "The Android app needs Android 10 or later; "
                      "the iOS app needs iOS 16 or later."),
    ("d12", "mobile", "Purchases made in the iOS app are billed by Apple, "
                      "so refunds for them are requested from Apple."),
    ("d13", "mobile", "Charged twice after upgrading in the Android app? Google Play "
                      "refunds the duplicate payment automatically."),
    ("d14", "mobile", "Cancel a subscription bought in the app from the "
                      "Google Play or App Store subscription page."),
]

STOP_WORDS = {
    "a", "after", "and", "any", "are", "as", "by", "for", "from", "i", "if", "in",
    "is", "it", "made", "my", "or", "so", "than", "the", "them", "to", "under",
    "used", "was", "when", "with", "your",
}


def tokenize(text: str) -> list[str]:
    """Lower-case words; codes such as err-7702 stay one token."""
    words = re.findall(r"[a-z0-9]+(?:-[a-z0-9]+)*", text.lower())
    return [w for w in words if w not in STOP_WORDS]


# Stand-in for an embedding model, so the lab runs offline: words with related
# meanings share a direction. Replace embed() with your real model.
CONCEPTS = {
    "money": "bill billed billing card charge charged invoices money paid payment "
             "payments purchase purchases refund refunds subscription",
    "repeat": "again double duplicate twice two",
    "access": "account accounts fingerprint locked login password reset sign sign-in "
              "unlock",
    "export": "csv download excel export exporting exports report reports row rows",
    "phone": "android app ios mobile notifications phone push",
    "fault": "error exceeds fails failed larger limit stopped",
}
DIM = 64


def _unit(seed: int) -> np.ndarray:
    vector = np.random.default_rng(seed).standard_normal(DIM)
    return vector / np.linalg.norm(vector)


_CONCEPT_OF = {w: c for c, words in CONCEPTS.items() for w in words.split()}
_CONCEPT_VEC = {c: _unit(i) for i, c in enumerate(CONCEPTS)}


def embed(text: str) -> np.ndarray:
    """Unit vector: one concept direction per known word, plus a little word noise.
    Unknown words, including codes such as err-7702, contribute nothing."""
    total = np.zeros(DIM)
    for word in tokenize(text):
        if word in _CONCEPT_OF:
            total += _CONCEPT_VEC[_CONCEPT_OF[word]]
            total += 0.3 * _unit(1000 + zlib.crc32(word.encode()))
    norm = np.linalg.norm(total)
    return total / norm if norm else total


IDS = [doc_id for doc_id, _, _ in DOCS]
PLATFORM = {doc_id: platform for doc_id, platform, _ in DOCS}
Python · demo_corpus.py
from corpus import DOCS, embed, tokenize

print(len(DOCS), "documents")
print(tokenize("Error ERR-7702 means the export is larger than 100,000 rows."))
print(round(float(embed("refund") @ embed("charged")), 3))
print(round(float(embed("refund") @ embed("password")), 3))
print(embed("ERR-7702").any())
Expected output (python demo_corpus.py)
14 documents
['error', 'err-7702', 'means', 'export', 'larger', '100', '000', 'rows']
0.908
0.05
False

The tokeniser keeps err-7702 as one token, which keyword search will need. The last line shows the stand-in turning the bare code into an all-zero vector.

03. Step 2: vector search

Python · vector.py
"""Exact vector search over the corpus, with an optional allow-list of ids."""

import numpy as np

from corpus import DOCS, IDS, embed

DOC_VECTORS = np.stack([embed(text) for _, _, text in DOCS])


def vector_search(query: str, k: int, allowed: set[str] | None = None) -> list[str]:
    """Top k by cosine; with `allowed`, only those ids can be returned (pre-filter)."""
    sims = DOC_VECTORS @ embed(query)
    ranked = [IDS[i] for i in np.argsort(-sims, kind="stable")]
    if allowed is not None:
        ranked = [doc_id for doc_id in ranked if doc_id in allowed]
    return ranked[:k]
Python · demo_vector.py
from vector import vector_search

print(vector_search("I paid two times for a single purchase", k=3))
print(vector_search("ERR-7702 when exporting", k=3))
Expected output (python demo_vector.py)
['d01', 'd13', 'd02']
['d07', 'd09', 'd08']

With 14 documents, exact search is the right tool. The first query shares no words with d01 or d13 ("paid two times" against "billed twice"), yet vector search finds both. The second query is about one specific error, d08, but the embedder ignores the code and ranks it behind the general export articles. Note also that vector search always returns k results, however weak the match.

04. Step 3: filter before or after the search

A user in the mobile app asks the first question again, and only mobile articles apply to them. There are two places to apply platform == "mobile":

  • Post-filtering: search first, then drop the results that fail the filter.
  • Pre-filtering: restrict the search to matching documents, so the top k is chosen among them.
Python · demo_filter.py
from corpus import IDS, PLATFORM
from vector import vector_search

query, k = "I paid two times for a single purchase", 3
mobile = {doc_id for doc_id in IDS if PLATFORM[doc_id] == "mobile"}

top = vector_search(query, k)                              # search, then filter
print("post-filter:", [d for d in top if d in mobile])
print("pre-filter: ", vector_search(query, k, allowed=mobile))
wider = vector_search(query, k * 2)                        # over-fetch, then filter
print("over-fetch: ", [d for d in wider if d in mobile][:k])
Expected output (python demo_filter.py)
post-filter: ['d13']
pre-filter:  ['d13', 'd12', 'd14']
over-fetch:  ['d13', 'd12', 'd14']

Post-filtering asked for three results and delivered one: two of the top three were web articles, the filter removed them, and nothing refilled the slots. The more selective the filter, the worse it gets. Over-fetching (ask for more, filter, cut to k) worked here, but no multiplier is safe for every filter.

Exact search makes pre-filtering trivial. In an approximate index it is harder, because the graph or clusters were built for the whole collection. Qdrant adds graph links for indexed payload fields and switches to a full scan when its planner estimates that few points match. pgvector applies the WHERE clause after the index scan, and since version 0.8.0 can keep scanning (iterative index scans) until enough rows pass. Elasticsearch pre-filters when the filter sits inside the knn clause and post-filters when it sits beside it in a bool query. For a small filtered subset, exact search over it is often simplest.

Filters that enforce access rights belong in the search itself; a forgotten post-filter or a prompt asking the model to ignore passages is not access control.

05. Step 4: keyword search with BM25

BM25 is the standard ranking function of keyword search and the default in Lucene, Elasticsearch and OpenSearch. A document scores the sum, over the query terms it contains, of each term's IDF (high for terms found in few documents) times a term-frequency factor. That factor grows with repeats but saturates, at a rate set by k1 (1.2 in Lucene), and is scaled by document length against the average, to a degree set by b (0.75), so long documents do not win by sheer size.

The class below is the whole algorithm. The rank_bm25 package has a ready-made version, but its default k1 is 1.5 and its IDF differs for common terms, so its scores will not match these.

Python · bm25.py
"""Okapi BM25 keyword search, using the Lucene IDF and default k1 and b."""

import math
from collections import Counter

from corpus import DOCS, IDS, tokenize


class BM25:
    def __init__(self, texts: list[str], k1: float = 1.2, b: float = 0.75) -> None:
        self.tfs = [Counter(tokenize(text)) for text in texts]
        self.lengths = [sum(tf.values()) for tf in self.tfs]
        self.avg_length = sum(self.lengths) / len(texts)
        n = len(texts)
        df = Counter(term for tf in self.tfs for term in tf)   # docs containing term
        self.idf = {t: math.log(1 + (n - f + 0.5) / (f + 0.5)) for t, f in df.items()}
        self.k1, self.b = k1, b

    def scores(self, query: str) -> list[float]:
        terms = tokenize(query)
        result = []
        for tf, length in zip(self.tfs, self.lengths):
            score = 0.0
            for term in terms:
                f = tf[term]                                   # 0 if absent
                if f:
                    norm = self.k1 * (1 - self.b + self.b * length / self.avg_length)
                    score += self.idf[term] * f * (self.k1 + 1) / (f + norm)
            result.append(score)
        return result


KEYWORD_INDEX = BM25([text for _, _, text in DOCS])


def keyword_search(query: str, k: int, allowed: set[str] | None = None) -> list[str]:
    """BM25 top k among documents that share at least one term with the query."""
    scores = KEYWORD_INDEX.scores(query)
    matches = [i for i, s in enumerate(scores) if s > 0]
    ranked = sorted(matches, key=lambda i: -scores[i])
    ids = [IDS[i] for i in ranked if allowed is None or IDS[i] in allowed]
    return ids[:k]
Python · demo_bm25.py
from bm25 import KEYWORD_INDEX, keyword_search

print(keyword_search("ERR-7702 when exporting", k=3))
print(keyword_search("I paid two times for a single purchase", k=3))
print(keyword_search("refund for a duplicate payment", k=3))
print({t: round(KEYWORD_INDEX.idf[t], 2) for t in ("err-7702", "refunds", "app")})
Expected output (python demo_bm25.py)
['d08']
[]
['d13', 'd01']
{'err-7702': 2.3, 'refunds': 1.46, 'app': 0.84}

The two retrievers fail in opposite places. BM25 finds the error article at once, because err-7702 occurs in a single document and so has the highest IDF in the corpus. The paraphrased billing question shares no terms with any document, so BM25 returns nothing. There is no stemming either: "exporting" does not match "export", and "refund" missed "refunds".

06. Step 5: fuse the rankings with RRF

The two lists have scores on unrelated scales, cosine between -1 and 1 and corpus-dependent BM25 values, so adding or averaging them lets the larger scale dominate. Reciprocal rank fusion (Cormack, Clarke and Büttcher, 2009) uses positions only: each document receives 1 / (k + rank) from every list it appears in, with ranks counted from 1, and the sums set the fused order. The paper fixed k at 60, still the common default.

Python · fusion.py (first part)
"""Reciprocal rank fusion, and hybrid search built on it."""

from bm25 import keyword_search
from corpus import IDS, PLATFORM
from vector import vector_search


def rrf(rankings: list[list[str]], k: int = 60) -> list[tuple[str, float]]:
    """Sum 1 / (k + rank) over the rankings a document appears in; ranks start at 1."""
    scores: dict[str, float] = {}
    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], item[0]))
Python · demo_rrf.py
from bm25 import keyword_search
from fusion import rrf
from vector import vector_search

for query in ("ERR-7702 when exporting", "I paid two times for a single purchase"):
    by_vector = vector_search(query, k=10)
    by_keyword = keyword_search(query, k=10)
    fused = rrf([by_vector, by_keyword])
    print(query)
    print("  vector: ", by_vector[:4])
    print("  keyword:", by_keyword[:4])
    print("  fused:  ", [(doc_id, round(score, 4)) for doc_id, score in fused[:3]])
Expected output (python demo_rrf.py)
ERR-7702 when exporting
  vector:  ['d07', 'd09', 'd08', 'd03']
  keyword: ['d08']
  fused:   [('d08', 0.0323), ('d07', 0.0164), ('d09', 0.0161)]
I paid two times for a single purchase
  vector:  ['d01', 'd13', 'd02', 'd03']
  keyword: []
  fused:   [('d01', 0.0164), ('d13', 0.0161), ('d02', 0.0159)]

Check the first fused score by hand: d08 is third in the vector list and first in the keyword list, so it gets 1/63 + 1/61 = 0.0159 + 0.0164 = 0.0323, while the vector favourite d07 gets only 1/61. A second list roughly doubles a score, whereas dropping from first to tenth place in one list only lowers it from 0.0164 to 0.0143. With k = 60, agreement between retrievers outweighs exact position; a smaller k rewards top positions more. For the paraphrased query the keyword list is empty, so fusion keeps the vector order.

Check the details before comparing engines. Elasticsearch counts ranks from 1 with a rank_constant of 60 by default. Qdrant counts ranks from 0 with a default constant of 2, equivalent to k = 1 with ranks from 1; since version 1.16 you can set it.

07. Step 6: filtered hybrid search

Python · fusion.py (add at the end)


def hybrid_search(
    query: str, k: int = 3, platform: str | None = None, depth: int = 10
) -> list[str]:
    """Pre-filter both retrievers, take `depth` candidates from each, fuse with RRF."""
    allowed = None
    if platform is not None:
        allowed = {doc_id for doc_id in IDS if PLATFORM[doc_id] == platform}
    rankings = [
        vector_search(query, depth, allowed),
        keyword_search(query, depth, allowed),
    ]
    return [doc_id for doc_id, _ in rrf(rankings)[:k]]
Python · demo_hybrid.py
from fusion import hybrid_search

print(hybrid_search("ERR-7702 when exporting"))
print(hybrid_search("duplicate payment refund", platform="mobile"))
print(hybrid_search("duplicate payment refund", platform="web"))
Expected output (python demo_hybrid.py)
['d08', 'd07', 'd09']
['d13', 'd12', 'd14']
['d01', 'd02', 'd03']

The function applies the same filter to both retrievers before ranking, takes depth candidates from each (Elasticsearch calls this the rank window), and fuses. The same question now gets the Google Play article for a mobile user and the web refund policy for a web user.

In production you rarely build this from scratch. With pgvector you combine a vector index, SQL WHERE filters and Postgres full-text search, and write the fusion in SQL or application code. Qdrant runs dense and sparse searches as prefetch steps of one query and fuses them with RRF. Elasticsearch has BM25 and kNN search in one index and an rrf retriever.

08. Check your understanding

Practice check · 3 questions

Filters, BM25 and fusion

Reason from the lab results.

Q1. A search with k = 10 returns only 2 results when restricted to platform = mobile, although the collection holds 400 mobile documents. What is the most likely cause?
Q2. With k = 60, document A is 2nd in the vector list and missing from the keyword list. Document B is 5th in both lists. Which ranks higher after fusion?
Q3. In the lab, tokenize() keeps codes such as err-7702 as one token. Suppose it split on hyphens instead. What would keyword_search return for ERR-7703, a code that no article mentions?
Practice only: not graded, not saved, not evidence.

09. Apply it: stretch tasks

Finish the practice project by adding a filter and rank fusion to the index from lesson 4:

  1. A query type that vectors miss. Write ten queries that hinge on exact strings in your corpus (error codes, product numbers, names), with the ids of the chunks that answer them.
  2. Keyword side. Build BM25 over your chunk texts with a tokeniser that keeps your codes intact.
  3. Filter inside the index. Add a metadata field such as source or product. In FAISS, pass allowed row ids with params=faiss.SearchParametersHNSW(sel=faiss.IDSelectorBatch(ids), efSearch=64), and compare recall@10 with exact search over the same subset, for a filter matching half the collection and one matching 2%. If the selective filter loses much recall, search that subset exactly.
  4. Fuse and compare. Count how often the answering chunk reaches the top 3 with vector-only, keyword-only and hybrid search, for RRF k of 10, 60 and 100.
  5. Swap the embedder. Replace embed() with your real model, rerun the demos, and explain what changed.

10. Review prompt

Without looking back:

  1. Why can post-filtering return fewer than k results, and what are two ways to avoid it?
  2. Name the three parts of a BM25 term score and the parameters behind the last two.
  3. Compute the RRF score, with k = 60, of a document ranked 1st in one list and 4th in another.
  4. Give one query that vector search handles better than BM25, and one where the reverse holds.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check