SteelReed

Search

Search posts, questions…

7. System Design

Hybrid search: full-text, vectors and reranking

Keyword search misses synonyms, vector search misses exact codes: combine both branches with Reciprocal Rank Fusion right inside PostgreSQL, rerank the top 50 with a cross-encoder, and measure with recall@k instead of gut feeling.

27 Nov 20266 min readSenior

–

1. The problem

A support bot uses vector search. A customer asks about "error E1042", and the bot returns the guide for E1024 because the two passages mean nearly the same thing. The old keyword search box, meanwhile, finds nothing for "water-resistant jacket" when the product says "waterproof raincoat".

2. Key idea

Keyword search compares characters; vector search compares approximate meaning. An embedding model squeezes a whole passage into one vector, so "E1042" and "E1024" land almost in the same spot. An inverted index doesn't know "water-resistant" and "waterproof" mean the same. They fail in different places, so combining them fixes most of each other's mistakes.

Query type Full-text Vector
Codes, part numbers, SKUs, function names good poor
Synonyms, long phrasing poor good
Vietnamese typed without diacritics good if stripped at index time depends on the model

2.1 How to combine?

BM25 or ts_rank_cd scores have no upper bound; cosine distance lies in [0, 2]. Adding them lets one side dominate. RRF uses only ranks: first in both branches scores 2/61, first in one scores 1/61. Each branch must fetch wide (50) before fusing.

Approach Use when Don't use when
Full-text only codes, names, logs, short exact queries users ask in natural sentences
Hybrid RRF the default for RAG and search boxes there's no eval set, just "to be safe"
Hybrid + rerank the top 5 decides the answer, a few hundred ms are affordable autocomplete needs under 50 ms

Recall@k: the share of questions with a correct document in the top k. MRR: the mean of 1/rank of the first correct document.

3. In Java

One SQL query runs both branches as CTEs and fuses them with RRF; filter by tenant in both branches.

JAVA
List<Long> hybridSearch(String tenant, String q, float[] v) {
    return jdbc.sql("""
        WITH kw AS (
          SELECT id, row_number() OVER (ORDER BY ts_rank_cd(tsv, query) DESC) AS r
          FROM chunk, websearch_to_tsquery('simple', f_unaccent(:q)) query
          WHERE tenant_id = :tenant AND tsv @@ query
          ORDER BY r LIMIT 50),
        vec AS (
          SELECT id, row_number() OVER (ORDER BY dist) AS r   -- distance: smaller is closer
          FROM (SELECT id, embedding <=> CAST(:v AS vector) AS dist
                FROM chunk WHERE tenant_id = :tenant
                ORDER BY dist LIMIT 50) t)                     -- HNSW serves only ASC LIMIT
        SELECT id FROM (
          SELECT id, 1.0 / (60 + r) AS s FROM kw
          UNION ALL SELECT id, 1.0 / (60 + r) FROM vec) u
        GROUP BY id ORDER BY sum(s) DESC LIMIT 30""")
        .param("tenant", tenant).param("q", q).param("v", v)
        .query(Long.class).list();
}

The tsv column uses the simple configuration plus unaccent for accent-insensitive search. Elasticsearch's rrf retriever does the same job.

Reranking: cross-encoders, latency, fallback

Vector search uses a bi-encoder: query and documents are embedded separately. A cross-encoder reads the pair in one model pass, so it catches fine-grained relations, at the cost of one pass per candidate.

Options: a provider's rerank API, an open model hosted internally (the bge-reranker family), or an LLM as judge. Rerank only 30–50 candidates; set a timeout, say 300 ms, and fall back to the RRF order. A rerank failure must not fail the request. Measure before adding: how much MRR improves, how much p95 grows.

4. Working with AI

Give the AI: the hybrid CTE, a tsvector column migration, a script computing recall@k and MRR from an eval set, query variants (no diacritics, abbreviations, codes).

Check in AI-written code:

  • The vector branch sorts <=> ascending.
  • Each branch has a wide LIMIT (30–100) before fusing.
  • Tenant and permission filters appear in both branches.
  • recall@k is reported before and after the change on the same eval set.

5. Exercises

Exercise 1: An AI-written vector branch

The AI wrote this, described as "fetch the 50 most relevant chunks for RRF". Hybrid recall is lower than full-text alone.

SQL
vec AS (
  SELECT id, row_number() OVER (ORDER BY dist DESC) AS r
  FROM (SELECT id, embedding <=> CAST(:v AS vector) AS dist
        FROM chunk WHERE tenant_id = :tenant
        ORDER BY dist DESC LIMIT 50) t)

Find the bug.

Solution to Exercise 1

<=> returns a distance, not a similarity. DESC puts the 50 farthest chunks on top, and RRF adds them as if relevant: the vector branch only adds noise.

Test: a case where a chunk nearly repeats the question verbatim must rank first in the vector branch. Fix: drop both DESCs. Also: an HNSW index only serves ORDER BY embedding <=> ... ASC LIMIT n, so the DESC version scans the whole table too.

Exercise 2: Reranking slows everything

After adding reranking, /search p95 went from 180 ms to 1.4 s, and 6% of requests time out at the gateway (2 s). Traces: the rerank span takes 1.1 s, each request sends 200 candidates, and the provider returns 429 at peak. Diagnose, the 15-minute action, the root fix.

Solution to Exercise 2

200 synchronous candidates are too many: time scales with candidate count, call volume exceeds quota so you get 429s, and retries slow things further.

15 minutes: turn reranking off with a config flag and fall back to the RRF order. Root fix: a 30–50 candidate window, a 300 ms timeout with RRF fallback, a circuit breaker on the rerank API; re-measure MRR to confirm 50 candidates still suffice.

Summary

  • Full-text catches codes and names; vectors catch synonyms.
  • Fuse by rank with RRF k = 60, each branch fetching wide.
  • Filter permissions in both branches.
  • Rerank after fusion, a few dozen candidates, with timeout and fallback.
  • Measure recall@k and MRR before and after every change.

Read more: Elasticsearch: analyzers, inverted index and mapping.

Practice interview questions on this topic

All AI & LLM questions →

Loading comments…