Hybrid search

Part of the free LogicWiz Data Engineering course, Module 16: Databases for AI agents. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is 10:05 on Monday, and two tickets land a minute apart. Ken pastes "error PAY-402" from the checkout page, and the assistant explains card payments in general: the one chunk that names PAY-402 came third. Rosa asks "can I return my Northwind lamp after 3 weeks?" and the assistant says yes, she has 60 days. That is Acme's policy. Northwind gives 14.

You'll learn to

  • Run keyword search in Postgres and see where it beats vectors
  • Fuse two ranked lists with reciprocal rank fusion
  • Put tenant filters inside both searches, before the limit
  • Say what a reranker adds and what it costs

Learn

Ken's code came third

Start with Ken. Vector search matches meaning, and "error PAY-402" means "something went wrong with a payment". Three chunks are about that, and the search ranks them by how payment-like they are.

It cannot see what a person sees at once: one of those chunks contains the exact code Ken pasted. To an embedding model, "PAY-402" and "PAY-404" look almost the same. Error codes, order numbers, product codes and names are where search by meaning is weakest.

What vector search returned for "error PAY-402"

Bars of cosine similarity for the four nearest chunks: chunk 5 about failed card payments 0.994, chunk 7 about pending charges 0.947, chunk 6 which explains PAY-402 at 0.930, and chunk 4 about refunds 0.744.

The scores are cosine similarities, best first. The green bar is the only chunk that contains "PAY-402", and it is third.

A search that matches words

The old kind of search is good at exactly this. Keyword search looks for the words themselves. Postgres has it built in, under the name full-text search.

It does a little more than compare letters. It cuts each text into word stems, in lower case, with filler words such as "the" dropped. Postgres calls these stems lexemes. So "returned" and "returns" both become return, and a search for one finds the other.

Run it for Ken's question.

Keyword search in Postgres

SELECT chunk_id,
       content,
       ROUND(ts_rank(to_tsvector('english', content),
                     plainto_tsquery('english', 'error PAY-402'))::numeric, 4) AS rank
FROM chunks
WHERE to_tsvector('english', content) @@ plainto_tsquery('english', 'error PAY-402')
ORDER BY rank DESC, chunk_id;

One row: chunk 6. to_tsvector turns the text into lexemes. plainto_tsquery does the same to the question and joins its words with AND. @@ means "matches", and ts_rank scores how well. In production the tsvector is a stored column with a GIN index. Use websearch_to_tsquery when you want or and quoted phrases.

One question, two rankings: "error PAY-402"

ChunkVector rank (similarity)Keyword rank
5: If a card payment fails, the order waits...1 (0.994)no match
7: A failed payment can show as a pending charge...2 (0.947)no match
6: Error PAY-402 means your bank declined the charge...3 (0.930)1
4: Refunds go back to the original payment method...4 (0.744)no match

Vector search alone puts the one chunk that names the error third. Keyword search alone finds only that chunk, and would find nothing at all for "my card was refused". You want one list that uses both.

Two lists, one answer

Running both searches and merging the two lists is called hybrid search. Each method covers the other's blind spot.

How do you merge? You cannot add the scores. Cosine similarity runs from -1 to 1, ts_rank might be 0.06 or 0.27, and the two scales mean nothing to each other. But a rank means the same in every list: "this was third best".

So each chunk earns 1 / (k + rank) from every list it appears in, and you add up what it earned. k is a constant, usually 60, that keeps a single first place from deciding everything. A list that misses a chunk adds nothing for it. This is called reciprocal rank fusion, or RRF.

Two lists fused by rank

Four steps of reciprocal rank fusion for "error PAY-402": the vector list ranks chunks 5, 7, 6 and 4 and the keyword list ranks chunk 6 first; every entry earns 1 over 60 plus its rank; chunk 6 adds 0.0159 and 0.0164 to reach 0.0323; sorted by the sum, chunk 6 is first.

  1. Two lists, best first. Vector search ranks chunk 6 third. Keyword search has one hit: chunk 6, in first place.

  2. Every entry earns 1 / (60 + rank). First place earns 1/61 = 0.0164, second 1/62 = 0.0161, third 1/63 = 0.0159, fourth 1/64 = 0.0156.

  3. Add up what each chunk earned. Chunk 6 is in both lists: 0.0159 + 0.0164 = 0.0323. The other three are in one list only, so they keep one score each.

  4. Sort by the sum. Chunk 6 jumps from third to first. Two searches agreeing on a chunk beat one search putting another chunk on top.

Follow the green boxes: chunk 6 is third in one list, first in the other, and first in the fused list.

Hybrid search with RRF in one query

