Early-bird price on the GenAI & Agentic AI Engineer Bootcamp batch. Grab a seat →

Hybrid search and reranking: getting the right passages to the model

Combine keyword and vector search with reciprocal rank fusion, then rerank with a cross-encoder. Includes the RRF formula, a worked example and code.

Related courseGenAI & Agentic AI Engineer Bootcamp
On this page
Diagram: Hybrid retrieval with reranking

Hybrid search runs a keyword search and a vector search for the same question and merges the two ranked lists, so you catch both exact terms and paraphrases. Reranking then uses a slower, more accurate model to reorder the merged candidates, so the few passages you send to the language model are the best ones. Add them in that order, and only when your measurements show plain vector search is missing things.

Key takeaways

  • Vector search finds passages that mean the same thing. Keyword search finds passages that contain the same words. Each fails where the other succeeds.
  • Reciprocal rank fusion (RRF) merges ranked lists using only positions, so you never have to compare a cosine distance with a keyword score.
  • PostgreSQL's built-in full-text search works for the keyword side, but its ranking functions are not BM25.
  • A cross-encoder reranker reads the question and passage together. It is more accurate than vector similarity and much slower, so apply it to tens of candidates, not to the whole corpus.
  • Every extra stage adds latency. Keep it only if it improves results on your own test set.

This article is one part of our complete guide to retrieval-augmented generation.

Why is vector search alone not enough?

An embedding model compresses a passage into one vector that captures its general meaning. That is why "how do I get my money back" finds a passage headed "Refund policy". It is also why exact strings get blurred. Part numbers, error codes, function names, surnames and rare abbreviations carry little "meaning" for the model to place.

Ask about error E-4471 and vector search may return passages about errors in general, while a keyword search returns the one passage containing that string. The reverse failure is just as real: keyword search finds nothing for "money back" if the document only says "refund".

Question typeVector searchKeyword search
Paraphrase or synonymStrongWeak
Exact code, ID or nameWeakStrong

Most real question sets contain both kinds, which is the case for running both searches.

What does the keyword side look like?

The best-known keyword ranking function is BM25. Anthropic's write-up on retrieval describes it as building on TF-IDF, a measure of how important a word is to a document in a collection, with an adjustment for document length and a cap on the effect of repeating a term. In short, rare words count for more, and repeating a word twenty times does not make a passage twenty times more relevant.

If your data is in Postgres you can start with its built-in full-text search. Add a generated tsvector column and a GIN index, the pattern shown in the PostgreSQL documentation:

ALTER TABLE chunks
    ADD COLUMN textsearch tsvector
    GENERATED ALWAYS AS (to_tsvector('english', content)) STORED;

CREATE INDEX chunks_textsearch_idx ON chunks USING GIN (textsearch);

SELECT id, content
FROM chunks, websearch_to_tsquery('english', 'refund "gift card"') AS query
WHERE textsearch @@ query
ORDER BY ts_rank_cd(textsearch, query) DESC
LIMIT 20;

websearch_to_tsquery accepts search-box style input, and ts_rank_cd ranks by how often the query terms appear and how close together they are.

One limit should be stated plainly. The PostgreSQL manual says its ranking functions "do not use any global information". They do not know how rare a word is across your whole table, which is what lets BM25 weight rare terms more heavily. So ts_rank and ts_rank_cd are not BM25. For many corpora that is fine, because the matching step does much of the work. If you need BM25 scoring, use a search engine whose documentation says it implements it. Qdrant's, for instance, says its full-text index can rank with BM25.

How does reciprocal rank fusion combine the two lists?

You now have two ranked lists whose scores are on different scales. A cosine distance of 0.21 and a text rank of 0.08 cannot be added in any meaningful way.

Reciprocal rank fusion avoids the problem by ignoring scores and using positions only. It was introduced by G. V. Cormack, C. L. A. Clarke and Stefan Büttcher in a SIGIR 2009 paper. For each document d, add up one term per ranking r in which it appears:

