Every RAG tutorial starts by adding a database to your stack. A vector store here, a keyword index there, a sync job to keep them consistent, a backup story for each. Meanwhile the database you already run — Postgres, the one holding your users, your orders, your audit log — has done vector search since 2023. pgvector is a Postgres extension: one CREATE EXTENSION, and the same database that stores your rows also stores your embeddings, ranks them, and joins the results back to the rest of your data. No new service to operate, no sync job, no second backup to forget.

This tutorial builds a complete RAG pipeline on Postgres and nothing else: twelve documents about Postgres itself, embedded locally with BGE-small, stored in a vector column, searched three ways — dense, keyword, and hybrid — and wired into a small Q&A app that answers from what it retrieves. Everything runs on your laptop. There is no API key anywhere in it: the embedding model and the answering model both run on CPU. Every command and query below was run while writing this tutorial, on Postgres 16.15 with pgvector 0.6.0, and the timings and rankings reported are the ones that actually came back.

What you’ll need#

  • Postgres 16 or newer with pgvector. On Ubuntu or Debian: sudo apt-get install -y postgresql-16 postgresql-16-pgvector. On macOS: brew install postgresql pgvector. The pgvector project also publishes a Docker image, pgvector/pgvector:pg16, with the extension preinstalled. Ubuntu 24.04 ships pgvector 0.6.0; the latest release is 0.8.7, available by building from source. Everything in this tutorial works on 0.6.0.
  • Python 3.12 and about 2–3 GB of free disk for the Python environment and the two local models (PyTorch CPU is the bulk of it).
  • No accounts, no API keys, no GPU. The embedding model (BGE-small-en-v1.5, 384 dimensions) and the answering model (Qwen2.5-0.5B-Instruct) both run on CPU. A laptop with 4 GB of RAM free is enough; the hands-on steps take about ten minutes once Postgres is installed.

1. Install Postgres and pgvector#

On Ubuntu 24.04, the whole install is two commands:

sudo apt-get update
sudo apt-get install -y postgresql-16 postgresql-16-pgvector

Check what you got:

psql --version
# psql (PostgreSQL) 16.15 (Ubuntu 16.15-0ubuntu0.24.04.1)

If you want the newest pgvector instead of the packaged 0.6.0, the README’s from-source path is git clone --branch v0.8.7 https://github.com/pgvector/pgvector.git, then make && sudo make install inside the checkout. You need the Postgres server headers (postgresql-server-dev-16 on Debian/Ubuntu) for the build. The tutorial’s SQL is identical either way, so take the packaged version unless you need a feature added after 0.6.0.

2. Create the database, user, and schema#

Create a database and a dedicated user for it. Then enable the extension — and here is the first gotcha: CREATE EXTENSION vector requires a superuser. A normal user gets permission denied to create extension "vector" with the hint Must be superuser to create this extension. So create the extension as the postgres superuser, and let the app user do everything else:

sudo -u postgres psql -c "CREATE USER rag WITH PASSWORD 'ragdemo';" \
                      -c "CREATE DATABASE rag_demo OWNER rag;"
sudo -u postgres psql -d rag_demo -c "CREATE EXTENSION vector;"
sudo -u postgres psql -d rag_demo -c "SELECT extname, extversion FROM pg_extension WHERE extname = 'vector';"
--  extname | extversion
-- ---------+------------
--  vector  | 0.6.0

Now the schema. Save this as schema.sql:

-- Schema for the pgvector RAG tutorial (run with: psql -d rag_demo -f schema.sql)
CREATE EXTENSION IF NOT EXISTS vector;

DROP TABLE IF EXISTS documents;

CREATE TABLE documents (
    id          bigserial PRIMARY KEY,
    title       text NOT NULL,
    category    text NOT NULL,
    content     text NOT NULL,
    content_tsv tsvector GENERATED ALWAYS AS
        (to_tsvector('english', title || ' ' || content)) STORED,
    embedding   vector(384)
);

-- Keyword search rides on a GIN index over the generated tsvector column.
CREATE INDEX documents_tsv_idx ON documents USING gin (content_tsv);