WITH vector_hits AS (
  SELECT chunk_id,
         ROW_NUMBER() OVER (ORDER BY cosine_sim(embedding, '{0.1,0,0.9,0.2}') DESC, chunk_id) AS rnk
  FROM chunks
  ORDER BY rnk
  LIMIT 5
),
keyword_hits AS (
  SELECT chunk_id,
         ROW_NUMBER() OVER (ORDER BY ts_rank(to_tsvector('english', content), q) DESC, chunk_id) AS rnk
  FROM chunks, plainto_tsquery('english', 'error PAY-402') AS q
  WHERE to_tsvector('english', content) @@ q
  ORDER BY rnk
  LIMIT 5
)
SELECT chunk_id,
       ROUND(SUM(1.0 / (60 + rnk)), 4) AS rrf
FROM (
  SELECT chunk_id, rnk FROM vector_hits
  UNION ALL
  SELECT chunk_id, rnk FROM keyword_hits
) AS both_lists
GROUP BY chunk_id
ORDER BY rrf DESC, chunk_id
LIMIT 3;

Chunk 6 comes first with 0.0323, the number from the walkthrough. Each CTE is one ranked list cut to its top 5 (real systems keep 20 to 100 per list before fusing). ROW_NUMBER turns scores into ranks, with chunk_id as the tie-breaker. UNION ALL stacks the lists and GROUP BY adds up each chunk's scores. A third list, say a search on titles, is one more CTE in the union.

RRF in Python

def rrf(rankings, k=60):
    """rankings: lists of ids, best first. Returns all ids by fused score, best first."""
    scores = {}
    for ranking in rankings:
        for rank, chunk_id in enumerate(ranking, start=1):
            scores[chunk_id] = scores.get(chunk_id, 0) + 1 / (k + rank)
    return sorted(scores, key=lambda c: (-scores[c], c))

vector_list = [5, 7, 6, 4]      # cosine similarity, best first
keyword_list = [6]              # full-text match for "PAY-402"
print(rrf([vector_list, keyword_list]))

The same fusion in a few lines: [6, 5, 7, 4]. Teams fuse in application code like this when the two lists come from different systems, for example Elasticsearch for keywords and a vector database for meaning.

Remember: fuse ranks, never raw scores. A chunk that two searches both found beats a chunk that one search ranked first.

Rosa got another seller's policy

Now Rosa. She asked about a Northwind lamp, and the assistant quoted 60 days. That is Acme's rule. Northwind's is 14.

SwiftKart is a marketplace. Sellers such as Northwind and Acme keep their own help pages in the same index. Each owner of data in a shared system is called a tenant, and every chunk carries a tenant column.

Acme's returns chunk is close in meaning to Rosa's question, so the search ranked it second. Nothing told the search "Northwind only".

The lamp question, with no filter

Bars of cosine similarity for the five nearest chunks to the lamp question: chunk 8 from Northwind 0.995, chunk 11 from Acme 0.931, chunk 3 from SwiftKart 0.904, chunk 4 from SwiftKart 0.599 and chunk 9 from Northwind 0.502.

The five nearest chunks to Rosa's question, best first. Only the green bars are Northwind's. The model read three different return periods and picked the wrong one.

Filter before you rank

The fix is a filter on tenant. Where you put it matters.

Put it inside each search, before the ranking and the LIMIT. This is called a pre-filter: only Northwind's chunks are ranked at all.

The tempting shortcut is a post-filter: take the top 5 overall, then drop the other tenants' rows. Look at the bars again. Of those five, two are Northwind's. Filter afterwards and a LIMIT 5 hands back two rows, while Northwind's third chunk sat at rank 8, never looked at.

A tenant filter is also a security boundary, so Lesson 16.6 enforces it in the database itself.

The same search for one seller

WITH vector_hits AS (
  SELECT chunk_id,
         ROW_NUMBER() OVER (ORDER BY cosine_sim(embedding, '{0.1,0.9,0,0.4}') DESC, chunk_id) AS rnk
  FROM chunks
  WHERE tenant = 'northwind'
  ORDER BY rnk
  LIMIT 5
),
keyword_hits AS (
  SELECT chunk_id,
         ROW_NUMBER() OVER (ORDER BY ts_rank(to_tsvector('english', content), q) DESC, chunk_id) AS rnk
  FROM chunks, plainto_tsquery('english', 'return lamp') AS q
  WHERE tenant = 'northwind'
    AND to_tsvector('english', content) @@ q
  ORDER BY rnk
  LIMIT 5
)
SELECT c.chunk_id,
       ROUND(SUM(1.0 / (60 + h.rnk)), 4) AS rrf,
       c.content
