Sub topic 10
Combining keyword and vector search
This chapter assumes you can read basic Python and know how embeddings, cosine similarity and top-k retrieval work. It also assumes you have a keyword index such as BM25 (a standard term-frequency ranking formula) or a database full-text search. If you need a refresher, review the chapters on embeddings and top-k retrieval first.
Why one retriever is not enough
Vector search finds passages that mean something similar to the query. It handles paraphrases well: "how do I get my money back" can match a passage titled "Refund policy". It is weak on exact strings. Product codes, error numbers, function names, and rare surnames often land in odd places in embedding space, because the embedding model compresses text into a fixed number of dimensions and exact tokens can get lost.
Keyword search is the opposite. It matches the literal tokens in the query, and it weights rare tokens heavily. A query for ERR_CONN_4172 finds the one passage containing that string. But it fails when the user and the document use different words for the same idea.
Hybrid search runs both retrievers and merges the results into one ranked list. The goal is to keep the strengths of each and cover the other's blind spots.
| Property | Keyword (BM25) | Vector (embeddings) |
|---|---|---|
| Matches on | Shared tokens | Similar meaning |
| Strong at | Identifiers, rare terms, exact phrases | Paraphrases, vague or conversational queries |
| Weak at | Synonyms, typos, different wording | Exact strings, numbers, new jargon |
| Score range | Unbounded, depends on corpus statistics | Bounded, such as -1 to 1 for cosine |
| Needs a model | No | Yes, an embedding model |
The hybrid pipeline
The query goes to both retrievers in parallel. Each returns its own top-N candidates, where N is usually larger than the final k, for example 20 to 50. A fusion step merges the two lists. Only then do you cut to the final k passages for the prompt.
Retrieving more candidates than you finally need matters. A passage that ranks 12th in one list and 3rd in the other can still win after fusion, but only if the 12th place result was retrieved at all.
Why you cannot just add the scores
The obvious approach is to add the two scores. It does not work well, because the scores live on different scales. A BM25 score might be 14.2 for the best document in one corpus and 3.1 in another, since it depends on document length and term frequencies. A cosine score is usually between 0.2 and 0.9. Adding them lets the keyword score dominate, and the balance shifts whenever the corpus changes.
You can normalize each list first, for example with min-max scaling to the range 0 to 1, and then take a weighted sum. This works, but it is sensitive to outliers. One very high score squashes every other score in that list toward zero. You also have to retune the weights whenever the corpus or the embedding model changes.
Reciprocal rank fusion
Reciprocal rank fusion (RRF) avoids the scale problem by ignoring scores and using only ranks. Each document earns 1 / (k + rank) from every list it appears in, and the earned values are summed. The constant k (60 is the common default) softens the gap between the top ranks, so rank 1 is not overwhelmingly better than rank 2.
def reciprocal_rank_fusion(rankings, k=60):
# rankings is a list of ranked lists of document ids, best first
scores = {}
for ranking in rankings:
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + 1.0 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
keyword_ranking = ["d3", "d1", "d7"]
vector_ranking = ["d1", "d5", "d3"]
print(reciprocal_rank_fusion([keyword_ranking, vector_ranking]))Running this prints ['d1', 'd3', 'd5', 'd7']. Here is the arithmetic with k = 60:
d1is rank 2 in the keyword list and rank 1 in the vector list: 1/62 + 1/61 ≈ 0.03252.d3is rank 1 and rank 3: 1/61 + 1/63 ≈ 0.03227.d5appears only in the vector list at rank 2: 1/62 ≈ 0.01613.d7appears only in the keyword list at rank 3: 1/63 ≈ 0.01587.
Documents found by both retrievers rise to the top. This is the main benefit of fusion: agreement between two independent methods is good evidence of relevance. A document found by only one retriever can still make the list, but it ranks below documents both found at similar positions.
Properties to know
- No tuning of score scales. You can change the embedding model or the keyword analyzer without recalibrating anything.
- Any number of lists. You can fuse three or more rankings, such as keyword, vector, and a second vector index built with a different chunk size.
- Loses score information. If the vector search returns a near-perfect match with cosine 0.98 and the next result is 0.41, RRF treats them as adjacent ranks. A score gap is thrown away.
- Ties are possible. Two documents can get identical fused scores. Python's sort is stable, so ties keep first-seen order. If that matters, add an explicit tie-break.
Weighting one retriever more
If your queries are mostly identifier lookups, you may want keyword results to count more. A simple extension multiplies each list's contribution by a weight.
def weighted_rrf(rankings, weights, k=60):
if len(rankings) != len(weights):
raise ValueError("need one weight per ranking")
scores = {}
for ranking, weight in zip(rankings, weights):
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] = scores.get(doc_id, 0.0) + weight / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
print(weighted_rrf([["a", "b"], ["b", "a"]], weights=[2.0, 1.0]))This prints ['a', 'b']. Without the weights, a and b would tie, since each takes rank 1 in one list and rank 2 in the other. Weighting the first list by 2 breaks the tie in favor of a.
Common errors
- Fusing document ids that do not match. RRF merges by id. If the keyword index stores chunk ids like
doc7-chunk3and the vector index storesdoc7#3, nothing is ever merged and the result is two interleaved lists. Use one id scheme for both indexes. - Indexes out of sync. If a chunk is re-embedded but not re-indexed for keywords, or the reverse, the two retrievers see different corpora. Update both in the same ingestion job.
- Too few candidates per retriever. Taking only the top 5 from each list leaves fusion with little to work with. Start with 20 to 50 and cut after fusing.
- Mismatched metadata filters. If an access or date filter is applied to the vector search but forgotten on the keyword search, restricted passages leak through the keyword side. Apply identical filters to both.
- Poor keyword analysis. If you tokenize identifiers like
max_retriesintomaxandretries, exact-match queries lose their precision. Check how your keyword index splits code and part numbers. - Assuming hybrid always wins. On a corpus of conversational prose with no identifiers, keyword search may add noise. Measure before you commit.
Deciding whether you need hybrid search
Measure it. Build a small set of real queries with known relevant passages, then compare recall at k for keyword only, vector only, and fused retrieval. The recall_at_k metric from the evaluation chapter works for all three. Look at the queries where the fused list does worse than the better single retriever, since those show where the merge is hurting you.
Hybrid search is most worth the extra index and latency when your queries mix natural language with exact terms, such as support tickets, legal text, API documentation, and internal wikis with product names. Fusion is cheap, since the two searches run in parallel and the merge is a few dictionary operations. The cost is maintaining a second index.
Fusion also sets up the next stage. A fused list of 30 candidates is a good input for a reranker, which reads the query and each passage together and reorders them with more accuracy than either first-stage retriever.
Exercise
Document A is rank 1 in the keyword list only. Document B is rank 2 in both the keyword list and the vector list. Using reciprocal rank fusion with k = 60, which document ranks higher, and what are the two fused scores?
Show answer
B ranks higher. A scores 1/61 ≈ 0.01639, since it appears in one list only. B scores 1/62 + 1/62 = 2/62 ≈ 0.03226, since it appears in both. Agreement between the two retrievers outweighs a top rank in just one.
Exercise
A user searches for the exact error code E-90417. Vector search returns nothing useful, but keyword search finds the right passage at rank 1. The fused list still pushes that passage below several vector-only results. Name two changes that could fix this.
Show answer
Use weighted RRF with a higher weight on the keyword list, or detect identifier-like queries and route them to keyword search only. Another fix is to check that the keyword analyzer keeps E-90417 as a single token, so the exact match is strong.