Three decisions are doing work here. First, embedding vector(384): the column type pins the dimension, so a wrong-sized vector is rejected at insert time instead of silently corrupting your rankings. 384 is the output size of the embedding model used in Step 3 — switch models and you change this number to match (1024 for BGE-large, 1536 for OpenAI’s text-embedding-3-small). Second, content_tsv is a generated column: Postgres rebuilds the keyword index data itself on every insert and update, so the text search index can never drift out of sync with the content. Third, the GIN index on that column is what makes keyword search fast; without it, every keyword query scans the table.

Apply it as the rag user and confirm the table:

PGPASSWORD=ragdemo psql -h localhost -U rag -d rag_demo -f schema.sql
PGPASSWORD=ragdemo psql -h localhost -U rag -d rag_demo -c "\d documents"
--  Table "public.documents"
--   Column    |    Type     | Nullable | Default
--  -----------+-------------+----------+---------
--   id        | bigint      | not null | nextval(...)
--   title     | text        | not null |
--   category  | text        | not null |
--   content   | text        | not null |
--   content_tsv | tsvector  |          | generated always as ...
--   embedding | vector(384)|          |
--  Indexes:
--      "documents_pkey" PRIMARY KEY, btree (id)
--      "documents_tsv_idx" gin (content_tsv)

3. Embed the corpus with a local model#

The corpus is twelve short documents about Postgres features, two to four sentences each — HNSW indexes, IVFFlat, VACUUM, the write-ahead log, GIN, JSONB, partitioning, full-text search, logical replication, pg_stat_statements, connection pooling, BRIN. The subject is deliberate: the reader is learning Postgres, and the documents are varied enough that dense search, keyword search, and hybrid search return visibly different rankings on the same questions. Save this as corpus.py:

"""Corpus for the pgvector RAG tutorial: 12 short documents about Postgres features."""

DOCUMENTS = [
    {
        "title": "HNSW index",
        "category": "indexing",
        "content": (
            "An HNSW index organizes vectors into a multilayer graph so nearest-neighbor "
            "search can skip most of the table. You build it with CREATE INDEX ... USING hnsw, "
            "choosing vector_cosine_ops for cosine distance or vector_l2_ops for Euclidean distance. "
            "Two build-time knobs matter: m, the number of connections per layer, and ef_construction, "
            "the size of the candidate list while building the graph. At query time, hnsw.ef_search "
            "controls the trade-off between recall and speed."
        ),
    },
    {
        "title": "IVFFlat index",
        "category": "indexing",
        "content": (
            "An IVFFlat index splits vectors into lists with k-means and searches only the lists "
            "closest to the query. It builds faster and uses less memory than HNSW, but its "
            "speed-recall trade-off is worse. Create it after the table has data, with a list count "
            "near rows divided by 1000, and tune ivfflat.probes at query time to search more lists "
            "for better recall."
        ),
    },
    {
        "title": "VACUUM",
        "category": "maintenance",
        "content": (
            "VACUUM reclaims storage occupied by dead tuples left behind by updated or deleted rows. "
            "It also freezes old transaction IDs so the database never wraps around and stops. "
            "Autovacuum runs it automatically in the background; a manual VACUUM ANALYZE also "
            "refreshes planner statistics."
        ),
    },
    {
        "title": "Write-ahead log",
        "category": "durability",
        "content": (
            "The write-ahead log, or WAL, records every change before it reaches the data files, "
            "so a crash can replay committed transactions. WAL archiving enables point-in-time "
            "recovery to any moment covered by the archive. Streaming replication ships WAL records "
            "to standby servers, which apply them to stay current."
        ),
    },
    {
        "title": "GIN index",
        "category": "indexing",
        "content": (
            "A GIN index is an inverted index: it maps each key, such as a word or a JSONB key, "
            "to the rows that contain it. It accelerates full-text search, JSONB containment queries, "
            "and array membership tests. GIN indexes are larger and slower to update than B-tree "
            "indexes, so they suit read-heavy workloads."
        ),
    },
    {
        "title": "JSONB",
        "category": "storage",
        "content": (
            "JSONB stores JSON in a decomposed binary format, so the database can index inside "
            "documents and query individual keys. Operators like @> test containment, ->> extracts "
            "a value as text, and a GIN index makes those lookups fast. Prefer JSONB over JSON when "
            "you query the contents; plain JSON only preserves the exact input text."
        ),
    },
    {
        "title": "Table partitioning",
        "category": "storage",
        "content": (
            "Partitioning splits a large table into smaller physical tables by range or list, while "
            "queries still see one logical table. The planner prunes partitions it can prove are "
            "irrelevant, so a query over one month reads one month of data. Detaching an old partition "
            "is also the fastest way to drop a time range."
        ),
    },
    {
        "title": "Full-text search",
        "category": "query",
        "content": (
            "Postgres full-text search turns text into a tsvector of lexemes and matches it against "
            "a tsquery. to_tsvector('english', content) builds the document vector, plainto_tsquery "
            "turns a user's words into a query, and ts_rank_cd scores matches. A GIN index on the "
            "tsvector makes keyword search fast without an external engine."
        ),
    },
    {
        "title": "Logical replication",
        "category": "replication",
        "content": (
            "Logical replication copies changes row by row through publications and subscriptions, "
            "rather than shipping whole WAL segments. It supports replicating a subset of tables, "
            "filtering rows, and replicating between different major versions. A subscription applies "
            "changes on the target with the same transactional guarantees."
        ),
    },
    {
        "title": "pg_stat_statements",
        "category": "monitoring",
        "content": (
            "The pg_stat_statements extension records execution statistics for every normalized query: "
            "total time, call count, rows returned, and shared buffer hits. Query pg_stat_statements "
            "ordered by total_exec_time to find the queries that cost the most. It needs "
            "shared_preload_libraries set before the server starts."
        ),
    },
    {
        "title": "Connection pooling",
        "category": "operations",
        "content": (
            "Each Postgres connection is a server process, so thousands of direct connections waste "
            "memory and CPU. A pooler such as PgBouncer keeps a small set of real connections and "
            "multiplexes many clients onto them. Transaction pooling gives the most reuse; session "
            "pooling preserves session-level features like prepared statements."
        ),
    },
    {
        "title": "BRIN index",
        "category": "indexing",
        "content": (
            "A BRIN index stores the minimum and maximum value of each block range, so it is tiny "
            "compared to a B-tree. It works when the physical order of rows correlates with the "
            "indexed value, such as a timestamp column on an append-only table. Queries scan only "
            "the block ranges whose min-max window could contain matching rows."
        ),
    },
]

