Tutorial
Hybrid search and reranking in Postgres
Combine Postgres full-text search and pgvector with reciprocal rank fusion in one SQL query, rerank the top results with a cross-encoder, and measure the gain.
Bookmark
Bookmarks are kept in your free account, so you can find this page again on any device.
Sign in to bookmarkOn this page
Vector search finds passages that mean the same thing as the question. It is weak at exact matches: an error code, a product SKU, a person’s name, a rare acronym. Keyword search is the opposite. Hybrid search runs both and merges the results, and a reranker then reads the merged shortlist properly and puts the best passages first.
You can do all of it in Postgres. This tutorial builds a table with both a tsvector and a pgvector embedding, merges the two rankings with reciprocal rank fusion (RRF) in a single SQL query, reranks the top 20 with an open cross-encoder, and measures each step against a golden set. Checked against pgvector 0.8.7 and sentence-transformers 6.3 on 20 November 2026.
The pipeline
question ──► keyword search (full-text) ─┐
└─► vector search (pgvector) ─┴─► RRF merge (top 20) ─► cross-encoder rerank ─► top 5 to the model
Each stage has one job. Retrieval stages are fast and broad. The reranker is slow and precise, so it only sees a short list.
1. Start Postgres with pgvector
docker run -d --name pg-hybrid -e POSTGRES_PASSWORD=dev -p 5432:5432 pgvector/pgvector:0.8.7-pg17
pip install "psycopg[binary]>=3.3" "pgvector>=0.5" "sentence-transformers>=6.3" numpy
On a managed service (Neon, Supabase, RDS, Cloud SQL and others), pgvector is usually available as an extension you enable.
2. Create the table
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunks (
id bigserial PRIMARY KEY,
doc text NOT NULL,
content text NOT NULL,
embedding vector(384) NOT NULL,
tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', content)) STORED
);
CREATE INDEX chunks_embedding_idx ON chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX chunks_tsv_idx ON chunks USING gin (tsv);
vector(384)matches the output size ofBAAI/bge-small-en-v1.5. Change it if you use another embedder.- The generated
tsvcolumn keeps the full-text index in sync withcontentautomatically. - HNSW with
vector_cosine_opsservesORDER BY embedding <=> query, where<=>is cosine distance.
3. Load chunks
# load.py
from pathlib import Path
import psycopg
from pgvector.psycopg import register_vector
from sentence_transformers import SentenceTransformer
from chunkers import by_headings # from the chunking tutorial
model = SentenceTransformer("BAAI/bge-small-en-v1.5")
rows = [(p.name, c) for p in Path("docs").glob("*.md") for c in by_headings(p.read_text())]
vectors = model.encode([c for _, c in rows], normalize_embeddings=True, batch_size=64)
with psycopg.connect("postgresql://postgres:dev@localhost:5432/postgres") as conn:
register_vector(conn)
with conn.cursor() as cur:
cur.executemany(
"INSERT INTO chunks (doc, content, embedding) VALUES (%s, %s, %s)",
[(doc, content, vec) for (doc, content), vec in zip(rows, vectors)],
)
print(f"loaded {len(rows)} chunks")
register_vector teaches psycopg to send NumPy arrays as vector values.
4. The hybrid query
Reciprocal rank fusion ignores the raw scores, which are not comparable between full-text ranking and cosine distance, and combines ranks instead. Each result gets 1 / (k + rank) from each list it appears in, summed. k is a damping constant; 60 is the value from the original RRF paper and a sensible default.
-- hybrid.sql: parameters %(q)s (question text) and %(qvec)s (question embedding)
WITH semantic AS (
SELECT id, row_number() OVER (ORDER BY dist) AS rank
FROM (
SELECT id, embedding <=> %(qvec)s AS dist
FROM chunks
ORDER BY embedding <=> %(qvec)s
LIMIT 40
) nearest
),
keyword AS (
SELECT id, row_number() OVER (ORDER BY score DESC) AS rank
FROM (
SELECT id, ts_rank_cd(tsv, query) AS score
FROM chunks, websearch_to_tsquery('english', %(q)s) AS query
WHERE tsv @@ query
ORDER BY score DESC
LIMIT 40
) matched
)
SELECT c.id, c.content,
COALESCE(1.0 / (60 + s.rank), 0) + COALESCE(1.0 / (60 + k.rank), 0) AS rrf
FROM semantic s
FULL OUTER JOIN keyword k ON s.id = k.id
JOIN chunks c ON c.id = COALESCE(s.id, k.id)
ORDER BY rrf DESC
LIMIT 20;
How it works:
- The inner queries each fetch their top 40 using an index: HNSW for vectors, GIN for
tsv @@ query. websearch_to_tsqueryaccepts free text the way users type it, including quoted phrases and-exclusions, without syntax errors.- The
FULL OUTER JOINkeeps chunks that only one method found. A chunk found by both gets two contributions and rises.
If filtering matters (tenant, language, document type), add the same WHERE clause to both inner queries. With HNSW, filters are applied after the index scan, so a selective filter can return fewer than 40 rows; set hnsw.iterative_scan = strict_order (pgvector 0.8+) to let the index keep scanning.
5. Rerank
The retrievers score the question and each chunk separately. A cross-encoder reads them together, which is slower but much better at judging relevance. Score the top 20 from RRF and keep the best 5:
# search.py
from pathlib import Path
import psycopg
from pgvector.psycopg import register_vector
from sentence_transformers import CrossEncoder, SentenceTransformer
embedder = SentenceTransformer("BAAI/bge-small-en-v1.5")
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
HYBRID_SQL = Path("hybrid.sql").read_text()
VECTOR_SQL = "SELECT id, content FROM chunks ORDER BY embedding <=> %(qvec)s LIMIT 20"
conn = psycopg.connect("postgresql://postgres:dev@localhost:5432/postgres")
register_vector(conn)
def vector_only(q: str, k: int = 5) -> list[str]:
qvec = embedder.encode(q, normalize_embeddings=True)
rows = conn.execute(VECTOR_SQL, {"qvec": qvec}).fetchall()
return [r[1] for r in rows[:k]]
def hybrid(q: str, k: int = 5) -> list[str]:
qvec = embedder.encode(q, normalize_embeddings=True)
rows = conn.execute(HYBRID_SQL, {"q": q, "qvec": qvec}).fetchall()
return [r[1] for r in rows[:k]]
def hybrid_reranked(q: str, k: int = 5) -> list[str]:
qvec = embedder.encode(q, normalize_embeddings=True)
rows = conn.execute(HYBRID_SQL, {"q": q, "qvec": qvec}).fetchall()
candidates = [r[1] for r in rows]
if not candidates:
return []
scores = reranker.predict([(q, c) for c in candidates])
ranked = sorted(zip(scores, candidates), key=lambda x: x[0], reverse=True)
return [c for _, c in ranked[:k]]
cross-encoder/ms-marco-MiniLM-L6-v2 is a small English reranker that runs on a CPU. For multilingual content, BAAI/bge-reranker-v2-m3 is a common choice. Hosted reranking APIs (Cohere, Voyage, Jina and others) are an alternative when you would rather not run a model; they slot into the same place.
6. Measure each stage
Use the golden set from Chunking strategies for RAG: questions plus an evidence sentence.
# compare.py
import json
from search import hybrid, hybrid_reranked, vector_only
golden = [json.loads(line) for line in open("golden.jsonl", encoding="utf-8")]
norm = lambda s: " ".join(s.lower().split())
for name, fn in [("vector", vector_only), ("hybrid", hybrid), ("hybrid+rerank", hybrid_reranked)]:
hits, rr, misses = 0, 0.0, []
for item in golden:
results = fn(item["q"])
ev = norm(item["evidence"])
rank = next((i for i, c in enumerate(results, 1) if ev in norm(c)), None)
if rank:
hits += 1
rr += 1 / rank
else:
misses.append(item["q"])
n = len(golden)
print(f"{name:14} hit@5={hits / n:.2f} MRR={rr / n:.2f}")
for q in misses[:3]:
print(f" missed: {q}")
Run it and look at two things. Hit@5 tells you whether hybrid search finds evidence that vector search alone missed; the questions that flip are usually ones with exact terms. MRR tells you whether reranking moved the evidence to the top, which matters because models pay most attention to what comes first.
Add questions with exact identifiers (“what does error E1042 mean?”) to your golden set if it has none. Those are where hybrid search earns its keep, and a golden set without them will undersell it.
7. Tune, in this order
- Candidate depth. Fetch more from each retriever (40 → 100) if hit@20 is low. Recall at the retrieval stage caps everything after it.
- Rerank depth. Rerank 20 to 50 candidates. More costs latency linearly; measure where gains stop.
- Weights. If one retriever is clearly better for your data, weight it: multiply its RRF term by, say, 1.5. Change one thing at a time.
- Text configuration.
'english'stems words and drops stop words. For code, IDs or mixed languages,'simple'may work better for the keyword side.
Latency budget
On a laptop CPU, the two index scans take milliseconds; embedding the question takes tens of milliseconds; reranking 20 pairs with a MiniLM cross-encoder takes roughly tens to a few hundred milliseconds depending on chunk length and hardware. Measure on your own hardware with time.perf_counter() around each stage before deciding where to spend effort. If reranking is too slow, rerank fewer candidates or move the model to a GPU.
Pitfalls
Comparing raw scores across retrievers. Cosine distance and ts_rank_cd are on different scales. That is why RRF uses ranks.
Forgetting the filter on one side. If the vector CTE filters by tenant and the keyword CTE does not, you leak documents across tenants.
Reranking a bad shortlist. A reranker can only reorder what retrieval gives it. If the evidence is not in the top 20, fix retrieval first.
Skipping the measurement. Hybrid search adds complexity. Keep it only if your golden set shows it helps.
Next steps
- Decide whether Postgres is enough in pgvector vs Pinecone, Qdrant and Weaviate.
- Build the full pipeline in RAG pipeline in a day.
- Keep evaluating in CI with Evaluate RAG with a golden set.
- Diagnose a bad answer by symptom with the RAG troubleshooting cheat sheet.
- Revisit the basics of the pipeline in RAG fundamentals: what RAG is and how it works.
- Go back to the single-method version in embeddings and vector search.
Covers
Check your understanding
Hybrid search and reranking quiz
Why vector search misses exact terms, reciprocal rank fusion in Postgres, full-text versus BM25, filters on both sides, cross-encoder reranking, hit@5 and MRR, and tuning order.
8 questions · pass mark 70%
Review
Related
- Chunking strategies for RAG, tested
Compare fixed-size, heading-based and semantic chunking on the same documents and questions, measure retrieval hit rate, and pick a strategy with evidence.
- Embeddings and vector search, hands on
Embed documents, store them in Postgres with pgvector, index them and run similarity and hybrid search.
- pgvector vs Pinecone, Qdrant and Weaviate
When storing embeddings in Postgres with pgvector is enough, and when a dedicated vector database such as Pinecone, Qdrant or Weaviate earns its extra cost.
- RAG pipeline in a day with Postgres and pgvector
Ingest your documents, answer with citations and measure retrieval against 20 questions written first.
- Hybrid search
Combining keyword search, such as BM25, with vector search and merging the results into one ranking, often with reciprocal rank fusion.