FROM (
  SELECT chunk_id, rnk FROM vector_hits
  UNION ALL
  SELECT chunk_id, rnk FROM keyword_hits
) AS h
JOIN chunks AS c ON c.chunk_id = h.chunk_id
GROUP BY c.chunk_id, c.content
ORDER BY rrf DESC, c.chunk_id
LIMIT 3;

The filter sits in both lists, so only Northwind's three chunks are ranked, with the 14-day rule on top. Delete the two WHERE tenant = 'northwind' lines (keep the to_tsvector condition) and Acme's chunk 11 takes second place with its 60-day rule.

An index filters too late

One more trap hides here, and it only shows at real scale, with an index.

An HNSW index does not rank every row. It walks its graph and hands back a short list of candidates: about hnsw.ef_search of them, 40 by default. pgvector's README is explicit: with an approximate index, the filter is applied after the index is scanned.

So even with the WHERE in the right place, the database takes the 40 nearest candidates from all tenants first, and only then keeps the rows that pass the filter.

If the filter keeps a share s of the rows, about 40 × s candidates survive. A seller with 10% gets 4 rows for a LIMIT 5. In the real help centre Northwind owns 3% of the chunks: 40 × 0.03 = 1.2 rows.

Three fixes, cheapest first:

  • Exact search on the filtered rows when the filter keeps few rows. A B-tree index on tenant and a scan of 5,000 vectors beats a graph walk over 5 million.
  • Iterative index scans (pgvector 0.8.0 and later): the index keeps walking until enough rows pass.
  • A partial index or a partition per large tenant, so the index holds only that tenant's rows.

Rows left from 40 candidates after the filter

Bars showing the expected rows that survive a filter applied after 40 index candidates: 20 when the filter keeps half the rows, 4 at 10 percent, 1.2 at 3 percent and 0.4 at 1 percent.

Each bar is how many rows you can expect back with hnsw.ef_search = 40. The same sum applies to row-level security on a vector table (Lesson 16.6): a policy is a filter the index cannot use.

Measure it: post-filter against pre-filter

import numpy as np

rng = np.random.default_rng(3)
docs = rng.standard_normal((5000, 16))
docs /= np.linalg.norm(docs, axis=1, keepdims=True)
queries = rng.standard_normal((200, 16))
queries /= np.linalg.norm(queries, axis=1, keepdims=True)
u = rng.random(5000)                      # a fixed number per chunk decides its seller

EF_SEARCH, K = 40, 5
for share in [0.5, 0.1, 0.05, 0.01]:
    mine = u < share                      # this seller's chunks
    got, recall = [], []
    for q in queries:
        sims = docs @ q
        candidates = np.argsort(-sims, kind="stable")[:EF_SEARCH]       # what the index hands back
        post = [c for c in candidates if mine[c]][:K]                     # filter afterwards
        pre = np.flatnonzero(mine)[np.argsort(-sims[mine], kind="stable")[:K]]  # filter first, exact
        got.append(len(post))
        recall.append(len(set(post) & set(pre)) / K)
    print(f"seller owns {share:4.0%}: rows returned {np.mean(got):.2f} of {K}, recall@5 {np.mean(recall):.2f}")

The candidates here are the exact 40 nearest, the best an HNSW scan could do, and the post-filter still fails as the seller gets smaller. At 10% the average is 3.44 rows, not 4, because LIMIT 5 caps the lucky queries. Filtering first with exact search is always right. The only question is whether it is fast enough for that tenant's number of rows.

A second, slower opinion

One last step can sharpen the short list. Both searches score the question and each chunk separately: the chunk's vector was computed long before the question existed.

A reranker reads the question and one chunk together and gives a relevance score. The usual kind is called a cross-encoder. It is more accurate, and far more work, because it runs a model over every pair:

  • Embedding the question: about 20 tokens, once.
  • Reranking 50 candidates of 500 tokens: 50 × (500 + 20) = 26,000 tokens per question.

So the shape is always the same. Retrieve 20 to 50 candidates cheaply, rerank them, and give the best 3 to 5 to the model. The reranker cannot start until retrieval has finished, so its time adds straight onto the answer's.

The whole retrieval pipeline

A graph: the question goes to a vector search and a keyword search, each filtered by tenant; their ranked lists meet in reciprocal rank fusion; the fused top 50 go to a cross-encoder reranker; its top 5 go to the model.

Follow the question from left to right. The list gets shorter at every arrow: every chunk, then 50, then 5.

Tokens a model reads for one question

Bars comparing tokens processed per question: 20 to embed the question, 10,400 to rerank 20 candidates, 26,000 to rerank 50 candidates, and 4,530 for the answering model.