QUERIES = [
    ("How do I make vector similarity search faster on a large table?", "HNSW index"),
    ("find the slowest queries", "pg_stat_statements"),
    ("pg_stat_statements total_exec_time", "pg_stat_statements"),
    ("get rid of obsolete row versions", "VACUUM"),
    ("fast approximate nearest neighbor search for embeddings", "HNSW index"),
]

The embedding model is BAAI’s bge-small-en-v1.5: a 33-million-parameter model that produces 384-dimensional embeddings, small enough to run on any CPU and strong enough for a retrieval demo. Install the Python stack with pinned versions — the versions in parentheses are the ones this tutorial actually ran:

python3 -m venv .venv
.venv/bin/pip install torch --index-url https://download.pytorch.org/whl/cpu  # CPU build, keeps the download small
.venv/bin/pip install "sentence-transformers==6.3.0" "psycopg[binary]==3.3.9" \
    "pgvector==0.5.1" "transformers==5.24.1"
# installed: torch 2.15.0+cpu, sentence-transformers 6.3.0, psycopg 3.3.9, pgvector 0.5.1

On a machine with no GPU, install the CPU build of PyTorch first, as above — otherwise pip fetches the CUDA build, which is several times larger and useless without a GPU. Then encode the corpus. Save this as ingest.py:

"""Embed the corpus with bge-small-en-v1.5 and insert it into Postgres."""
import time

import psycopg
from pgvector import Vector
from pgvector.psycopg import register_vector
from sentence_transformers import SentenceTransformer

from corpus import DOCUMENTS

MODEL = "BAAI/bge-small-en-v1.5"
DSN = "postgresql://rag:ragdemo@localhost:5432/rag_demo"

t0 = time.time()
model = SentenceTransformer(MODEL)
texts = [f"{d['title']}. {d['content']}" for d in DOCUMENTS]
embeddings = model.encode(texts, normalize_embeddings=True)
print(f"encoded {len(texts)} documents in {time.time() - t0:.1f}s; dims={embeddings.shape[1]}")

