Databases · Advanced · 24 min
Combine keyword and vector search in PostgreSQL for hybrid search
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · PostgreSQL 18.7 · pgvector 0.8.7
You will add keyword search beside vector search on a table of document chunks, merge the two ranked lists with reciprocal rank fusion in one SQL function, and show with a ten-question test set that the merged list finds answers each method misses on its own.
On this page
Vector search finds passages that mean the same thing as a question, even when they share no words with it. It is weak at the opposite job. Ask an embedding model about E5102 or FWBP30 and it sees a string with little meaning, so the chunk that contains that exact code may not come near the top. Keyword search has the reverse problem: it finds the code at once, but a question phrased in different words from the document finds nothing useful.
Hybrid search runs both and merges the results. In this tutorial you do it inside PostgreSQL, next to the vectors you already store with pgvector. You add a tsvector column to a chunks table shaped like the one in /tutorials/vector-search-with-postgresql-and-pgvector, write a keyword search and a vector search as SQL functions, look at questions where each fails, and merge their ranked lists with reciprocal rank fusion. Then you score all three against ten questions with known answers. If you would rather do the merge in application code, /tutorials/build-semantic-search-with-embeddings-in-python builds BM25 and RRF in Python; this tutorial keeps everything in SQL, next to the data.
The chunks are help-centre passages for Fernwood Hosting, the made-up company from the RAG series. Real embeddings have hundreds or thousands of numbers and come from a model API. Here each chunk and question carries a small hand-made 8-number vector, one number per topic (billing, refunds, DNS, email, backups, security, site errors, plans), so you can follow along with no API key and get the same results every time. The vectors are written to behave as embedding models typically do: they capture what a sentence is about and ignore product codes. The SQL is the same for real 1,024-number vectors, and the last step shows how to apply it to your RAG app's table.
You need PostgreSQL 18 with pgvector on Ubuntu 26.04, set up as in the pgvector tutorial. Ubuntu's archive ships pgvector 0.8.1 and the pgvector project's latest release is 0.8.7; nothing here needs more than the 0.8 series. PostgreSQL 19.0 was released on 19 November 2026; these steps were checked on 18, and nothing in them depends on 18-only behaviour.
Step 1 · Load the chunks, their embeddings and the test questions
Create a database called hybriddemo, turn on pgvector, and create a chunks table with the same columns as the RAG series: an id made from the source file and a chunk number, the source, the heading, the text and its embedding. The only difference is the vector size, 8 here instead of 1,024.
sudo -u postgres createdb hybriddemo
sudo -u postgres psql -d hybriddemo -v ON_ERROR_STOP=1 <<'SQL'
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE chunks (
id text PRIMARY KEY,
source text NOT NULL,
heading text NOT NULL,
content text NOT NULL,
embedding vector(8) NOT NULL
);
-- billing refunds dns email backups security errors plans
INSERT INTO chunks VALUES
('billing.md#0', 'billing.md', 'Billing', 'Fernwood Hosting bills each plan monthly, on the day of the month you signed up. The invoice lists each plan and add-on separately.', '[0.9,0,0,0,0,0,0,0.3]'),
('billing.md#1', 'billing.md', 'Refunds', 'Every new plan has a 30-day money-back guarantee. Ask within 30 days of the first payment and we refund the fee in full.', '[0.3,0.9,0,0,0,0,0,0.2]'),
('billing.md#2', 'billing.md', 'Failed payments', 'If a payment fails, we try the card again after three days and again after seven days. After the third failed attempt, the account is suspended.', '[0.8,0,0,0,0,0.2,0,0]'),
('errors.md#0', 'errors.md', 'Error codes', 'Error E5102 means the card issuer declined the charge. Ask your bank to allow international online payments, then retry from the Billing page.', '[0.7,0,0,0,0,0.3,0,0]'),
('errors.md#1', 'errors.md', 'Error codes', 'Error E7310 appears when a site uses more memory than its plan allows. Pages load slowly or return a 503 until you upgrade or reduce memory use.', '[0,0,0,0,0,0,0.9,0.4]'),
('domains.md#0', 'domains.md', 'Point a domain', 'To point a domain at your site, create an A record for the bare domain with the IP address from the Overview page, and a CNAME record for www.', '[0,0,0.95,0.1,0,0,0,0]'),
('domains.md#1', 'domains.md', 'DNS timing', 'A DNS change is not instant. Resolvers keep the old answer until its time to live runs out, so allow up to 48 hours.', '[0,0,0.9,0,0,0,0.3,0]'),
('email.md#0', 'email.md', 'Keep your mail', 'Do not delete MX records when you change DNS. They route your email, and removing them stops mail from arriving.', '[0,0,0.5,0.85,0,0,0,0]'),
('backups.md#0', 'backups.md', 'Automatic backups', 'Fernwood takes a full backup of every site each night and keeps the last seven. Plans with the Backup Plus add-on (SKU FWBP30) keep thirty.', '[0,0,0,0,0.9,0,0,0.3]'),
('backups.md#1', 'backups.md', 'Restore', 'To restore, open the site, choose Backups and pick a date. The restore replaces the files and the database, so anything written after that backup is lost.', '[0,0,0,0,0.95,0,0.1,0]'),
('security.md#0', 'security.md', 'Two-step sign-in', 'Turn on two-step sign-in from your profile settings. Signing in then needs a six-digit code from an authenticator app as well.', '[0,0,0,0,0,0.95,0,0]'),
('plans.md#0', 'plans.md', 'Plans', 'The Starter plan (SKU FWST1) hosts one site with 1 GB of memory. The Business plan (SKU FWBZ4) hosts ten sites with 4 GB and includes Backup Plus.', '[0.2,0,0,0,0.2,0,0.2,0.9]');
CREATE TABLE questions (
id integer PRIMARY KEY,
kind text NOT NULL,
question text NOT NULL,
expected_id text NOT NULL REFERENCES chunks (id),
embedding vector(8) NOT NULL
);
INSERT INTO questions VALUES
(1, 'exact code', 'What does error E5102 mean?', 'errors.md#0', '[0.1,0,0,0,0,0.1,0.95,0]'),
(2, 'exact code', 'What do I get with FWBP30?', 'backups.md#0', '[0.1,0,0,0,0,0,0,0.95]'),
(3, 'exact code', 'Explain E7310', 'errors.md#1', '[0.3,0,0,0,0,0.6,0,0]'),
(4, 'both', 'Is FWBZ4 enough for ten sites?', 'plans.md#0', '[0,0,0,0,0,0,0.3,0.9]'),
(5, 'paraphrase', 'I changed my mind after a week, can I be reimbursed?', 'billing.md#1', '[0.3,0.9,0,0,0,0,0,0.1]'),
(6, 'paraphrase', 'My website address is not showing my pages yet', 'domains.md#1', '[0,0,0.9,0,0,0,0.4,0]'),
(7, 'paraphrase', 'Someone could break into my account with just my password', 'security.md#0', '[0,0,0,0,0,0.95,0,0]'),
(8, 'paraphrase', 'I deleted a blog post yesterday and need it back', 'backups.md#1', '[0,0,0,0,0.9,0,0,0]'),
(9, 'both', 'How do I point my domain at Fernwood?', 'domains.md#0', '[0,0,0.9,0.1,0,0,0,0]'),
(10, 'both', 'What happens if my card payment fails?', 'billing.md#2', '[0.8,0,0,0,0,0.2,0,0]');
SQLThe questions table is your test set. Each row holds a question someone might type, the id of the chunk that answers it, and the question's embedding. In a real app the question embedding comes from the same model as the chunk embeddings, at search time. Storing it here lets you rerun the whole comparison without calling a model.
Look at the three kinds. The "exact code" questions turn on a product code or error code. The "paraphrase" questions describe a problem in words the help text never uses: nobody writes "reimbursed" or "blog post" in the refund and restore pages. The "both" questions share words and meaning with their answer.
Check it worked
sudo -u postgres psql -d hybriddemo -c "SELECT (SELECT count(*) FROM chunks) AS chunks, (SELECT count(*) FROM questions) AS questions;"You see 12 chunks and 10 questions. If CREATE EXTENSION fails with could not open extension control file, pgvector is not installed for PostgreSQL 18; install it as in the pgvector tutorial.
Step 2 · Add a keyword search column and index it
Keyword search needs each chunk's text reduced to lexemes. Add a stored generated column, so PostgreSQL fills it for existing rows and keeps it current when your chunking script inserts or replaces rows, and index it with GIN:
sudo -u postgres psql -d hybriddemo -v ON_ERROR_STOP=1 <<'SQL'
ALTER TABLE chunks
ADD COLUMN search tsvector
GENERATED ALWAYS AS (to_tsvector('english', content)) STORED;
CREATE INDEX chunks_search_idx ON chunks USING gin (search);
SQLSTORED matters: in PostgreSQL 18 a generated column without it is virtual and cannot back a search index. Name the configuration ('english') in the column and in every query, so both are reduced the same way. The full-text search tutorial covers weighting a heading above body text with setweight; this column indexes the chunk text only, to keep the ranking easy to follow.
See what happened to the chunk with the error code:
sudo -u postgres psql -d hybriddemo -c "SELECT search FROM chunks WHERE id = 'errors.md#0';"Check it worked
The vector contains 'e5102' exactly as written, lower-cased, next to stemmed words such as 'declin' and 'payment'. The english configuration sends tokens that mix letters and digits to the simple dictionary, which lower-cases them without stemming, so codes survive intact. That is what makes keyword search good at them.
Step 3 · Turn a question into a keyword query
websearch_to_tsquery and plainto_tsquery join every word with AND. That suits a search box, where people type two or three words, but not a RAG app, where people type whole questions: a chunk would need to contain every word of the question to match at all. For retrieval you want any chunk that shares a word, ranked by how many it shares. Build the query with plainto_tsquery, which drops stop words and stems the rest, then swap its ANDs for ORs:
sudo -u postgres psql -d hybriddemo -v ON_ERROR_STOP=1 <<'SQL'
CREATE FUNCTION any_word_query(question text)
RETURNS tsquery
LANGUAGE sql IMMUTABLE
AS $fn$
SELECT replace(plainto_tsquery('english', question)::text, ' & ', ' | ')::tsquery
$fn$;
CREATE FUNCTION keyword_search(question text, max_rows integer DEFAULT 5)
RETURNS TABLE (chunk_id text, kw_rank bigint)
LANGUAGE sql STABLE
AS $fn$
SELECT id, row_number() OVER (ORDER BY score DESC, id)
FROM (
SELECT c.id, ts_rank_cd(c.search, tq) AS score
FROM chunks AS c, any_word_query(question) AS tq
WHERE c.search @@ tq
ORDER BY score DESC, c.id
LIMIT max_rows
) AS hits
ORDER BY 2;
$fn$;
SQLplainto_tsquery quotes every lexeme, so the text it returns only ever contains quoted lexemes joined by & ` or, for hyphenated words, by ` <-> `. Swapping ` & ` for ` | ` therefore always leaves a valid query, whatever the reader types. A hyphenated word such as "two-step" stays a phrase match ('two-step' <-> 'two' <-> 'step'), so a chunk needs those words side by side to match on it. `keyword_search returns the chunk ids with their position in the ranking, 1 being the best. Positions are what the merge in a later step works with, so both search functions return them. Ties are broken by id, so the order is the same on every run.
Try it on the first test question:
sudo -u postgres psql -d hybriddemo -v ON_ERROR_STOP=1 <<'SQL'
SELECT any_word_query('What does error E5102 mean?');
SELECT k.kw_rank, k.chunk_id, c.content
FROM keyword_search('What does error E5102 mean?') AS k
JOIN chunks AS c ON c.id = k.chunk_id
ORDER BY k.kw_rank;
SQLCheck it worked
The query prints something like 'error' | 'e5102' | 'mean': "what" and "does" were dropped as stop words. Two chunks match. The first is errors.md#0, which contains all three lexemes; the second is the other error code chunk, which only shares "error". Keyword search has answered the code question correctly.
Step 4 · Run vector search beside it and see where each fails
Now the vector side. pgvector's <=> operator is cosine distance, where smaller means closer. The function takes the question's embedding, so in your app you embed the question first and pass the vector in:
sudo -u postgres psql -d hybriddemo -v ON_ERROR_STOP=1 <<'SQL'
CREATE FUNCTION vector_search(query_embedding vector, max_rows integer DEFAULT 5)
RETURNS TABLE (chunk_id text, vec_rank bigint)
LANGUAGE sql STABLE
AS $fn$
SELECT id, row_number() OVER (ORDER BY distance, id)
FROM (
SELECT c.id, c.embedding <=> query_embedding AS distance
FROM chunks AS c
ORDER BY distance, c.id
LIMIT max_rows
) AS nearest
ORDER BY 2;
$fn$;
SQLThe parameter is plain vector with no size, so the same function works on 8-number vectors here and 1,024-number vectors in your app. The inner query orders by distance and stops at max_rows, which is the shape an HNSW index can serve on a big table.
Put both methods side by side for question 1, the error code, and question 5, the refund question in other words:
sudo -u postgres psql -d hybriddemo -v ON_ERROR_STOP=1 <<'SQL'
SELECT q.id AS question, q.expected_id,
(SELECT string_agg(chunk_id, ', ' ORDER BY kw_rank) FROM keyword_search(q.question, 3)) AS keyword_top3,
(SELECT string_agg(chunk_id, ', ' ORDER BY vec_rank) FROM vector_search(q.embedding, 3)) AS vector_top3
FROM questions AS q
WHERE q.id IN (1, 5)
ORDER BY q.id;
SQLCheck it worked
Each method fails the question the other gets right:
- For question 1, keyword search puts
errors.md#0first. Vector search rankserrors.md#1first, because that chunk is about site errors and the question "looks like" a site error question; the payment chunk that definesE5102is not in its top three. - For question 5, vector search puts the refund chunk
billing.md#1first. Keyword search returns onlydomains.md#1andemail.md#0: "changed" stemmed tochangand matched two chunks about DNS changes, while "mind", "week" and "reimbursed" appear nowhere.
Neither list is wrong in its own terms. They measure different things, which is why combining them works.
Step 5 · Merge the two lists with reciprocal rank fusion
You cannot add a ts_rank_cd score to a cosine distance: they are on different scales, and the keyword score changes with document length and query length. Reciprocal rank fusion (RRF) sidesteps this by using only positions. Each chunk gets 1 / (k + position) from each list it appears in, and the scores are added. k is a constant, 60 in the paper that introduced the method, which stops the first position from dominating. A chunk that is fourth in one list and first in the other scores 1/64 + 1/61, which beats a chunk that is first in one list alone.
sudo -u postgres psql -d hybriddemo -v ON_ERROR_STOP=1 <<'SQL'
CREATE FUNCTION hybrid_search(
question text,
query_embedding vector,
max_rows integer DEFAULT 3,
candidates integer DEFAULT 5,
rrf_k integer DEFAULT 60
)
RETURNS TABLE (chunk_id text, score numeric, kw_rank bigint, vec_rank bigint)
LANGUAGE sql STABLE
AS $fn$
SELECT fused.id, round(fused.s, 5), fused.kr, fused.vr
FROM (
SELECT coalesce(k.chunk_id, v.chunk_id) AS id,
coalesce(1.0 / (rrf_k + k.kw_rank), 0)
+ coalesce(1.0 / (rrf_k + v.vec_rank), 0) AS s,
k.kw_rank AS kr,
v.vec_rank AS vr
FROM keyword_search(question, candidates) AS k
FULL OUTER JOIN vector_search(query_embedding, candidates) AS v
ON v.chunk_id = k.chunk_id
) AS fused
ORDER BY fused.s DESC, fused.id
LIMIT max_rows;
$fn$;
SQLThe FULL OUTER JOIN keeps chunks that only one method found; coalesce gives them nothing from the other. candidates is how deep each list goes before the merge. Five is plenty for twelve chunks; on a real table take 20 to 50 from each side and keep max_rows at what you send to the model. The ordering uses the unrounded score, and rounding only tidies the output.
Run the two questions from the last step through it:
sudo -u postgres psql -d hybriddemo -v ON_ERROR_STOP=1 <<'SQL'
SELECT q.id AS question, q.expected_id, h.*
FROM questions AS q,
hybrid_search(q.question, q.embedding) AS h
WHERE q.id IN (1, 5)
ORDER BY q.id, h.score DESC, h.chunk_id;
SQLCheck it worked
Both expected chunks are now in the top three. For question 1, errors.md#0 shows kw_rank 1 and vec_rank 4, and its score of about 0.03202 lifts it to second place, just behind errors.md#1, which both lists also found. For question 5, billing.md#1 has a vec_rank of 1 and an empty kw_rank, and domains.md#1 is the mirror image: first in the keyword list, absent from the vector list. Both score exactly 0.01639 (1/61). They are tied, and billing.md#1 comes first only because the ORDER BY ... fused.id tie-break sorts b before d. Three chunks go to the model instead of one, and the answer is among them, but the tie shows a real weakness of RRF with short lists: a chunk that only one method found scores the same whichever method found it, so the fused order between such chunks says nothing about which is better.
Step 6 · Score keyword, vector and hybrid search against the test set
Two examples prove little. Score all ten questions with hit rate at 3: the share of questions whose expected chunk is in the top three results. The evaluation tutorial in the RAG series explains this measure and mean reciprocal rank in more depth.
sudo -u postgres psql -d hybriddemo -v ON_ERROR_STOP=1 <<'SQL'
SELECT
count(*) FILTER (WHERE q.expected_id IN
(SELECT chunk_id FROM keyword_search(q.question, 3))) AS keyword_hits,
count(*) FILTER (WHERE q.expected_id IN
(SELECT chunk_id FROM vector_search(q.embedding, 3))) AS vector_hits,
count(*) FILTER (WHERE q.expected_id IN
(SELECT chunk_id FROM hybrid_search(q.question, q.embedding, 3))) AS hybrid_hits,
count(*) AS questions
FROM questions AS q;
SQLThe totals hide which questions failed. This query shows, for each question, where the expected chunk landed in each list of five (an empty cell means it was not there):
sudo -u postgres psql -d hybriddemo -v ON_ERROR_STOP=1 <<'SQL'
SELECT q.id, q.kind,
(SELECT kw_rank FROM keyword_search(q.question, 5) WHERE chunk_id = q.expected_id) AS keyword,
(SELECT vec_rank FROM vector_search(q.embedding, 5) WHERE chunk_id = q.expected_id) AS vector,
(SELECT h.pos FROM hybrid_search(q.question, q.embedding, 5)
WITH ORDINALITY AS h(chunk_id, score, kw_rank, vec_rank, pos)
WHERE h.chunk_id = q.expected_id) AS hybrid
FROM questions AS q
ORDER BY q.id;
SQLCheck it worked
The first query prints 6, 7, 10 and 10: keyword search finds 6 of 10, vector search 7 of 10, and hybrid search all 10. The second shows the pattern behind those numbers. Keyword search misses all four paraphrase questions. Vector search misses the three exact-code questions, placing the right chunk fourth or not at all. Hybrid search finds every one, though for questions 1, 6, 7 and 8 the answer is second or third rather than first, so the model has to read past one or two other chunks.
Two of the first places are ties won on the id. For question 3, errors.md#1 (keyword 1) and security.md#0 (vector 1) both score 1/61, and for question 5, billing.md#1 and domains.md#1 do the same. In each case the right chunk wins because its id sorts first, not because the method preferred it. Question 8 shows the opposite problem. backups.md#1 is first in the vector list, but the refund chunk billing.md#1 beats it: "money-back" gives that chunk the lexeme back, which matches "need it back", and with only twelve chunks it also sits fifth in the vector list, among chunks with no similarity at all. Two weak places score more than one strong one. With deeper candidate lists on a real table, ties like this are rarer, because a good chunk usually turns up somewhere in both lists. Still, if your test set shows many exact ties, break them with something meaningful, such as the vector distance, rather than the id.
These vectors were written to show the two failure modes clearly, so do not read the numbers as a benchmark. The method is what carries over: write questions from real support tickets or search logs, including the codes, names and plain-language complaints your users really send, and score each method before you choose. If your users write in more than one language, put questions in each language in the set: the english configuration does not stem Yoruba, Hausa or Swahili, and embedding models differ widely in how well they handle them.
Step 7 · Apply hybrid search to your RAG app's chunks table
If you followed the RAG series, the ragdemo database holds the chunks table with real 1,024-number embeddings, and it has the same columns as the demo table. Warning first: adding a stored generated column rewrites the table under an ACCESS EXCLUSIVE lock, so both reads and writes on it wait until that finishes. On the series' 16 chunks that is instant; on a large table, run it at a quiet time.
sudo -u postgres psql -d ragdemo -v ON_ERROR_STOP=1 <<'SQL'
ALTER TABLE chunks
ADD COLUMN search tsvector
GENERATED ALWAYS AS (to_tsvector('english', heading || ' ' || content)) STORED;
CREATE INDEX chunks_search_idx ON chunks USING gin (search);
SQLThen create any_word_query, keyword_search, vector_search and hybrid_search in ragdemo exactly as above. Indexing the heading as well helps there, because the series' headings name the topic ("Billing and refunds > Refunds"). In your app, replace the plain vector query with a call that passes both the question text and its embedding as parameters, never by pasting the question into the SQL string:
SELECT c.id, c.heading, c.content
FROM hybrid_search($1, $2::vector, 4, 30) AS h
JOIN chunks AS c ON c.id = h.chunk_id
ORDER BY h.score DESC, h.chunk_id;Then rerun the series' evaluation script and compare hit rate and mean reciprocal rank before and after. A few points as the table grows:
- With an HNSW index on the embeddings, the vector side returns at most
hnsw.ef_searchrows (40 by default), so keepcandidatesbelow that or raise the setting. - If you filter chunks, for example by
sourceor by tenant, put the same filter in both search functions, or the fused list mixes filtered and unfiltered results. For filtered vector queries, turn on pgvector's iterative scans as shown in the pgvector tutorial. - Leave
rrf_kat 60 unless your test set says otherwise. If one method is consistently better for your questions, a common change is to weight its term, for example1.5 / (rrf_k + v.vec_rank), and measure again. - Each search is a few milliseconds of SQL. For people on low-end Android phones and prepaid data, the cost that matters is the model call after it, so send the model a handful of strong chunks rather than twenty weak ones.
Check it worked
sudo -u postgres psql -d ragdemo -c "SELECT count(*) AS chunks, count(search) AS with_search FROM chunks;"Both counts are equal, and \df hybrid_search in psql lists the function. A question that names an exact setting or code from your help pages now returns the chunk that contains it, while questions in other words still find their answers through the vector side.
When you are finished with the demo, remove it with sudo -u postgres dropdb hybriddemo. Keep ragdemo if you are still working through the RAG series.
Next steps
- Build the RAG endpoint that sends these chunks to a model:
/tutorials/build-a-rag-question-answering-endpoint. - Score the whole pipeline, not only retrieval, with a larger test set:
/tutorials/evaluate-a-rag-app-with-a-test-set. - Go deeper on ranking, highlighting, accents and typos in keyword search:
/tutorials/add-full-text-search-to-a-postgresql-database. - Tune the HNSW index and filtered vector queries:
/tutorials/vector-search-with-postgresql-and-pgvector.
Related tutorials
- How to Do Vector Similarity Search in PostgreSQL with pgvectorYou will install PostgreSQL 18 with the pgvector extension on Ubuntu 26.04, store and compare vectors with SQL, load the chunks from the previous tutorial into a table, and add an HNSW index to make nearest-neighbour search fast.
- Add full-text search to a PostgreSQL databaseYou will make 20,000 product descriptions searchable in PostgreSQL 18 with a weighted tsvector column, a GIN index, ranked and highlighted results, accent-insensitive matching and typo suggestions, all behind one SQL function your app can call.
- How to Evaluate and Improve a RAG App with a Test SetYou will write a test set of questions with known answers, measure retrieval with hit rate and mean reciprocal rank and the full pipeline with pass or fail checks, then use the results to add a distance cutoff that makes the app decline questions it cannot answer.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials