Hybrid Search in PostgreSQL: Full-Text Search plus pgvector with RRF
Picture a support search box. A customer pastes in the exact error from their screen, PG-1042, and the search comes back with three articles about connection problems in general. The one article that names PG-1042 is in third place. That is exactly the problem hybrid search in PostgreSQL is good at fixing.
Then a different customer types “too many clients connecting”, and a plain keyword search finds almost nothing, because the right article talks about a “connection pool” being “exhausted” instead.
Those are the two failure modes of search, and most systems only fix one of them. Vector search understands meaning but is surprisingly bad at exact terms such as error codes, SKUs, function names and surnames. Keyword search is the reverse.
Hybrid search runs both kinds of search and merges the results. You do not need a separate search engine for this. PostgreSQL has had good full-text search for years, and with the pgvector extension the same table can hold embeddings too. In this post I build a small working example, show where each kind of search fails on its own, and then combine them with Reciprocal Rank Fusion in one SQL query and a short Python function. Every output below is copied from a real run.
What each kind of search is good at
| Query | Keyword (full-text) search | Vector (semantic) search |
|---|---|---|
Exact codes and identifiers (PG-1042, ERR_SSL) |
Strong: exact token match | Weak: the code carries little meaning for the model |
| Paraphrases (“too many clients connecting”) | Weak: needs the same words | Strong: matches on meaning |
| Rare names and jargon | Strong | Often weak, depending on the model |
| Typos and synonyms | Weak without extra work | Fairly strong |
| “Is anything relevant at all?” | Returns nothing when nothing matches | Always returns the k nearest rows, relevant or not |
Most real search boxes get a mix of both kinds of query, which is why combining them usually beats either one alone.
Setting up PostgreSQL and pgvector for hybrid search
If you do not have a database with pgvector yet, my guide to running pgvector in Docker with Docker Compose gets one running in a few minutes. I tested everything below on the pgvector/pgvector:0.8.7-pg18 image (PostgreSQL 18, pgvector 0.8). Any recent PostgreSQL with pgvector 0.5 or later will run it, apart from one setting mentioned under pitfalls that needs 0.8.
The table keeps the text, an embedding, and a generated tsvector column for full-text search:
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE docs (
id bigserial PRIMARY KEY,
title text NOT NULL,
body text NOT NULL,
embedding vector(3) NOT NULL,
search tsvector GENERATED ALWAYS AS (
setweight(to_tsvector('english', title), 'A') ||
setweight(to_tsvector('english', body), 'B')
) STORED
);
CREATE INDEX docs_search_idx ON docs USING gin (search);
CREATE INDEX docs_embedding_idx ON docs USING hnsw (embedding vector_cosine_ops);
A few details worth noting:
- The generated column keeps the full-text index in step with the text automatically. You never have to remember to update it.
setweightmarks words from the title as weight A and words from the body as weight B, so a match in the title ranks higher.- Two indexes: a GIN index for the
tsvectorand an HNSW index for the vectors. If you want to know how HNSW works, see HNSW vector search explained. vector_cosine_opsmeans the index is built for cosine distance, the<=>operator. The index only helps queries that use the same operator.
To keep the example readable, the embeddings have three dimensions instead of the hundreds or thousands a real model produces. Think of the three numbers as roughly “about databases”, “about errors” and “about cooking”. In a real application you would get these from an embedding model; if you are choosing one, I compared two popular options in Nomic vs OpenAI embeddings.
-- Toy 3-dimensional "embeddings": roughly [databases, errors, cooking].
INSERT INTO docs (title, body, embedding) VALUES
('Fix error PG-1042 on login', 'Error PG-1042 means the connection pool is exhausted. Raise max_connections or add PgBouncer.', '[0.6, 0.8, 0.0]'),
('Why is my Postgres connection refused', 'The server may not be listening on the right address, or a firewall blocks port 5432.', '[0.8, 0.6, 0.0]'),
('Tuning PostgreSQL for many clients', 'A connection pooler lets thousands of clients share a small number of database connections.', '[0.9, 0.4, 0.0]'),
('Sourdough starter troubleshooting', 'If your starter will not rise, keep it warmer and feed it more often.', '[0.0, 0.3, 0.95]'),
('Database backups with pg_dump', 'pg_dump writes a consistent snapshot of one database to a file.', '[1.0, 0.0, 0.0]');
Keyword search on its own
websearch_to_tsquery turns what a user types into a full-text query using the same rules as a web search box: quoted phrases, or, and - to exclude a word. ts_rank_cd scores each match.
SELECT title, round(ts_rank_cd(search, q)::numeric, 3) AS rank
FROM docs, websearch_to_tsquery('english', 'PG-1042') AS q
WHERE search @@ q
ORDER BY rank DESC;
title | rank ----------------------------+------- Fix error PG-1042 on login | 1.400 (1 row)
That is exactly right: one document mentions the code, and it comes back with a high score. Now try a question phrased the way a person would ask it, “too many clients connecting”. Keyword search returns only “Tuning PostgreSQL for many clients”, because that is the only row containing all of the important words after stemming. The login error post, which is really about the same problem, is missed because it says “connection pool is exhausted” instead.
Vector search on its own
For the same question, the embedding model would give a vector close to “databases” with some “errors” in it. Here that is [0.85, 0.5, 0.0]. The <=> operator returns cosine distance, where 0 means the same direction:
SELECT title, round((embedding <=> '[0.85, 0.5, 0.0]')::numeric, 4) AS distance FROM docs ORDER BY embedding <=> '[0.85, 0.5, 0.0]' LIMIT 3;
title | distance ---------------------------------------+---------- Why is my Postgres connection refused | 0.0062 Tuning PostgreSQL for many clients | 0.0064 Fix error PG-1042 on login | 0.0772 (3 rows)
Vector search finds all three connection-related posts, even though none of them uses the words “too many clients connecting”. But notice two things. First, the post that actually names the error code is only third. Second, if you asked for five rows instead of three, you would also get the pg_dump post and the sourdough post. Vector search always returns the k nearest rows, whether or not they are relevant. There is no “no results” answer.
Hybrid search in PostgreSQL with Reciprocal Rank Fusion
The obvious way to combine them is to add the scores together, but the scores are not comparable. ts_rank_cd can be any positive number and depends on document length and weights, while cosine distance sits between 0 and 2. Rescaling them so they line up is fiddly and breaks when your data changes.
Reciprocal Rank Fusion avoids the problem by ignoring the scores and using only each document’s position in each list. A document’s RRF score is:
score(d) = Σ 1 / (k + ranki(d))
summed over every list the document appears in, where rank is 1 for the top result. A document missing from a list adds nothing for that list. The constant k stops the top few positions from dominating; 60 is the value used in the original paper by Cormack, Clarke and Büttcher (2009), and it works well in practice. With k = 60, being first in a list is worth 1/61 ≈ 0.0164 and being tenth is worth 1/70 ≈ 0.0143, so a document that appears in both lists almost always beats one that tops only a single list.
Do not try to make two different scores agree. Compare ranks instead.
In SQL, each search becomes a common table expression that returns ids and ranks, and a FULL OUTER JOIN keeps documents that appear in only one list:
WITH params AS (
SELECT websearch_to_tsquery('english', 'PG-1042 connections') AS q,
'[0.85, 0.5, 0.0]'::vector AS v
),
keyword AS (
SELECT d.id,
row_number() OVER (ORDER BY ts_rank_cd(d.search, p.q) DESC) AS rank
FROM docs d, params p
WHERE d.search @@ p.q
ORDER BY ts_rank_cd(d.search, p.q) DESC
LIMIT 20
),
semantic AS (
SELECT d.id,
row_number() OVER (ORDER BY d.embedding <=> p.v) AS rank
FROM docs d, params p
ORDER BY d.embedding <=> p.v
LIMIT 20
)
SELECT d.title,
round((COALESCE(1.0 / (60 + k.rank), 0) +
COALESCE(1.0 / (60 + s.rank), 0))::numeric, 5) AS rrf_score,
k.rank AS keyword_rank,
s.rank AS semantic_rank
FROM keyword k
FULL OUTER JOIN semantic s ON s.id = k.id
JOIN docs d ON d.id = COALESCE(k.id, s.id)
ORDER BY rrf_score DESC
LIMIT 5;
title | rrf_score | keyword_rank | semantic_rank ---------------------------------------+-----------+--------------+--------------- Fix error PG-1042 on login | 0.03227 | 1 | 3 Why is my Postgres connection refused | 0.01639 | | 1 Tuning PostgreSQL for many clients | 0.01613 | | 2 Database backups with pg_dump | 0.01563 | | 4 Sourdough starter troubleshooting | 0.01538 | | 5 (5 rows)
This is the result we wanted. The error-code post appears in both lists (first for keywords, third for meaning), so it rises to the top. The two other connection posts follow on the strength of their semantic match. The irrelevant rows are still there at the bottom because vector search always returns something, but their scores are clearly lower, and in a real system you would show only the top few.
Calling hybrid search in PostgreSQL from Python
The same query works from application code. This version uses psycopg 3 and the pgvector Python package, which teaches psycopg how to send NumPy arrays as vectors. Install them with pip install "psycopg[binary]" pgvector numpy.
import os
import numpy as np
import psycopg
from pgvector.psycopg import register_vector
HYBRID_SQL = """
WITH keyword AS (
SELECT id,
row_number() OVER (ORDER BY ts_rank_cd(search, query) DESC) AS rank
FROM docs, websearch_to_tsquery('english', %(text)s) AS query
WHERE search @@ query
ORDER BY ts_rank_cd(search, query) DESC
LIMIT %(pool)s
),
semantic AS (
SELECT id,
row_number() OVER (ORDER BY embedding <=> %(embedding)s) AS rank
FROM docs
ORDER BY embedding <=> %(embedding)s
LIMIT %(pool)s
)
SELECT d.id, d.title,
COALESCE(1.0 / (%(k)s + k.rank), 0) +
COALESCE(1.0 / (%(k)s + s.rank), 0) AS score
FROM keyword k
FULL OUTER JOIN semantic s ON s.id = k.id
JOIN docs d ON d.id = COALESCE(k.id, s.id)
ORDER BY score DESC
LIMIT %(limit)s
"""
def hybrid_search(conn, text, embedding, limit=5, pool=20, k=60):
params = {"text": text, "embedding": embedding,
"limit": limit, "pool": pool, "k": k}
return conn.execute(HYBRID_SQL, params).fetchall()
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
register_vector(conn)
# In a real app, the query embedding comes from the same model
# you used for the documents.
query_embedding = np.array([0.85, 0.5, 0.0])
for doc_id, title, score in hybrid_search(conn, "PG-1042 connections",
query_embedding, limit=3):
print(f"{score:.5f} {title}")
Run it with DATABASE_URL set to your connection string, for example postgresql://postgres:postgres@localhost:5432/postgres:
0.03227 Fix error PG-1042 on login 0.01639 Why is my Postgres connection refused 0.01613 Tuning PostgreSQL for many clients
Everything is passed as a query parameter, including the user’s text, so there is no risk of SQL injection, and the database does all of the work in one round trip.
Tuning hybrid search in PostgreSQL for your data
The query above works well as it is. When you want to adjust it, these are the levers, roughly in the order I would try them.
How many candidates each side brings
Each CTE keeps its top 20 rows before fusion. A larger pool gives a document ranked lower in one list a chance to be lifted by the other, at a small cost in speed. Somewhere between 20 and 100 is common.
The k constant
A smaller k, say 10 to 20, rewards top positions more strongly. A larger k flattens the differences. Start at 60 and change it only if your measurements say so.
Weighting one side
If exact matches matter more in your domain, multiply that side’s term, for example 1.5 * COALESCE(1.0 / (60 + k.rank), 0). Keep the weights simple, and test them.
Filters belong inside both searches
Put filters such as tenant, language or date inside both CTEs. If you filter after fusion, you can end up with far fewer results than you asked for.
Reranking on top
Hybrid search makes an excellent first stage. For the best quality, pass the top 20 to 50 fused results to a cross-encoder reranker and keep its top few. Techniques like contextual retrieval improve the first stage further by adding context to each chunk before it is indexed.
Whatever you change, measure it on a set of real queries from your users rather than judging by eye. Search changes that look better on three hand-picked queries often look worse on three hundred.
Five hybrid search pitfalls in PostgreSQL to check first
websearch_to_tsquery requires every word
“PG-1042 connections” only matches rows that contain both terms, which is why only one row came back from the keyword side in the hybrid example. When users type long natural-language questions, keyword search may return little or nothing, and the result falls back to vector search alone. That is usually fine, but it is worth knowing. Users can type or between words to match either.
Filtered HNSW queries can return too few rows
An HNSW index scan looks at a limited number of candidates (40 by default, set by hnsw.ef_search) and applies the WHERE clause afterwards. With a selective filter you can get fewer rows than your LIMIT. In pgvector 0.8 and later, run SET hnsw.iterative_scan = relaxed_order; so the index keeps scanning until it has enough rows.
The text search configuration matters
'english' stems words (connecting becomes connect) and drops stop words. Use the configuration for your content’s language, and use 'simple' for identifiers you never want stemmed.
Queries and documents need the same embedding model
Vectors from different models live in different spaces. Mixing them gives distances that mean nothing, and nothing warns you.
The index operator and the query operator must match
An index built with vector_cosine_ops is ignored by a query that orders by <-> (Euclidean distance). Check with EXPLAIN that your query actually uses the index.
The takeaway on hybrid search in PostgreSQL
Keyword search finds exact terms; vector search finds meaning. Hybrid search in PostgreSQL gives you both. PostgreSQL with pgvector can do both in the same table, and Reciprocal Rank Fusion merges them by rank, so you never have to make two incompatible scores agree. The whole thing is one SQL query you can call from any language, with no extra service to run.
Further reading
- PostgreSQL documentation: Full Text Search
- pgvector on GitHub, including the notes on HNSW, filtering and iterative index scans
- Cormack, Clarke and Büttcher, Reciprocal Rank Fusion outperforms Condorcet and individual Rank Learning Methods (SIGIR 2009)
- On this site: pgvector in Docker, HNSW explained, vector quantisation and building a RAG system
The post Hybrid Search in PostgreSQL: Full-Text Search plus pgvector with RRF appeared first on Alpesh Kumar.