Skip to content
Visual explainer 3h to learn 4 steps

Hybrid search & reranking

Combine keyword and vector search and rerank results for better precision.

By Invicly Tech, , in AI Engineering with Python. About 13 minutes to read.

Topic 15 of 33

In short

Vector search finds similar meanings but can miss exact terms like product codes. Hybrid search combines keyword and vector results, and a reranker then reorders the top candidates for precision.

Explained simply

Vector search is great at meaning: it knows that money back and refund are related. But it is weak at exact words. Search for error E1042 or part SKU-4471 and the right page may not come first, because a code has little meaning to an embedding model.

Keyword search is the opposite. It finds exact words and codes very well, but it misses a page that says reimbursement when the user typed refund. Hybrid search runs both kinds of search and combines the two result lists, so you get the strengths of each.

Even then, the order is not perfect. A reranker is a second, more careful model. It reads the question and each candidate passage together and gives a precise relevance score. It is slower, so you use it only on the top few dozen results.

Each step should earn its place. You measure how many of the top results are relevant before and after adding keywords and reranking, and keep only what helps.

Press Play on a diagram to walk through it one step at a time.

FlowHybrid retrieval with reranking
  1. 1
    User query

    e.g. error E1042 on login

  2. 2
    Keyword search

    BM25 or tsvector finds exact terms

  3. 3
    Vector search

    Embeddings find similar meaning

  4. 4
    Fuse results

    Reciprocal rank fusion merges both lists

  5. 5
    Rerank

    Cross-encoder scores query and chunk together

  6. 6
    Top-k chunks

    Best few go to the model

SequenceOne hybrid query with reranking
App
Postgres
Reranker
LLM
  1. 1Keyword search: top 30
    App to Postgres: Keyword search: top 30
  2. 2Vector search: top 30
    App to Postgres: Vector search: top 30
  3. 3Two ranked lists
    Postgres to App: Two ranked lists
  4. 4RRF merge: about 40 unique
    App to App: RRF merge: about 40 unique
  5. 5Score 40 query and chunk pairs
    App to Reranker: Score 40 query and chunk pairs
  6. 6Relevance scores
    Reranker to App: Relevance scores
  7. 7Top 5 chunks plus the question
    App to LLM: Top 5 chunks plus the question

In depth

How BM25 ranks keyword matches

BM25 is the standard formula behind most keyword search engines. It scores a document for a query by adding up a score for each query word. Two ideas drive it. Rare words count more: a word that appears in few documents, like E1042, is worth far more than a common word like login. This is inverse document frequency (IDF). And repeats help, but with diminishing returns: the tenth mention of a word adds much less than the first. This is term frequency saturation, controlled by a parameter k1 (often 1.2 to 2.0).

BM25 also adjusts for length, so a long document does not win just by containing more words. The parameter b (usually 0.75) sets how strong that adjustment is.

In Python, the rank_bm25 package gives a quick in-memory BM25. Search engines such as Elasticsearch and OpenSearch use BM25 by default.

  • Rare words weigh more (IDF)
  • Repeated words help less and less (k1)
  • Long documents are normalised (b)
  • Exact tokens matter: tokenise codes carefully

Keyword search inside Postgres

If your vectors are in Postgres, you can do keyword search in the same table. to_tsvector('english', content) turns text into a list of normalised words (lexemes): lowercased, stemmed so refunds becomes refund, with common stop words removed. Store it in a generated column and add a GIN index so matching is fast. websearch_to_tsquery('english', $1) turns user input into a query, and understands quoted phrases, or, and a minus sign for exclusion.

Rank matches with ts_rank or ts_rank_cd. Note that these are not BM25: they do not use corpus-wide word rarity, so a common word can score as well as a rare one. For many apps that is good enough, especially when fused with vector results. If you need true BM25 inside Postgres, extensions exist, or you can use a search engine alongside.

The english configuration stems words, which can mangle codes; the simple configuration does not stem.

  • Generated tsvector column plus a GIN index
  • websearch_to_tsquery accepts user-style queries
  • ts_rank is not BM25: no corpus-wide IDF
  • simple config for codes and names

Fusing two ranked lists

