Sub topic 11
Hybrid search: keywords plus vectors
This chapter assumes you know how embeddings and similarity metrics work, and what a nearest neighbor query returns. You should also be comfortable reading short Python and SQL. Earlier chapters covered dense vector indexes. This chapter shows how to combine them with keyword search.
Why vector search alone is not enough
Vector search matches meaning. A query for "how do I change my login secret" can find a page titled "Resetting your password", even though the two share no words.
The same strength causes failures on exact tokens:
- Identifiers. Product codes such as
XR-2200, error codes such asERR_CONN_RESET, and function names are rare strings. An embedding model may mapXR-2200andXR-2300to almost the same vector. - Rare names. People, drugs and places that were uncommon in the model's training data get weak embeddings.
- Out-of-domain terms. Internal jargon and new acronyms may be unknown to the model.
- Negation and precision. "Not a refund" and "refund" often embed close together.
Keyword search has the opposite profile. It matches exact terms, but it misses paraphrases and synonyms. Hybrid search runs both retrievers and merges their results, so each covers the other's weak spots.
The keyword side: sparse retrieval
Keyword retrieval uses an inverted index. This is a map from each term to the list of documents that contain it. The usual scoring function is BM25. It rewards a document when:
- it contains a query term often (term frequency, with diminishing returns),
- the term is rare across the collection (inverse document frequency),
- the document is not unusually long (length normalization).
Because each document is represented by a mostly empty vector over the whole vocabulary, keyword retrieval is called sparse. Embedding-based retrieval is called dense, because every dimension holds a value.
Some models, such as SPLADE, blur the line. They produce sparse vectors with learned term weights, including expansion terms that are not in the text. Many vector databases store these sparse vectors natively. For the rest of this chapter, "keyword" means BM25 or an equivalent full-text ranking.
The core problem: scores are not comparable
BM25 scores are unbounded and depend on the collection and the query. A score of 14.2 means nothing alone. Cosine similarity lies between -1 and 1, and the useful range is often narrow, such as 0.55 to 0.85. You cannot add these numbers directly without making one retriever dominate.
There are two standard fixes. You can convert the scores to a common scale, or you can ignore scores and fuse by rank.
Fusion method 1: reciprocal rank fusion
Reciprocal rank fusion (RRF) uses only each document's position in each result list. A document at rank r in a list earns 1 / (k + r). Its final score is the sum across lists. The constant k is usually 60. It damps the advantage of the top positions.
from collections import defaultdict
def rrf(rankings, k=60):
scores = defaultdict(float)
for ranking in rankings:
for rank, doc_id in enumerate(ranking, start=1):
scores[doc_id] += 1.0 / (k + rank)
return sorted(scores.items(), key=lambda item: item[1], reverse=True)
keyword_ranking = ["d7", "d2", "d9", "d4"]
vector_ranking = ["d2", "d5", "d7", "d1"]
for doc_id, score in rrf([keyword_ranking, vector_ranking]):
print(doc_id, round(score, 4))This prints:
d2 0.0325
d7 0.0323
d5 0.0161
d9 0.0159
d4 0.0156
d1 0.0156d2 and d7 appear in both lists, so they beat every document found by only one retriever. RRF needs no tuning and no normalization. It also works when the two retrievers return very different score scales. Its weakness is that it throws away score magnitude. A near-perfect vector match and a barely relevant one at the same rank count the same.
Fusion method 2: weighted score combination
The alternative is to normalize each score list and blend them with a weight alpha:
final = alpha * dense_norm + (1 - alpha) * sparse_normMin-max normalization rescales each list to the 0 to 1 range. This keeps magnitude information, so a confident match stays ahead. It has two problems:
- Normalization depends on the candidate set. A single outlier compresses all other scores.
alphaneeds tuning against labeled queries, and the best value can differ between query types.
def min_max(scores):
lo, hi = min(scores.values()), max(scores.values())
if hi == lo:
return {doc: 1.0 for doc in scores}
return {doc: (s - lo) / (hi - lo) for doc, s in scores.items()}
def weighted_fusion(dense, sparse, alpha=0.5):
dense_n, sparse_n = min_max(dense), min_max(sparse)
docs = set(dense_n) | set(sparse_n)
fused = {
d: alpha * dense_n.get(d, 0.0) + (1 - alpha) * sparse_n.get(d, 0.0)
for d in docs
}
return sorted(fused.items(), key=lambda item: item[1], reverse=True)
dense = {"d2": 0.81, "d5": 0.79, "d7": 0.62, "d1": 0.55}
sparse = {"d7": 12.4, "d2": 6.1, "d9": 5.9, "d4": 2.0}
for doc_id, score in weighted_fusion(dense, sparse, alpha=0.6):
print(doc_id, round(score, 3))A document missing from one list gets 0 for that component. That is a design choice, because "not retrieved" is not the same as "scored lowest".
| Property | RRF | Weighted scores |
|---|---|---|
| Needs score normalization | No | Yes |
| Tuning parameters | `k`, rarely changed | `alpha`, needs labeled data |
| Uses score magnitude | No | Yes |
| Robust to outliers | Yes | No, unless normalization is robust |
| Good default | Yes | When you have evaluation data |
The pipeline
Both retrievers run on the same query, each returns a candidate list, and a fusion step merges them. A reranker may then rescore the merged list.
Reranking as a second stage
Fusion is cheap and approximate. A cross-encoder reranker reads the query and each candidate together and produces a more accurate relevance score. It is too slow to run over the whole corpus, so it only rescored the top 20 to 100 fused candidates. The two stages divide the work:
- Retrieval favors recall. Get the right documents somewhere in the candidate list.
- Reranking favors precision. Put the best ones at the top.
If you add a reranker, retrieve more candidates than you plan to return, and measure whether it improves your results enough to justify the added latency.
Running hybrid search in Postgres
When the data already lives in Postgres, you can run both retrievers in one SQL statement. This example uses the built-in full-text search and pgvector. It merges the results with RRF in SQL.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE docs (
id bigserial PRIMARY KEY,
body text,
embedding vector(3),
tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', body)) STORED
);
CREATE INDEX ON docs USING gin (tsv);
CREATE INDEX ON docs USING hnsw (embedding vector_cosine_ops);
INSERT INTO docs (body, embedding) VALUES
('How to reset your password', '[1, 0, 0]'),
('Changing account credentials', '[0.9, 0.1, 0]'),
('Error ERR_CONN_RESET explained', '[0, 1, 0]');
WITH keyword AS (
SELECT id,
row_number() OVER (ORDER BY ts_rank_cd(tsv, q) DESC) AS rank
FROM docs, websearch_to_tsquery('english', 'reset password') AS q
WHERE tsv @@ q
LIMIT 50
),
semantic AS (
SELECT id,
row_number() OVER (ORDER BY embedding <=> '[1, 0, 0]') AS rank
FROM docs
ORDER BY embedding <=> '[1, 0, 0]'
LIMIT 50
)
SELECT COALESCE(k.id, s.id) AS id,
COALESCE(1.0 / (60 + k.rank), 0) + COALESCE(1.0 / (60 + s.rank), 0) AS score
FROM keyword k
FULL OUTER JOIN semantic s ON k.id = s.id
ORDER BY score DESC
LIMIT 10;The FULL OUTER JOIN keeps documents found by only one retriever. The COALESCE calls give a missing rank a contribution of zero. In a real application, the query vector comes from your embedding model, and you pass it as a parameter instead of a literal.
Dedicated vector databases often offer this as one API call. You supply a text query, a vector and optionally a fusion method or weight. Some systems accept a sparse vector alongside the dense one. Check which fusion method your system uses by default, because the choice changes ranking.
Edge cases and common errors
- Different analyzers. The keyword side lowercases, stems and removes stop words according to its analyzer. If the analyzer differs between indexing and querying, terms silently fail to match. Language settings matter, for example
'english'versus'simple'in Postgres. - Small candidate lists. If each retriever returns only 10 results, fusion has little to merge. Retrieve 50 to 200 per side before fusing, then cut down.
- Filters on both sides. A metadata filter must apply to both retrievers. If you filter only the vector side, keyword results can leak documents the user should not see. Apply access-control filters before retrieval wherever possible.
- Weights tuned on too few queries. An
alphathat works for natural-language questions can hurt on code or ID lookups. Evaluate separately by query type, or choose RRF. - Duplicate documents from chunking. If you retrieve chunks, two chunks from the same document may rank separately. Decide whether to fuse by chunk or by parent document.
- Mismatched freshness. The keyword index and vector index may update at different times, so a new document can appear in only one. This is usually harmless for RRF but worth knowing.
- Query embedding cost. Each query needs an embedding call. Cache embeddings for repeated queries if latency or cost matters.
Deciding whether you need it
Use hybrid search when queries mix natural language with exact tokens, such as support search, code search, legal or medical lookup, and e-commerce. For purely conceptual queries over clean prose, dense retrieval alone may be enough. Measure it. Build a set of real queries with known relevant documents, compare dense-only, keyword-only and hybrid on recall at your chosen k, and keep the added complexity only if hybrid wins on your data.
Exercise
A user searches for "ERRCONNRESET timeout fix". Dense retrieval ranks a general article on network timeouts first, and the page that names ERRCONNRESET fifth. Keyword retrieval ranks the ERRCONNRESET page first. Using RRF with k = 60, what score does that page get if the dense list places it fifth and the keyword list first, and why does hybrid help here?
Show answer
The score is 1/(60+1) + 1/(60+5) = 0.01639 + 0.01538 = about 0.0318. The network timeouts article, ranked first by the dense list and absent from the keyword list, scores only 1/61 = 0.0164. The ERRCONNRESET page therefore moves to the top. The keyword retriever supplies the exact-token match that the embedding model blurs, and the dense retriever still contributes to the score of the page.
Exercise
Your weighted fusion uses min-max normalization, and one query returns a single dense candidate with a similarity far above the rest. What happens to the other normalized dense scores, and what would you try instead?
Show answer
The outlier sets the maximum, so all other dense scores compress toward 0 and contribute little to the blend. Options include switching to RRF, which ignores magnitude, or normalizing with a more robust method such as z-scores or percentile clipping.