Hybrid Search: Combining BM25 and Embeddings for Better RAG
Pure vector search misses exact-keyword queries. Pure BM25 misses semantic ones. Combining them with reciprocal rank fusion is the simplest large win in RAG retrieval.
Key takeaways
- Hybrid search runs a keyword ranker such as BM25 and a vector search in parallel, then merges the two ranked lists with reciprocal rank fusion, scoring each document 1/(60 + rank) per list.
- Keywords catch identifiers and error codes, embeddings catch paraphrases, and fusion needs no score normalization or weight tuning.
On this page
Hybrid search means running BM25 keyword search and vector search on the same chunks, then merging both ranked lists with reciprocal rank fusion (RRF): each document scores the sum of 1/(60 + rank) across lists. It fixes the queries pure vector search fumbles: error codes, config keys and product names.
Verified againstChecked against official docs
PostgreSQL 18.6 full-text search, pgvector 0.8.7, and Elasticsearch's RRF retriever docs, against the postgresql.org text search docs, the pgvector README and the original Cormack et al. RRF paper. Checked October 2026.
The first version of most RAG systems uses pure vector search: embed the query, find the nearest chunks in cosine-similarity space, send them to the LLM. That works for queries that match documents semantically. It works terribly for queries that depend on specific identifiers, version numbers, error codes, or product names. A typical case: a user types the exact name of a feature into a support assistant and gets back chunks about something else. Hybrid retrieval is the standard fix for that recall gap, and this post shows how to set it up.
Where vector search fails
Vector embeddings encode meaning, not surface form. If that distinction is fuzzy, start with what embeddings actually are. It is their strength most of the time and their weakness for a specific class of queries:
- Identifiers: error codes, SKUs, customer IDs, file paths.
"ERR_TLS_HANDSHAKE_FAILED"and"the handshake failed during TLS negotiation"describe similar concepts, but the embedding distance can be surprisingly large. Pure vector retrieval ranks the prose version first; the user wanted the error code one. - Exact phrases: quoted strings, function names, command-line flags.
"max_connections"should match documents that contain that literal config key, not just documents that talk about connection pooling abstractly. - Rare terms: niche product names, internal jargon. The embedding model hasn't seen them often enough, so the vector lands close to lots of unrelated things.
For these, BM25, which counts term overlap weighted by inverse document frequency, does much better.
Where BM25 fails
BM25 has the symmetric problem. It looks at words, not meaning:
"how do I fix a 502 error"doesn't match a doc that uses"bad gateway response": no shared keywords.- Synonyms, paraphrases and abbreviations all defeat it.
- Cross-language queries are hopeless.
These are exactly where vector search shines. The two methods have complementary failure modes, which is why combining them works.
Reciprocal rank fusion (RRF)
RRF is the simplest way to combine ranked lists from multiple search systems. For each candidate document, compute:
score(doc) = sum over each list of 1 / (k + rank_in_that_list)
k is a smoothing constant. Cormack, Clarke and Buettcher fixed it at 60 in the 2009 paper that introduced RRF and found that value near-optimal, and Elasticsearch's rank_constant still defaults to 60 as of October 2026. Documents that rank highly in multiple lists score high; documents that rank highly in only one still get partial credit.
No tuning of relative weights, no normalizing raw scores from different systems, no calibration. Just rankings.
def rrf(rankings: list[list[str]], k: int = 60) -> list[str]:
scores: dict[str, float] = {}
for ranking in rankings:
for i, doc_id in enumerate(ranking):
scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + i + 1)
return sorted(scores, key=lambda d: scores[d], reverse=True)
dense_results = vector_search(query) # list of doc_ids ranked
bm25_results = bm25_search(query) # list of doc_ids ranked
fused = rrf([dense_results, bm25_results])[:10]
That's the whole algorithm.
How to run it in production
Backend. Postgres with pgvector for embeddings, plus Postgres's built-in full-text search via tsvector and ts_rank_cd for the keyword side. Both indexes on the same table, both queries against the same data. No separate Elasticsearch needed at our scale.
One honest caveat: ts_rank_cd is not true BM25. The PostgreSQL docs state that its ranking functions "do not use any global information", so there is no corpus-wide IDF. For RRF that matters less than you'd think, because only the order within each list counts, but if you need real BM25 scoring, use a search engine or a Postgres extension that implements it.
Pipeline at query time:
- Run both queries in parallel against the same
documenttable: vector top-25 by cosine distance, FTS top-25 byts_rank_cd. - Fuse with RRF (k=60).
- Take the top 8-10 for the LLM context.
You can also do the fusion inside one SQL statement, which keeps the round trip count at one:
-- hybrid_search.sql: $1 = query embedding, $2 = raw query text
WITH semantic AS (
SELECT id, RANK() OVER (ORDER BY embedding <=> $1) AS rank
FROM document
ORDER BY embedding <=> $1
LIMIT 25
),
keyword AS (
SELECT id, RANK() OVER (ORDER BY ts_rank_cd(tsv, q) DESC) AS rank
FROM document, plainto_tsquery('english', $2) q
WHERE tsv @@ q
ORDER BY ts_rank_cd(tsv, q) DESC
LIMIT 25
)
SELECT COALESCE(s.id, k.id) AS id,
COALESCE(1.0 / (60 + s.rank), 0) + COALESCE(1.0 / (60 + k.rank), 0) AS score
FROM semantic s
FULL OUTER JOIN keyword k ON s.id = k.id
ORDER BY score DESC
LIMIT 10;
We added re-ranking on top later (a small cross-encoder scores the fused results against the query), but RRF on its own moved the needle enough to justify the complexity. Whether the reranker is worth its latency is its own decision, covered in when a cross-encoder earns its latency.
What to expect, and what you should measure
Comparing top-10 retrieval against labeled relevant chunks, the usual qualitative ordering looks like this:
| Method | Keyword-heavy queries | Paraphrased queries | Extra latency |
|---|---|---|---|
| Pure vector | Weak | Strong | Baseline |
| Pure keyword (Postgres FTS) | Strong | Weak | Baseline |
| RRF fusion | Strong | Strong | One parallel query |
| RRF + cross-encoder rerank | Strongest | Strongest | A model call per query |
Vector wins over keyword overall, but fusion beats either alone, because RRF lets each method "vote" for the docs it found. The size of the win is workload-dependent: expect it to be largest for corpora full of error codes and identifiers and smallest for prose-heavy doc search. Don't trust anyone's numbers; build an offline retrieval eval harness on your own labeled queries and measure recall@10 before and after.
Latency stays small because the two queries run in parallel: you pay roughly the slower of the two, plus a trivial fusion step.
Common mistakes
Running vector and BM25 against different document sets. If they have different ingestion pipelines (different chunking, different normalization), the fused list returns documents that don't exist in one or the other. It looks weird and debugging is awkward. Same source, same chunks.
Weighting BM25 to compensate for "vector is better." With RRF you don't need weighting. If you find yourself adding scalar weights to one side, you're rebuilding what RRF already does.
Forgetting to normalize text consistently. Both pipelines need the same tokenization, lowercasing and stemming. Mismatches mean keyword ranks differ for queries that look the same after normalization.
Skipping eval. Hybrid sounds obviously better, but the win varies by corpus. Run the eval against your actual labeled set.
What we'd skip
A few patterns we tried and dropped:
- Learned weights for combining scores. Fixed RRF with k=60 worked as well as anything we trained.
- Query expansion with synonyms before BM25. Too much complexity for marginal gain.
- Two separate vector indexes (different models) fused. Doesn't move the needle the way orthogonal methods (vector plus keyword) do.
Questions people ask
Is hybrid search better than vector search for RAG?
Usually, yes, for any corpus with identifiers, error codes, config keys or product names. Vector search handles paraphrases but misses exact tokens; keyword search does the opposite. Fusing both with RRF recovers the queries each one misses, at the cost of one extra parallel query. On pure prose corpora the gain shrinks, so confirm it with a labeled retrieval eval before assuming it.
What value of k should I use for reciprocal rank fusion?
Start with 60. The original RRF paper fixed k at 60 and found it near-optimal, and Elasticsearch uses 60 as its default rank_constant. A higher k flattens the curve, so lower-ranked documents carry more weight; a lower k rewards top positions more. We have never found a tuned value that beat 60 by enough to justify the extra knob.
Is Postgres full-text search the same as BM25?
No. ts_rank and ts_rank_cd weigh term frequency, proximity and document structure, but the PostgreSQL docs note they use no global information, so there is no corpus-wide inverse document frequency. For RRF fusion that is usually fine, since only rank order matters. If you need true BM25 scores, use Elasticsearch, OpenSearch, or a Postgres BM25 extension.
What to read next
- Build your first RAG app in Python: the end-to-end RAG pattern this fits into
- What are embeddings?: the vector side of hybrid
- The best vector databases: where these indexes live
- Embeddings drift detection: when "similar enough" stops being similar: what happens after you've got retrieval working
Sources
Cite this article
Kiril Urbonas (2026). Hybrid Search: Combining BM25 and Embeddings for Better RAG. DevOpsNess. Updated 2026-11-20. https://www.devopsness.com/blog/hybrid-search-bm25-embeddings-rag
[Hybrid Search: Combining BM25 and Embeddings for Better RAG](https://www.devopsness.com/blog/hybrid-search-bm25-embeddings-rag) (Kiril Urbonas, DevOpsNess, updated 2026-11-20)
More from AI
Explore more articles in this category
Embeddings Drift Detection: When "Similar Enough" Stops Being Similar
Embedding indexes degrade silently. The signals that catch drift, how often to re-embed, and the operational patterns we built after one quiet quality regression.
Reranking in RAG: When a Cross-Encoder Earns Its Latency
Our RAG answers kept citing the wrong paragraph even when the right one was retrieved. A cross-encoder reranker fixes relevance but adds a forward pass per candidate. Here's when that trade pays off.
Small Language Models vs LLMs: When Smaller Wins
Small language models now handle most agent steps at a fraction of the cost, so pick per step instead of defaulting to a frontier model.
You might have missed
Evergreen posts worth revisiting.