with psycopg.connect(DSN, autocommit=True) as conn:
    register_vector(conn)
    with conn.cursor() as cur:
        for doc, emb in zip(DOCUMENTS, embeddings):
            cur.execute(
                "INSERT INTO documents (title, category, content, embedding) "
                "VALUES (%s, %s, %s, %s)",
                (doc["title"], doc["category"], doc["content"], Vector(emb)),
            )
        n = cur.execute("SELECT count(*) FROM documents").fetchone()[0]
        dim = cur.execute("SELECT vector_dims(embedding) FROM documents LIMIT 1").fetchone()[0]
        nulls = cur.execute("SELECT count(*) FROM documents WHERE embedding IS NULL").fetchone()[0]
        print(f"rows={n} vector_dims={dim} null_embeddings={nulls}")

Two details matter. register_vector(conn) teaches psycopg how to send and receive the vector type; without it, inserts fail with a type error. And normalize_embeddings=True scales every vector to length 1, which makes cosine distance and inner product rank identically — so the <=> operator in the next steps measures what you think it measures. Run it:

.venv/bin/python ingest.py
# encoded 12 documents in 2.7s; dims=384
# rows=12 vector_dims=384 null_embeddings=0

4. Insert and verify#

The ingest script already printed its checks, but verify from the database side too — trust the table, not the script:

PGPASSWORD=ragdemo psql -h localhost -U rag -d rag_demo -c \
  "SELECT count(*), vector_dims(embedding) FROM documents GROUP BY 2;"
--  count | vector_dims
-- -------+-------------
--     12 |         384
PGPASSWORD=ragdemo psql -h localhost -U rag -d rag_demo -c \
  "SELECT title, category, length(content) FROM documents ORDER BY id LIMIT 3;"
--        title       | category  | length
-- ------------------+-----------+--------
--  HNSW index        | indexing  |    471
--  IVFFlat index     | indexing  |    354
--  VACUUM            | maintenance |  280

Also confirm the generated keyword column populated — a NULL content_tsv would mean keyword search silently returns nothing later:

PGPASSWORD=ragdemo psql -h localhost -U rag -d rag_demo -c \
  "SELECT count(*) FROM documents WHERE content_tsv IS NULL;"
--  count
-- -------
--      0

5. Dense-only search — the baseline#

Dense search is one query: embed the question with the same model, then order rows by cosine distance to it. Save the search script as search.py — it runs all three methods and compares them, but here is the dense part:

DENSE_SQL = """
SELECT title, 1 - (embedding <=> %s) AS similarity
FROM documents ORDER BY embedding <=> %s LIMIT 3
"""

qvec = Vector(model.encode([question], normalize_embeddings=True)[0])
dense = [r[0] for r in cur.execute(DENSE_SQL, (qvec, qvec)).fetchall()]

The <=> operator is cosine distance: 0 for identical direction, 2 for opposite. Subtracting from 1 turns it into a similarity score, which reads better in output. pgvector also offers <-> (Euclidean distance), <#> (negative inner product), and <+> (Manhattan distance) — for normalized embeddings, cosine is the standard choice, and the BGE model card recommends normalized embeddings for retrieval.

Run the five test questions from corpus.py through dense search alone. This is the baseline everything else is measured against:

.venv/bin/python search.py
# Q: 'How do I make vector similarity search faster on a large table?'
#   dense: ['IVFFlat index', 'HNSW index', 'Full-text search']
# Q: 'find the slowest queries'
#   dense: ['Table partitioning', 'pg_stat_statements', 'HNSW index']
# Q: 'pg_stat_statements total_exec_time'
#   dense: ['pg_stat_statements', 'Connection pooling', 'Table partitioning']
# Q: 'get rid of obsolete row versions'
#   dense: ['Logical replication', 'VACUUM', 'Table partitioning']
# Q: 'fast approximate nearest neighbor search for embeddings'
#   dense: ['HNSW index', 'IVFFlat index', 'Full-text search']

Dense search gets the right document into the top three for all five questions, but look at the two misses at rank one. For “find the slowest queries” it puts Table partitioning first — the word “queries” in that document (“queries still see one logical table”) pulls the embedding toward it, while the pg_stat_statements document, the right answer, sits second. For “get rid of obsolete row versions” it puts Logical replication first, because “versions” matches “different major versions” in that document, with VACUUM second. Embeddings understand meaning, but they also get fooled by a shared word. That is exactly the failure keyword search exists to catch. Timings, for the record: the first query took about 70 ms cold, then 1–2 ms each. On twelve rows those numbers are noise, not benchmarks — the point is that nothing here needs a GPU or a server.