BM25 scores and cosine distances are on completely different scales, so you cannot simply add them. Reciprocal rank fusion (RRF) avoids the problem by using only positions. Each document gets 1 / (k + rank) from each list it appears in, and the scores are summed. k = 60 comes from the original paper and works well in practice; it stops the very top rank from dominating.

A document ranked 1st in one list and absent from the other gets 1/61, about 0.0164. A document ranked 3rd in both gets 2/63, about 0.0317, so it wins. Agreement between the two searches is rewarded.

The alternative is score blending: normalise each list's scores to 0 to 1, then mix with a weight, such as 0.7 vector and 0.3 keyword. It can be tuned more finely but is sensitive to score distributions. Either way, fetch more candidates from each search than you need, such as 20 to 50 each.

CompareRRF vs score blending
Reciprocal rank fusion
  • Uses ranks only
  • No score normalising
  • k = 60 is a solid default
  • Rewards agreement between lists
Weighted score blend
  • Normalise each list to 0 to 1
  • Mix with a weight like 0.7 / 0.3
  • Finer control
  • Sensitive to score shapes

Rerankers: bi-encoders vs cross-encoders

The embedding search you already have uses a bi-encoder: the query and each document are turned into vectors separately, and documents are embedded ahead of time. That is what makes it fast, but the model never sees the query and the document together.

A cross-encoder takes the query and one passage as a single input and outputs a relevance score. Because it reads both at once, it notices details such as whether the passage actually answers the question or just mentions the same topic. It is much more accurate and much slower, since nothing can be computed in advance: every query and candidate pair needs a full model pass.

So rerank only the top 20 to 50 fused candidates and keep the best 3 to 10. Options include open cross-encoder models via sentence-transformers, hosted rerank APIs, or asking an LLM to judge relevance, which is the slowest and most expensive.

CompareBi-encoder vs cross-encoder
Bi-encoder (embeddings)
  • Query and document encoded apart
  • Document vectors pre-computed
  • Searches millions quickly
  • Good recall, rougher order
Cross-encoder (reranker)
  • Reads query and passage together
  • Nothing can be pre-computed
  • Only practical for dozens of items
  • Sharper precision at the top

Proving it helps

Build a labelled set: 30 to 100 real queries, each with the ids of the chunks that answer it. Include queries with exact codes, paraphrases and vague wording. Then compare configurations on the same set: vector only, keyword only, hybrid, and hybrid plus reranking.

Useful metrics: precision at k, the share of the top k that are relevant; recall at k, the share of all relevant chunks that appear in the top k; and MRR (mean reciprocal rank), which rewards putting the first relevant chunk near the top. For RAG, recall at k matters most for the retrieval step, and precision near the top matters for prompt size and answer quality.

Track latency next to quality. A reranker that adds 300 ms for a 2 point gain may or may not be worth it; the numbers let you decide.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Add keyword search with BM25 or tsvector~45m
  2. 2
    Fuse keyword and vector results~45m
  3. 3
    Rerank with a cross-encoder~45m
  4. 4
    Measure precision before and after~45m

Key points

  • Keyword search excels at names, codes and rare terms; vectors excel at paraphrases.
  • Reciprocal rank fusion merges lists by rank, so scores need no normalising.
  • Rerankers are slower, so apply them only to the top few dozen candidates.
  • Measure precision at k before and after to prove the change helps.

Key terms

Tap a card to flip it. 0/5 known

Examples

python
def rrf(*ranked_lists: list[str], k: int = 60) -> list[str]:
    scores: dict[str, float] = {}
    for results in ranked_lists:
        for rank, doc_id in enumerate(results, start=1):
            scores[doc_id] = scores.get(doc_id, 0) + 1 / (k + rank)
    return sorted(scores, key=scores.get, reverse=True)

keyword = ['doc7', 'doc2', 'doc9']
vector = ['doc2', 'doc4', 'doc7']
print(rrf(keyword, vector))  # doc2 and doc7 rise to the top

Reciprocal rank fusion of keyword and vector results.

Hybrid search with RRF in one SQL query

