Skip to content
Visual explainer 4h to learn 5 steps

Compare keyword, vector and hybrid retrieval in PostgreSQL

Run keyword, vector and hybrid retrieval over one question set and explain where each wins or fails.

By Invicly Tech, , in Generative AI, Agentic AI and RAG. About 12 minutes to read.

Topic 10 of 34

In short

Keyword search matches the exact words in a question, vector search matches meaning, and hybrid search combines both rankings. Each one wins on different questions: keywords find error codes and product names, vectors find paraphrases. Running all three over the same labelled question set shows you where each fails instead of guessing.

Think of it like this: Keyword search is a librarian who checks the index for your exact word; vector search is one who knows what you mean even if you used a different word.

Explained simply

Before the assistant can answer, it has to find the right chunks. There are two basic ways to search. Keyword search, also called lexical search, looks for the words in the question. Vector search looks for chunks whose meaning is close to the question, even if they use different words.

Each has blind spots. Ask about error code ERR-4012 and keyword search finds it at once, while vector search may return any chunk about errors. Ask how long you have to get your money back and vector search finds the refund window, while keyword search may find nothing because no chunk says money back.

Hybrid search runs both and merges the two ranked lists. A simple and popular way to merge is reciprocal rank fusion: a chunk gets points for being near the top of either list. Chunks that appear high in both lists rise to the top.

You only learn which method works by testing. Write 20 or so questions, note which chunk IDs should be found for each, and run all three methods. The pattern of hits and misses tells you more than any demo.

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

CompareWhere each retrieval method shines
Keyword (full text)
  • Exact codes like ERR-4012
  • Rare names and SKUs
  • Explainable matches
  • Misses synonyms
Vector
  • Paraphrases and synonyms
  • Questions in plain words
  • Weak on exact identifiers
  • Hard to explain a match
Hybrid
  • Merges both ranked lists
  • Robust across question types
  • Two queries to run
  • Needs tuning and tests
FlowA hybrid query in PostgreSQL
  1. 1
    Filter

    Active, visible, current versions only

  2. 2
    Keyword top 20

    tsvector @@ websearch_to_tsquery

  3. 3
    Vector top 20

    ORDER BY embedding <=> query

  4. 4
    Fuse

    Reciprocal rank fusion

  5. 5
    Return top k

    With chunk IDs and scores

MapDiagnosing a retrieval miss
Expected chunk not in top k
  • Not in the corpus
    • Add content or abstain
  • Excluded by a filter
    • Wrong scope or status
    • Date range too narrow
  • Missed by keywords
    • Synonyms or paraphrase
    • Different text search config
  • Missed by vectors
    • Exact code or name
    • Negation or very short query
  • Found but ranked low
    • Fusion weights
    • Duplicates crowd it out

In depth

Full text search in PostgreSQL

PostgreSQL turns text into a tsvector: a sorted list of normalized words, called lexemes, with stop words such as the removed and words reduced to stems, so refunds and refunded both become refund. A query becomes a tsquery, and the @@ operator tests whether they match. websearch_to_tsquery accepts search-box style input, including quoted phrases and a minus sign to exclude words.

Store the tsvector in a generated column so it stays in sync, and add a GIN index so matching does not scan every row. ts_rank scores how well a chunk matches, using word frequency; ts_rank_cd also rewards matched words that sit close together. Use the same text search configuration, such as english, when building the column and the query.

  • tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', text)) STORED
  • CREATE INDEX ON chunks USING gin (tsv)
  • websearch_to_tsquery('english', 'refund -annual')
  • ts_rank or ts_rank_cd for scoring

Vector similarity and its quiet failure modes

A vector query embeds the question with the same model as the chunks, then orders by distance, for example ORDER BY embedding <=> $1 LIMIT 20. It always returns 20 rows, even when none are relevant, because something is always nearest. That is its main quiet failure: confident-looking results for a question the corpus cannot answer.

Other failures are common. Exact identifiers, part numbers and names often embed poorly. Negations such as not refundable can land next to refundable. Short questions carry little meaning to match. And with an approximate index, a WHERE filter applied after the index scan can return fewer rows than requested; pgvector 0.8 added iterative index scans to help with that, and small labs can avoid it by using an exact scan.