Postgres has had full-text search since long before vector search existed, and the generated content_tsv column from Step 2 already feeds it. A tsvector is the document reduced to lexemes — stemmed words with positions — and a tsquery is the question in the same form. Matching is exact by construction: a document either contains the lexeme or it does not. The ranking function ts_rank_cd scores matches by how often and how densely the terms appear.

The keyword leg of the search script looks like this:

FTS_SQL = """
SELECT title, ts_rank_cd(content_tsv, websearch_to_tsquery('english', %s)) AS rank
FROM documents
WHERE content_tsv @@ websearch_to_tsquery('english', %s)
ORDER BY rank DESC LIMIT 3
"""

or_query = ' OR '.join(question.split())
fts = [r[0] for r in cur.execute(FTS_SQL, (or_query, or_query)).fetchall()]

The OR join is not cosmetic — it is the difference between a search box that works and one that returns nothing. The more obvious function, plainto_tsquery, ANDs the terms: plainto_tsquery('english', 'find the slowest queries') produces 'find' & 'slowest' & 'queri', and no document contains all three, so the query returns zero rows. websearch_to_tsquery accepts the same words joined by OR and produces 'slowest' | 'queri', which matches any document containing either term and ranks by ts_rank_cd. Stopwords (“the”, “how”, “do”) are dropped by the parser in both cases, so joining every word with OR is safe.

Run the same five questions through keyword search alone:

# Q: 'How do I make vector similarity search faster on a large table?'
#   fts: ['HNSW index', 'IVFFlat index', 'Table partitioning']
# Q: 'find the slowest queries'
#   fts: ['pg_stat_statements', 'JSONB', 'IVFFlat index']
# Q: 'pg_stat_statements total_exec_time'
#   fts: ['pg_stat_statements']
# Q: 'get rid of obsolete row versions'
#   fts: ['Logical replication', 'BRIN index', 'IVFFlat index']
# Q: 'fast approximate nearest neighbor search for embeddings'
#   fts: ['HNSW index', 'Full-text search', 'IVFFlat index']

Keyword search is the mirror image of dense search. Where dense search was fooled, keyword search is exact: “find the slowest queries” puts pg_stat_statements first, because that document is the only one where “queries” appears alongside the ranking terms, and “pg_stat_statements total_exec_time” returns a single row — the exact document, nothing else. Where keyword search fails, it fails completely: “get rid of obsolete row versions” never mentions the word VACUUM, and no document contains “obsolete”, so the right document does not even appear in the top three. Each method has a blind spot the other one covers. That is the whole argument for hybrid search.

Diagram of the RAG pipeline: documents become embeddings, are stored in Postgres with vectors and a keyword index, then hybrid search returns a ranked list for the answer
AI-generated illustration: the pipeline this tutorial builds — documents in, ranked answers out.

7. Hybrid search with RRF in pure SQL#

Hybrid search runs both methods and merges the rankings. The standard merge is Reciprocal Rank Fusion: each method contributes 1 / (k + rank) per document, with k conventionally 60, and the scores are summed. A document ranked first by both methods scores about 0.033; a document ranked first by one and absent from the other scores about 0.016. The formula needs no tuning and no model — and it fits in a single SQL query, which is the point of keeping vectors in Postgres:

WITH dense AS (
    SELECT id, ROW_NUMBER() OVER (ORDER BY embedding <=> $1) AS rank
    FROM documents LIMIT 20
),
fts AS (
    SELECT id, ROW_NUMBER() OVER (
        ORDER BY ts_rank_cd(content_tsv, websearch_to_tsquery('english', $2)) DESC
    ) AS rank
    FROM documents
    WHERE content_tsv @@ websearch_to_tsquery('english', $2)
    LIMIT 20
),
fused AS (
    SELECT id, SUM(1.0 / (60 + rank)) AS score
    FROM (SELECT id, rank FROM dense UNION ALL SELECT id, rank FROM fts) s
    GROUP BY id
)
SELECT d.title, round(f.score::numeric, 4) AS rrf_score
FROM fused f JOIN documents d ON d.id = f.id
ORDER BY f.score DESC LIMIT 3;

From Python, the same query with parameters — the query vector, the OR-joined question twice, and the RRF constant:

rrf = [r[0] for r in cur.execute(RRF_SQL, (qvec, or_query, or_query, 60)).fetchall()]

Here are all five questions, all three methods, top three each — the actual output of search.py:

QuestionDense-only (top 1)Keyword-only (top 1)Hybrid RRF (top 1)
How do I make vector similarity search faster on a large table?IVFFlat indexHNSW indexIVFFlat index
find the slowest queriesTable partitioning ✗pg_stat_statementspg_stat_statements
pg_stat_statements total_exec_timepg_stat_statementspg_stat_statementspg_stat_statements
get rid of obsolete row versionsLogical replication ✗Logical replication ✗Logical replication ✗
fast approximate nearest neighbor search for embeddingsHNSW indexHNSW indexHNSW index

Two rows are the lesson. On “find the slowest queries”, hybrid search fixes a real dense-search miss: dense search ranked Table partitioning first and pg_stat_statements second, keyword search ranked pg_stat_statements first, and RRF promoted it to the top — the fused score of a document both methods like beats a document only one likes. On “get rid of obsolete row versions”, nobody wins: both methods rank Logical replication first (the word “versions” again), VACUUM is second for dense search and absent for keyword search, and RRF keeps the wrong answer on top. RRF blends evidence; it cannot invent evidence neither method has. On a twelve-document corpus that is the honest limit — with more documents, a cross-encoder reranker over the fused top ten (BGE’s own bge-reranker-base is the usual companion) is the next step, not a different database.

8. Metadata filters are just WHERE clauses#

This is the step that justifies the whole architecture. In a dedicated vector store, filtering by metadata is a special API with its own syntax and its own edge cases. In Postgres it is a WHERE clause:

SELECT title, category FROM documents
WHERE category = 'indexing'
ORDER BY embedding <=> (SELECT embedding FROM documents WHERE title = 'HNSW index')
LIMIT 3;
--      title     | category
-- ---------------+----------
--  HNSW index    | indexing
--  IVFFlat index | indexing
--  GIN index     | indexing

The filter applies before the ranking, so the nearest-neighbor search only ever considers indexing documents. The same works for any column you already have — a tenant ID for multi-tenancy, a timestamp range, a boolean flag — and it composes with joins: filter documents by the project they belong to through a join to your projects table, then rank. That is the practical difference between “a vector database with a Postgres adapter” and “Postgres, with vectors”. If your data already lives in Postgres, the second one means your retrieval layer inherits transactions, constraints, backups, and access control instead of reimplementing them.

9. Add the HNSW index — and read the plan#

So far every query has been exact search: Postgres compared the question vector against all twelve rows and sorted. That is perfect recall and it is fast at this size, but it is a full scan, and full scans stop being fast somewhere in the tens of thousands of rows. The fix is an HNSW index — a multilayer graph that lets the search skip most of the table. Build it with the operator class matching the distance you query by:

PGPASSWORD=ragdemo psql -h localhost -U rag -d rag_demo -c \
  "CREATE INDEX documents_embedding_idx ON documents USING hnsw (embedding vector_cosine_ops);"
-- CREATE INDEX
PGPASSWORD=ragdemo psql -h localhost -U rag -d rag_demo -c \
  "SELECT pg_size_pretty(pg_relation_size('documents_embedding_idx'));"
--  pg_size_pretty
-- ----------------
--  32 kB

Now ask the planner what it thinks of the index:

PGPASSWORD=ragdemo psql -h localhost -U rag -d rag_demo -c \
  "EXPLAIN (ANALYZE, BUFFERS) SELECT title FROM documents
   ORDER BY embedding <=> (SELECT embedding FROM documents WHERE title='HNSW index') LIMIT 3;"
--  Limit  (actual time=0.096..0.098 rows=3 loops=1)
--    ->  Sort  (actual time=0.095..0.096 rows=3 loops=1)
--          Sort Key: ((documents.embedding <=> $0))
--          ->  Seq Scan on documents  (actual time=0.023..0.075 rows=12 loops=1)

The planner ignores the index. That is correct. Scanning twelve rows and sorting them takes under a tenth of a millisecond; traversing a graph to avoid scanning twelve rows is more work, not less. The pgvector README says the same thing: on a small table, a table scan may be faster. You can prove the index itself works by disabling sequential scans for one transaction:

PGPASSWORD=ragdemo psql -h localhost -U rag -d rag_demo -c \
  "BEGIN; SET LOCAL enable_seqscan = off;
   EXPLAIN (ANALYZE) SELECT title FROM documents
   ORDER BY embedding <=> (SELECT embedding FROM documents WHERE title='HNSW index') LIMIT 3;
   COMMIT;"
--  ->  Index Scan using documents_embedding_idx on documents
--        Order By: (embedding <=> $0)

Two things worth knowing came out of running this. First, the indexed query on this twelve-row table took roughly 0.1–0.2 seconds of wall time, against about 0.2 milliseconds for the sequential scan — the index really is slower than the scan at this scale, and the planner is right to skip it. Second, the approximate and exact searches return identical top threes here (HNSW index, IVFFlat index, GIN index), which is the recall check the README recommends: compare the indexed result against the exact result with SET LOCAL enable_indexscan = off, and if they diverge, raise hnsw.ef_search — 40 by default — to widen the candidate list:

PGPASSWORD=ragdemo psql -h localhost -U rag -d rag_demo -c \
  "SET hnsw.ef_search = 100; SHOW hnsw.ef_search;"
--  hnsw.ef_search
-- ----------------
--  100

Use SET LOCAL inside a transaction to apply it to a single query. The index build options are m (connections per layer, 16 by default) and ef_construction (candidate list while building, 64 by default); leave both alone unless recall measurements tell you otherwise. And if build speed matters more than query speed, the alternative index type is IVFFlat — it builds faster and uses less memory, at a worse speed-recall trade-off. Its creation was verified while writing this tutorial and then dropped, since HNSW is the index this pipeline keeps:

PGPASSWORD=ragdemo psql -h localhost -U rag -d rag_demo -c \
  "CREATE INDEX documents_embedding_ivf_idx ON documents USING ivfflat (embedding vector_cosine_ops) WITH (lists = 10);"
-- CREATE INDEX
PGPASSWORD=ragdemo psql -h localhost -U rag -d rag_demo -c "DROP INDEX documents_embedding_ivf_idx;"
-- DROP INDEX
Illustration of a multilayer graph search: glowing nodes connected in stacked layers with one highlighted path threading through them
AI-generated illustration: HNSW search descends layer by layer through a graph of vectors instead of scanning the whole table.

10. Assemble the Q&A app#

Retrieval is done. The last step is the app: retrieve the top three chunks with the hybrid query from Step 7, pack them into a grounded prompt, and hand the prompt to a model. The generator here is Qwen2.5-0.5B-Instruct running on CPU — the smallest model that can follow a “use only this context” instruction — because the point of this tutorial is a pipeline with no API key in it. Save this as qa.py:

"""Q&A app: hybrid retrieval in Postgres, answer from a local model."""
import argparse

import psycopg
from pgvector import Vector
from pgvector.psycopg import register_vector
from sentence_transformers import SentenceTransformer

DSN = "postgresql://rag:ragdemo@localhost:5432/rag_demo"

# ... RRF_SQL is the hybrid query from Step 7, returning title and content ...

SYSTEM = (
    "Answer using ONLY the context below. If the context does not contain the "
    "answer, say so. Keep the answer to three sentences or fewer."
)

def retrieve(question):
    model = SentenceTransformer("BAAI/bge-small-en-v1.5")
    qvec = Vector(model.encode([question], normalize_embeddings=True)[0])
    with psycopg.connect(DSN, autocommit=True) as conn:
        register_vector(conn)
        or_query = ' OR '.join(question.split())
        return conn.execute(RRF_SQL, (qvec, or_query, or_query, 60)).fetchall()

def build_prompt(question, chunks):
    context = "\n\n".join(f"[{t}]\n{c}" for t, c in chunks)
    return f"{SYSTEM}\n\nContext:\n{context}\n\nQuestion: {question}\nAnswer:"