RRFscore(d) = sum over rankings r of  1 / (k + rank_r(d))

rank_r(d) is the document's position in ranking r, starting from 1, and k is a constant. A document missing from a list contributes nothing for that list. The authors fixed k = 60 in a pilot study. They report that this value was near-optimal but that the choice was not critical. The constant damps the influence of a single high placing from one outlier system.

A worked example

Suppose vector search returns A, B, C, D in that order, and keyword search returns C, A, E. With k = 60:

PassageVector rankKeyword rankCalculationRRF score
A121/61 + 1/620.0325
C311/63 + 1/610.0323
B2not found1/620.0161
Enot found31/630.0159
D4not found1/640.0156

The fused order is A, C, B, E, D. The two passages that both methods found rise to the top.

In Python:

def rrf(rankings, k=60):
    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)

print(rrf([["A", "B", "C", "D"], ["C", "A", "E"]]))
# ['A', 'C', 'B', 'E', 'D']

You can also do the fusion in one SQL statement. The pgvector project publishes an example that takes the top 20 from each search in two common table expressions, joins them with a FULL OUTER JOIN and sums 1.0 / (k + rank) for each side. The link is in the sources below.

RRF has limits. It treats both lists as equally trustworthy and discards how confident each search was. That is the price of needing no tuning. In the original paper's four TREC tests RRF scored above Condorcet Fuse every time and above CombMNZ in all but one. That is evidence from document search in 2009, not a guarantee for your corpus.

Hybrid retrieval sends the question to keyword search and vector search, fuses the two lists, reranks the candidates and passes the top passages to the model.

What does a reranker add?

Vector search uses a bi-encoder: the question and the passage are embedded separately and only their vectors are compared. That is fast, but the model never sees the two side by side.

A cross-encoder takes the question and one passage together as a single input and outputs a relevance score. The Sentence Transformers documentation says cross-encoders generally perform better than bi-encoders and are often slower, because every question-and-passage pair needs its own model run. It therefore recommends using them to rerank the top results from a faster retriever.

from sentence_transformers import CrossEncoder

model = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")

query = "How do I get a refund on a gift card?"
passages = [row[1] for row in candidates]  # text of the fused top 30

ranks = model.rank(query, passages)
top_passages = [passages[r["corpus_id"]] for r in ranks[:5]]

rank returns a list of dictionaries, best first, each with a score and a corpus_id, which is the index of the passage in the list you passed in. The model named here is the one in the library's own example. Pick a reranker that supports your languages.

The cost is concrete. Reranking 30 candidates means 30 extra model runs for every query. Anthropic's write-up notes the same trade-off: reranking adds latency at run time, and reranking more chunks buys better results at the price of speed and cost. In its own experiments the company retrieved 150 chunks, reranked them and passed the top 20 to the model.

How do you decide what to add?

Use the test set from how to evaluate a RAG system and look at where the right passage ends up.

  1. The right passage is missing from the top 50 altogether. This is a recall problem. Check extraction and chunking first. If the missed questions contain exact terms, add keyword search and fusion.
  2. The right passage is in the top 50 but not the top 5. This is a ranking problem, and it is what a reranker fixes.
  3. The right passage is already in the top 5 for nearly every question. Stop. Further retrieval work will not help. Look at the answer prompt instead.

Common questions

How many candidates should each search return before fusion?

Enough that the right passage is nearly always somewhere in the pool. The pgvector example takes 20 from each list. Start there, measure recall at that depth and raise it if good passages are being cut off.

No. A reranker can only reorder what retrieval gave it. If the passage containing E-4471 was never retrieved, no reranker will find it.

Does hybrid search need two databases?

No. Postgres can hold the vectors (with pgvector) and the full-text index in the same table. See pgvector or a dedicated vector database for when a separate system is worth running.

Free download: RAG evaluation checklist and test-set template

A checklist for measuring a RAG system properly, retrieval first and answers second, plus a blank test-set spreadsheet you can fill in today. See what’s inside.