Your chunks table has an embedding column and a generated tsv column. Step 1: the kw CTE takes the top 30 keyword matches and numbers them by rank. Step 2: the vec CTE takes the top 30 by cosine distance, also numbered. Step 3: a full outer join keeps chunks found by either search. Step 4: each chunk scores 1 / (60 + rank) per list, missing lists count as 0, and the 10 best come back. $1 is the query text and $2 its embedding.

sql
WITH kw AS (
  SELECT id, row_number() OVER (ORDER BY ts_rank_cd(tsv, q) DESC) AS r
  FROM chunks, websearch_to_tsquery('english', $1) q
  WHERE tsv @@ q ORDER BY ts_rank_cd(tsv, q) DESC LIMIT 30
), vec AS (
  SELECT id, row_number() OVER (ORDER BY embedding <=> $2) AS r
  FROM chunks ORDER BY embedding <=> $2 LIMIT 30
)
SELECT COALESCE(kw.id, vec.id) AS id,
       COALESCE(1.0 / (60 + kw.r), 0) + COALESCE(1.0 / (60 + vec.r), 0) AS score
FROM kw FULL OUTER JOIN vec ON kw.id = vec.id
ORDER BY score DESC
LIMIT 10;

Reranking candidates with a cross-encoder

Hybrid search returns 40 candidates, and you want the best 3 for the prompt. Step 1: load a small open cross-encoder trained for search relevance. Step 2: build one pair per candidate: the query and the chunk text. Step 3: score all pairs in one predict call. Step 4: sort by score and keep the top 3. The chunk that explains error E1042 should now rank above chunks that merely mention login.

python
# pip install sentence-transformers
from sentence_transformers import CrossEncoder

reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
query = "error E1042 on login"
candidates = [
    "Login page redesign: new colours and layout.",
    "E1042 means your session token expired. Sign out and sign in again.",
    "How to enable two-factor login.",
]
scores = reranker.predict([(query, text) for text in candidates])
ranked = sorted(zip(scores, candidates), reverse=True)
for score, text in ranked[:3]:
    print(f"{score:.2f}  {text}")

Quick reference

  • Keyword search wins on codes, names and rare terms; vectors win on paraphrases
  • Postgres: tsvector generated column + GIN index + websearch_to_tsquery
  • ts_rank is not BM25; it has no corpus-wide word rarity
  • RRF score = sum of 1 / (60 + rank) across lists
  • Fetch 20 to 50 candidates per search, rerank them, keep 3 to 10
  • Cross-encoders read query and passage together: accurate but slow
  • Compare vector, hybrid and hybrid + rerank on precision, recall, MRR and latency

Common mistakes

  • Adding scores from different systems directly without normalising.
  • Reranking thousands of candidates and blowing the latency budget.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1In BM25, why does the word E1042 count more than the word login?

Question 2

2Using RRF with k = 60, which document scores higher?

Question 3

3Why not rerank all 100,000 chunks with a cross-encoder?

Question 4

4What does MRR reward?

Question 5

5Why can't you just add a BM25 score to a cosine similarity?

0/5 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Use rank_bm25 to rank 5 short documents for the query reset password, and print the scores.

  2. Exercise 2medium

    Add keyword search to the pgvector chunks table: a generated tsvector column, a GIN index, and a query that returns the top 10 matches for a user query with their rank.

  3. Exercise 3hard

    Compare vector only, hybrid (RRF) and hybrid plus rerank on 30 labelled queries. Report precision at 5, MRR and median latency for each.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is hybrid search always better than vector search?
Usually it helps when users search with exact terms such as codes, names or error messages. Measure it on your own queries; for purely conversational questions the gain can be small.
What is the difference between a reranker and an embedding model?
An embedding model turns each text into a vector separately, so it can search huge collections fast. A reranker reads the query and one passage together and scores them, which is more accurate but only practical for a short list.
Why is k = 60 used in reciprocal rank fusion?
It is the value from the original RRF paper and works well across many datasets. It keeps a single top rank from outweighing consistent good ranks in both lists.
Do I need Elasticsearch for hybrid search?
No. Postgres full-text search plus pgvector can do hybrid search in one database. A dedicated search engine helps if you need true BM25, advanced text analysis or very large scale.
ShareXLinkedInWhatsApp