Fusing rankings with reciprocal rank fusion

Keyword scores and vector distances are on unrelated scales, so adding them is meaningless. Reciprocal rank fusion ignores the raw scores. For each chunk, it adds 1 / (k + rank) for every list the chunk appears in, where rank starts at 1 and k is a constant, commonly 60, that stops the very top positions from dominating. A chunk ranked 1st by keywords and 3rd by vectors scores 1/61 + 1/63; one found only by vectors at rank 1 scores 1/61.

You can weight one list more, for example 1.5 for keywords on a corpus full of codes. Keep k and the weights in configuration and change them only with an evaluation run.

SequenceHybrid search for one question
Retriever
Full text index
Vector index
  1. 1Top 20 by ts_rank, filtered
    Retriever to Full text index: Top 20 by ts_rank, filtered
  2. 2Ranked chunk IDs
    Full text index to Retriever: Ranked chunk IDs
  3. 3Top 20 by cosine distance, filtered
    Retriever to Vector index: Top 20 by cosine distance, filtered
  4. 4Ranked chunk IDs
    Vector index to Retriever: Ranked chunk IDs
  5. 5Sum 1 / (60 + rank), keep top k
    Retriever to Retriever: Sum 1 / (60 + rank), keep top k

Metadata filters and failure patterns

Metadata filters narrow the search to rows that are allowed and relevant: status = 'active', visibility in the caller's scopes, a product line, or an effective date range. Put them in each candidate query's WHERE clause, before LIMIT, so the top 20 are the top 20 of eligible rows.

When a labelled question fails, name the pattern so you fix the right stage. Vocabulary mismatch: the user's words differ from the document's, so keywords miss. Identifier blur: vectors miss an exact code. Over-filtering: the right chunk exists but a filter excluded it. Stale win: an old version outranks the current one. Not in corpus: no method can succeed, so the answer should abstain.

  • Vocabulary mismatch: fix with vectors or synonyms
  • Identifier blur: fix with keywords
  • Over-filtering: check the WHERE clause
  • Stale win: filter by status and date
  • Not in corpus: abstain, do not guess

Learn it in 5 short steps

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

  1. 1
    Query with PostgreSQL full text search~50m
  2. 2
    Query with pgvector similarity~50m
  3. 3
    Fuse results into a hybrid ranking~50m
  4. 4
    Apply metadata filters~50m
  5. 5
    Name common failure patterns~50m

Key points

  • PostgreSQL full text search uses tsvector columns, tsquery queries, ts_rank for scoring and a GIN index for speed.
  • pgvector's <=> operator returns cosine distance, so smaller means more similar.
  • Reciprocal rank fusion adds 1 / (k + rank) from each list, so you never compare raw scores from different methods.
  • Apply metadata filters (status, visibility, product, date) in the same SQL query, before limiting results.
  • Judge methods on a labelled question set with expected chunk IDs, not on a few hand-picked demos.

Key terms

Tap a card to flip it. 0/6 known

Examples

sql
SELECT chunk_id, ts_rank(tsv, q) AS score
FROM chunks, websearch_to_tsquery('english', 'refund window ERR-4012') AS q
WHERE tsv @@ q AND status = 'active'
ORDER BY score DESC LIMIT 20;

SELECT c.chunk_id, e.embedding <=> $1 AS distance
FROM chunk_embeddings e JOIN chunks c USING (chunk_id)
WHERE e.model = 'stub-hash-384' AND c.status = 'active'
ORDER BY distance LIMIT 20;

The two candidate lists that hybrid search fuses. $1 is the question's embedding.

A hybrid query with reciprocal rank fusion

Prerequisites: the chunks table with a tsv column and GIN index, and stub embeddings from the previous module. Step 1: get the keyword top 20 and the vector top 20 with the same filters. Step 2: give each row its rank. Step 3: full outer join on chunk_id and sum 1 / (60 + rank), treating a missing rank as 0. Expected evidence: a question quoting ERR-4012 and a paraphrased refund question both return their expected chunk in the top 5.