Compare the amber bars with the others. Halving the candidates halves the reranking work, and the evaluation set tells you whether recall survives. A reranking model is usually much smaller than the answering model, so each of its tokens costs less. Cache scores by (question hash, chunk hash) for repeated questions.

Filtering after the LIMIT is the classic hybrid bug. ORDER BY similarity DESC LIMIT 5 in a subquery, with WHERE tenant = 'northwind' outside it, looks harmless and returns fewer rows than you asked for, sometimes none, with no error. An approximate index does the same thing silently even when the WHERE is in the right place. Catch it by counting: log the rows each search returned, and alert when they fall below the LIMIT.

Numbers to remember

WhatValueGood to know
RRF score1 / (k + rank), summed over the listsk = 60 comes from the paper that introduced RRF (Cormack, Clarke and Buettcher, 2009) and is Elasticsearch's default rankconstant
What k doesk = 60: rank 10 earns 1/70, only 13% less than rank 1. k = 1: rank 10 earns 1/11, five and a half times less than rank 1A large k rewards agreement between the lists. A small k lets one first place nearly decide alone
Candidates per list before fusing20 to 100Elasticsearch calls it rankwindowsize. A chunk outside every window scores 0
A weight per listOffered by some enginesUse it when one method is known to suit your questions better. Tune it on the evaluation set, not by feel
hnsw.efsearch40 by defaultThe candidates an HNSW scan hands back before the filter runs
hnsw.iterativescan = relaxedorderpgvector 0.8.0 and laterKeeps walking up to hnsw.maxscantuples, 20,000 by default. Rows may come back slightly out of distance order: the README puts the query in a MATERIALIZED CTE and sorts its result again
RerankingRetrieve 20 to 50, keep 3 to 550 candidates: 26,000 tokens a question, 1,300 times the 20 tokens of embedding it. 20 candidates: 10,400

In Postgres, hybrid search is pgvector plus a tsvector column with a GIN index, fused with RRF as above (some teams add the ParadeDB extension for BM25 ranking, the scoring search engines use). Elasticsearch, Azure AI Search, Weaviate and Qdrant have hybrid modes built in, several with RRF. Hosted rerankers (such as Cohere Rerank) and open models (such as the BGE rerankers) do the reranking.

What changed at SwiftKart

By lunch both tickets are closed. Ken's "error PAY-402" now returns chunk 6 first: his bank declined the charge, and no money was taken. Rosa's search only ranks Northwind's chunks, so the assistant reads the 14-day rule and tells her that three weeks is too late.

The assistant can now find the right text. It still forgets everything the moment a chat ends. Hana told it last week that she wants updates by email, and today it does not know her. Lesson 16.5 gives the agent a memory.

In one line

Hybrid search runs keyword and vector search with the tenant filter inside both, fuses their ranks with RRF, 1 / (60 + rank), and can pass the short list to a reranker.

Interview corner

What is hybrid search, and why use it?

Hybrid search runs a keyword search (BM25 or Postgres full-text) and a vector search for the same question and merges the two ranked lists. Keywords catch exact tokens such as codes, names and SKUs; vectors catch paraphrases. Together they give better recall than either alone, which you confirm on an evaluation set.

How does reciprocal rank fusion work?

Each list ranks its candidates; a candidate gets 1 / (k + rank) from every list it appears in, usually with k = 60, and the scores are summed. It uses ranks, not raw scores, because BM25 scores and cosine similarities are on unrelated scales. Items found by several methods rise to the top, and there is nothing to train.

How do you combine metadata filters with an approximate vector index?

An HNSW scan returns about ef_search candidates (40 by default in pgvector) and the WHERE clause runs on those, so a filter matching 10% of rows leaves about 4: the query silently returns fewer rows than the LIMIT. For large tenants I would use a partition or a partial index so the index only holds rows that pass; for small ones, exact search on the B-tree-filtered rows; otherwise pgvector 0.8 iterative scans, which keep walking up to hnsw.max_scan_tuples (20,000 by default). Then I measure recall and rows returned with the filter on, per tenant size.

Would you add a reranker? What does it cost?

A cross-encoder reads the question with each candidate, so reranking 50 candidates of 500 tokens is 26,000 tokens of model work per question, against about 20 tokens to embed the question, and it adds its latency after retrieval. I would add it only if the evaluation set shows a real gain in recall@5 or nDCG, rerank the smallest candidate list that keeps the gain (often 20 to 50), and cache scores for repeated question and chunk pairs. If latency is tight, a better hybrid set-up or chunking often gets most of the gain for free.