方寸 Portal

AI Engineer Portal

Your personal operating system for career transition.

Private mode

Exercise

Build a hybrid retrieval pipeline

Build a Hybrid Retrieval Pipeline

Pure vector search misses documents with specific entity names, codes, or technical identifiers. Pure keyword search misses paraphrases and synonyms. Hybrid search combines both and consistently outperforms either alone across real-world query distributions.

The standard approach is Reciprocal Rank Fusion (RRF): each method ranks candidate documents independently, then RRF merges the rankings using score(doc) = sum(1 / (k + rank)) across all lists.

What you are building

Create a HybridRetriever class that:

  1. Stores documents in two parallel indices: a vector index (cosine similarity) and a keyword index (TF-IDF term scoring).
  2. Retrieves candidates from both indices independently for a given query, returning the top-N from each.
  3. Merges ranked lists using Reciprocal Rank Fusion.
  4. Returns the top-k results by final RRF score with source attribution (which method(s) found each document).
  5. Supports metadata filtering applied after retrieval but before merging.

Why this matters

Every serious production RAG system uses hybrid retrieval. Understanding RRF means you can tune the constant k (controls how much top positions are rewarded) and extend to three or more retrieval methods.

Constraints

  • Use only the Python standard library. Implement TF-IDF scoring directly.
  • Type-hint everything. Return list[RetrievedDoc] with score and source_methods fields.
  • The embedding function should be injectable (for testing with mocks).

Rag Systems / medium / Step 2 of 6

Practice stage

General drill

Hint

Keep the solution explicit and reviewable.

Success criteria

Make the solution explicit, debuggable, and easy to explain.

Review checklist

Review where the boundary is, what gets validated, and what would be hard to debug later.

Practice

Generate a variation

Generate a new exercise variation to deepen understanding or practice a related concept.

Attempt history

Recent submissions

Before you submit, decide what a strong answer should make obvious to the reviewer.

No attempts yet.