sql
WITH kw AS (
  SELECT chunk_id, row_number() OVER (ORDER BY ts_rank(tsv, q) DESC) AS r
  FROM chunks, websearch_to_tsquery('english', $1) q
  WHERE tsv @@ q AND status = 'active' AND visibility = ANY($3)
  ORDER BY r LIMIT 20),
vec AS (
  SELECT c.chunk_id, row_number() OVER (ORDER BY e.embedding <=> $2) AS r
  FROM chunk_embeddings e JOIN chunks c USING (chunk_id)
  WHERE e.model = 'stub-hash-384' AND c.status = 'active' AND c.visibility = ANY($3)
  ORDER BY r LIMIT 20)
SELECT chunk_id, COALESCE(1.0 / (60 + kw.r), 0) + COALESCE(1.0 / (60 + vec.r), 0) AS rrf
FROM kw FULL OUTER JOIN vec USING (chunk_id)
ORDER BY rrf DESC LIMIT 8;

Comparing the three methods on a question set

Step 1: write questions.yaml with 20 questions and the expected chunk IDs for each, including codes, paraphrases and one question the corpus cannot answer. Step 2: run keyword, vector and hybrid for every question. Step 3: record hit@5, whether any expected chunk is in the top 5. Expected evidence: keyword wins on code questions, vector on paraphrases, hybrid is best or close to best overall, and the unanswerable question still returns results from vector search, which is why later modules need abstention.

python
methods = {"keyword": keyword_search, "vector": vector_search, "hybrid": hybrid_search}
for name, search in methods.items():
    hits = 0
    for case in cases:
        got = [r.chunk_id for r in search(case["q"], scopes=["public", "internal"])[:5]]
        hits += bool(set(got) & set(case["expected"]))
    print(f"{name:8} hit@5 = {hits}/{len(cases)}")

Quick reference

  • Keyword: tsv @@ websearch_to_tsquery('english', q), ranked by ts_rank
  • GIN index on the tsvector column; same config at index and query time
  • Vector: ORDER BY embedding <=> $q LIMIT n, smaller distance is closer
  • RRF score = sum of 1 / (60 + rank) across lists
  • Filters go in WHERE before LIMIT, in every candidate query
  • Vector search always returns rows, even for unanswerable questions
  • Measure hit@k per method on a labelled set before choosing

Common mistakes

  • Adding raw ts_rank scores to cosine distances; the scales mean different things, so fuse by rank.
  • Filtering after LIMIT, which can leave you with zero results when the top 20 were all filtered out.
  • Using a different text search configuration at index time and query time, so stems never match.

Quick quiz

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

Question 1

1A user asks about 'ERR-4012'. Which method is most likely to find the right chunk first?

Question 2

2In reciprocal rank fusion with k = 60, what does a chunk ranked 1st in only one list score?

Question 3

3Why is adding ts_rank to cosine distance a bad way to combine results?

Question 4

4A billing chunk is the best match, but the caller only has the internal scope. What should the result list contain?

0/4 answered

Practice exercises

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

  1. Exercise 1easy

    Add a generated tsvector column and GIN index to your chunks table, then search for 'refund window'.

  2. Exercise 2medium

    Write 10 labelled questions (4 with exact codes, 4 paraphrases, 2 unanswerable) and report hit@5 for keyword and vector search.

  3. Exercise 3hard

    Implement hybrid search with a configurable keyword weight and k, then find the weight that maximises hit@5 on your set without lowering any single category below its best single-method score.

Check yourself

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

Feel confident about this topic?

Frequently asked questions

Do I need a separate search engine for hybrid search?
No. PostgreSQL full text search plus pgvector can do both in one database, which is enough for many internal assistants.
Is hybrid search always better?
Often, but not always. Measure it; on a corpus of pure prose, vector search alone may score the same with one query less.
What value of k should I use in reciprocal rank fusion?
60 is a common default. Treat it as a tuning setting and change it only when an evaluation shows a benefit.

Go deeper

ShareXLinkedInWhatsApp