def generate(prompt):
    import torch
    from transformers import AutoModelForCausalLM, AutoTokenizer

    tok = AutoTokenizer.from_pretrained("Qwen/Qwen2.5-0.5B-Instruct")
    lm = AutoModelForCausalLM.from_pretrained(
        "Qwen/Qwen2.5-0.5B-Instruct", dtype=torch.float32
    )  # loads on CPU by default; no device_map, no accelerate needed
    messages = [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": prompt},
    ]
    text = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    inputs = tok([text], return_tensors="pt")
    out = lm.generate(**inputs, max_new_tokens=120, do_sample=False)
    return tok.decode(out[0][inputs["input_ids"].shape[1]:], skip_special_tokens=True).strip()

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("question")
    ap.add_argument("--prompt-only", action="store_true")
    args = ap.parse_args()

    chunks = retrieve(args.question)
    print("Sources:")
    for title, _ in chunks:
        print(f"  - {title}")
    prompt = build_prompt(args.question, chunks)
    if args.prompt_only:
        print("\n--- grounded prompt ---\n" + prompt)
        return
    print("\nAnswer:\n" + generate(prompt))

if __name__ == "__main__":
    main()

Two notes on the code. In transformers 5.x, torch_dtype is deprecated in favor of dtype, and passing device_map="cpu" requires the accelerate package — leaving both out loads the model on CPU with no extra dependency, which is what the code above does. And --prompt-only prints the grounded prompt without generating, which is the useful mode when you point the prompt at your own model instead: the retrieval half is the part this tutorial owns, and the generation call is one swappable function.

Run it on the question dense search got wrong:

.venv/bin/python qa.py "find the slowest queries"
# Sources:
#   - pg_stat_statements
#   - Table partitioning
#   - IVFFlat index
#
# Answer:
# Query pg_stat_statements costs the most in terms of total time and rows returned.

The whole run took about 42 seconds, nearly all of it loading the 0.5B model and generating on CPU. The answer is grounded — it comes straight from the pg_stat_statements document, which is the top retrieved source — but it is also visibly the work of a half-billion-parameter model: it restates the document rather than answering the question in its own words. That is the honest trade for a pipeline with no API key. Swap generate() for a call to any frontier model and the same retrieved context produces a much better answer; the retrieval half does not change. Verify the prompt path separately with --prompt-only — it prints the sources and the exact prompt, which is the fastest way to debug a bad answer: if the sources are wrong, fix retrieval; if the sources are right and the answer is wrong, fix the prompt or the model.

Which approach should you use?#

SituationUse thisWhy
A few thousand rows, exact answers matterNo index — exact searchPerfect recall; a scan of a small table is faster than any index
100k+ rows, latency mattersHNSW indexBest speed-recall trade-off; tune with hnsw.ef_search
Fast bulk loads, tight memoryIVFFlat indexCheaper builds, smaller footprint, worse speed-recall than HNSW
Vectors plus relational datapgvector in PostgresFilters are WHERE clauses; joins, transactions, and backups come free
Vectors only, massive scale, managedA dedicated vector databasePurpose-built scaling and sharding; you pay with a second system to operate
Keyword quality matters as much as meaningHybrid RRF, then a rerankerRRF fuses both signals in SQL; a cross-encoder on the top ten polishes the order

The decision most people get wrong is the first row: reaching for an index on a table small enough to scan. If your corpus fits in memory and your queries run in milliseconds without an index, you do not have a search problem yet — you have a table. Add the HNSW index when the sequential scan shows up in your slow-query log, not before.

The takeaway#

  1. pgvector turns the Postgres you already run into a vector store. One extension, one vector(384) column, and your embeddings live next to the rest of your data — with transactions, backups, and access control included.
  2. Keyword search is not a legacy feature. Postgres full-text search catches the exact-match cases dense search misses, and vice versa. The two methods failed on different questions in this tutorial, which is why you run both.
  3. Hybrid search is one SQL query. Reciprocal Rank Fusion needs no model and no service — a CTE for each method, a sum of 1 / (60 + rank), and the merged ranking falls out.
  4. Trust the planner over your instincts. On twelve rows it ignores the HNSW index because a scan is faster, and it is right. Measure with EXPLAIN (ANALYZE, BUFFERS) before assuming an index helps.
  5. Retrieval is the product; generation is swappable. The pipeline in this tutorial answers with a 0.5B local model and no API key. Point the same grounded prompt at a frontier model and the answers improve — the Postgres half does not change.

You now have a RAG pipeline with no new service in it: Postgres stores the documents, embeds nothing itself, and answers three kinds of search from one table. The next step is your own corpus — point the ingest script at your docs, keep the schema, and measure the same five questions again. If hybrid search stops helping, the fix is a better corpus or a reranker, not a new database.