RAG on Postgres with pgvector, from chunks to cited answers.
Retrieval-augmented generation on Postgres needs two tables and one extension. Split documents into chunks, store each chunk with its embedding in a pgvector column, index it with HNSW, and at question time fetch the nearest chunks, merged with keyword matches, into the prompt. Your answers, permissions and source text stay in the database you already run.
Facts checked
The whole pipeline in one database
A RAG feature has five moving parts. Ingestion splits a document into chunks and asks an embedding model for one vector per chunk. Storage keeps the chunk text, its vector and where it came from. Retrieval embeds the question and finds the closest chunks. Generation passes those chunks to a chat model with an instruction to answer only from them. Updating re-embeds a document when it changes.
With pgvector, storage and retrieval are SQL. The chunks sit next to the rows they describe, so a JOIN gives you titles and permissions, a DELETE cascades, and backups cover the index too. You don’t need a second database to keep in sync until you have tens of millions of vectors or very high query rates.
Choose the embedding model before the schema
The model fixes the column width, and you can’t compare vectors from two different models. Store the model name on each row so you can re-embed later without guessing. pgvector indexes the vector type up to 2,000 dimensions, which rules out some models’ full-size output.
- OpenAI’s embeddings are normalized to length 1, so cosine distance and Euclidean distance rank results the same way. Use
vector_cosine_opsand the<=>operator unless your model’s docs say otherwise. - English and French in one index: a multilingual model like bge-m3 puts both languages in the same space. The keyword half of hybrid search still needs the right text-search configuration per language (
english,french). - bge-m3 also runs on Canner, in Montréal. AI endpoints serve it through an OpenAI-compatible API, so the ingestion code above works with
OPENAI_BASE_URLandOPENAI_API_KEYset andmodel: "bge-m3"; the texts aren’t stored and don’t leave Canada. It runs on processors, so it suits steady ingestion better than re-embedding millions of chunks at once.
| Model | Dimensions | Max input | Indexable as vector? |
|---|---|---|---|
OpenAI text-embedding-3-small † | 1,536 | 8,192 tokens | Yes: vector(1536) |
OpenAI text-embedding-3-large † † | 3,072 (shorter with the dimensions parameter) | 8,192 tokens | Not at full size. Request 2,000 or fewer dimensions, or index it as halfvec |
BAAI bge-m3 (open weights, MIT licence, 100+ languages) † | 1,024 | 8,192 tokens | Yes: vector(1024) |
† Competitor details come from each vendor’s own published pages on the dates shown; prices and plans change, so check the vendor before you decide. OpenAI `text-embedding-3-small` (2026-10-29) · OpenAI `text-embedding-3-large` (2026-10-29) · OpenAI `text-embedding-3-large` (2026-10-29) · BAAI `bge-m3` (open weights, MIT licence, 100+ languages) (2026-10-29)
pgvector’s type limits
| Type | Stores up to | Indexes up to | Use it for |
|---|---|---|---|
vector † | 16,000 dimensions | 2,000 dimensions | Most embedding models |
halfvec (half precision) † | 16,000 dimensions | 4,000 dimensions | Large models, and halving index size |
bit † | — | 64,000 dimensions | Binary quantization |
sparsevec † | 16,000 non-zero elements | 1,000 non-zero elements (HNSW) | Sparse models such as SPLADE |
† Competitor details come from each vendor’s own published pages on the dates shown; prices and plans change, so check the vendor before you decide. `vector` (2026-10-29) · `halfvec` (half precision) (2026-10-29) · `bit` (2026-10-29) · `sparsevec` (2026-10-29)
Schema: documents, chunks, two indexes
One row per document, one row per chunk. The generated tsv column gives you keyword search for free, and the source key lets you re-ingest a file and replace its chunks in one transaction.
-- Needs the vector extension (on Canner: canner db extensions <db> install vector)
CREATE TABLE documents (
id bigserial PRIMARY KEY,
source text NOT NULL UNIQUE, -- file path or URL, so re-ingesting replaces
title text,
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE chunks (
id bigserial PRIMARY KEY,
document_id bigint NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
ord int NOT NULL, -- position in the document
content text NOT NULL,
model text NOT NULL, -- which model made the embedding
embedding vector(1536) NOT NULL,
tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', content)) STORED
);
CREATE INDEX ON chunks USING gin (tsv);
-- Build the HNSW index after the first bulk load (see below)
CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);Ingest: chunk, embed, insert
Chunk size is a trade-off: small chunks match precisely but lose context, large ones carry context but dilute the match. A few hundred words with some overlap is a common starting point. Prefixing each chunk with its document title is cheap and helps both kinds of search. pgvector accepts a vector as text in [1,2,3] form, so JSON.stringify on the array is enough.
import OpenAI from "openai";
import pg from "pg";
const ai = new OpenAI(); // OPENAI_API_KEY from the environment
const db = new pg.Pool({ connectionString: process.env.DATABASE_URL, max: 4 });
const MODEL = "text-embedding-3-small";
// ~800-word pieces with a 100-word overlap, split on paragraphs where possible
function chunk(text, size = 800, overlap = 100) {
const words = text.split(/\s+/);
const out = [];
for (let i = 0; i < words.length; i += size - overlap) {
out.push(words.slice(i, i + size).join(" "));
if (i + size >= words.length) break;
}
return out;
}
export async function ingest(source, title, text) {
const pieces = chunk(text).map((p) => `${title}\n\n${p}`); // keep the title in every chunk
const client = await db.connect();
try {
await client.query("BEGIN");
const { rows: [doc] } = await client.query(
`INSERT INTO documents (source, title) VALUES ($1, $2)
ON CONFLICT (source) DO UPDATE SET title = $2, updated_at = now()
RETURNING id`, [source, title]);
await client.query("DELETE FROM chunks WHERE document_id = $1", [doc.id]);
for (let i = 0; i < pieces.length; i += 100) { // embed in batches
const batch = pieces.slice(i, i + 100);
const r = await ai.embeddings.create({ model: MODEL, input: batch });
for (const d of r.data) {
await client.query(
"INSERT INTO chunks (document_id, ord, content, model, embedding) VALUES ($1, $2, $3, $4, $5)",
[doc.id, i + d.index, batch[d.index], MODEL, JSON.stringify(d.embedding)]);
}
}
await client.query("COMMIT");
} catch (e) {
await client.query("ROLLBACK");
throw e;
} finally {
client.release();
}
}Retrieve: nearest chunks, then hybrid
Vector search finds chunks that mean the same thing. It is weak on exact strings: product codes, error messages, names. Full-text search is the opposite. Run both and merge the two rankings with reciprocal rank fusion: each result scores 1 / (60 + rank) in each list it appears in, and the sums decide the order. The constant 60 is the one pgvector’s own hybrid search example uses.
- `websearch_to_tsquery` never raises a syntax error, so you can pass the user’s question straight in.
- Vector search alone is the
semantichalf run by itself, shown in the next section.
-- $1 = question embedding, $2 = the question as typed
WITH semantic AS (
SELECT id, rank() OVER (ORDER BY embedding <=> $1) AS r
FROM chunks
ORDER BY embedding <=> $1
LIMIT 20
),
keyword AS (
SELECT id, rank() OVER (ORDER BY ts_rank_cd(tsv, q) DESC) AS r
FROM chunks, websearch_to_tsquery('english', $2) AS q
WHERE tsv @@ q
ORDER BY ts_rank_cd(tsv, q) DESC
LIMIT 20
)
SELECT c.id, c.content,
coalesce(1.0 / (60 + s.r), 0) + coalesce(1.0 / (60 + k.r), 0) AS score
FROM semantic s
FULL OUTER JOIN keyword k ON k.id = s.id
JOIN chunks c ON c.id = coalesce(s.id, k.id)
ORDER BY score DESC
LIMIT 8;Vector search alone
-- $1 = the question's embedding, as '[0.012, -0.034, ...]'
SELECT c.id, d.title, c.content, c.embedding <=> $1 AS distance
FROM chunks c
JOIN documents d ON d.id = c.document_id
ORDER BY c.embedding <=> $1
LIMIT 8;Filtered search returns too few rows
This is the bug most tutorials skip. With an approximate index, Postgres applies your WHERE clause after the index scan. HNSW looks at hnsw.ef_search candidates (40 by default), so if your filter matches 10% of chunks, you get about 4 rows back when you asked for 8. Per-tenant or per-collection filters hit this constantly.
pgvector 0.8.0 added iterative index scans: the index keeps scanning until enough rows pass the filter, up to hnsw.max_scan_tuples (20,000 by default). strict_order keeps exact distance order; relaxed_order gives better recall with results slightly out of order. Check your version first. For a filter that matches a small, fixed set (one tenant), a partial index or a B-tree index on the filter column can be the better fix.
-- pgvector 0.8.0+: keep scanning the index until enough rows pass the filter
SELECT extversion FROM pg_extension WHERE extname = 'vector';
BEGIN;
SET LOCAL hnsw.iterative_scan = strict_order;
SET LOCAL hnsw.ef_search = 100;
SELECT c.id, c.content
FROM chunks c
JOIN documents d ON d.id = c.document_id
WHERE d.source LIKE 'handbook/%'
ORDER BY c.embedding <=> $1
LIMIT 8;
COMMIT;Generate: answer only from the passages
Number the passages, tell the model to cite them and to say when the answer isn’t there. Then show the citations in your UI with links back to the source document. That is what lets a user check an answer, and what lets you find a bad chunk when an answer is wrong.
const context = rows.map((r, i) => `[${i + 1}] ${r.content}`).join("\n\n");
const answer = await ai.chat.completions.create({
model: "your-chat-model",
messages: [
{ role: "system", content:
"Answer only from the numbered passages. Cite them like [2]. " +
"If the passages do not contain the answer, say you don't know." },
{ role: "user", content: `${context}\n\nQuestion: ${question}` },
],
});HNSW or IVFFlat, and building the index
HNSW builds much faster when the graph fits in maintenance_work_mem, and Postgres logs a notice when it no longer fits. Raise it for the building session only, and load the initial data before creating the index. CONCURRENTLY keeps the table writable while it builds.
-- For the session that builds the index only. Stay well inside the instance's memory.
SET maintenance_work_mem = '512MB';
CREATE INDEX CONCURRENTLY chunks_embedding_hnsw
ON chunks USING hnsw (embedding vector_cosine_ops);| HNSW | IVFFlat | |
|---|---|---|
| Speed vs recall † | Better | Worse |
| Build time and memory † | Slower, more memory | Faster, less memory |
| Needs data before you create it † | No | Yes: it trains on the rows present |
| Main query setting † | hnsw.ef_search (default 40) | ivfflat.probes (default 1; start near the square root of lists) |
| Build settings † | m 16, ef_construction 64 | lists: rows / 1,000 up to 1M rows, then the square root of rows |
† Competitor details come from each vendor’s own published pages on the dates shown; prices and plans change, so check the vendor before you decide. Speed vs recall (2026-10-29) · Build time and memory (2026-10-29) · Needs data before you create it (2026-10-29) · Main query setting (2026-10-29) · Build settings (2026-10-29)
Running it on Canner
pgvector needs the dedicated Postgres instance, a $9 a month add-on per project. The shared tier has no extensions. On the instance, install it from Database → Extensions or with canner db extensions <name> install vector, then run the schema above in your release command or with psql. PostGIS, pg_trgm and unaccent are on the same list if your search needs them (extensions).
Embeddings come from whichever provider you choose. Store its key as a sensitive environment variable so it is hidden in the dashboard and scrubbed from build logs. Text you send to an outside embedding or chat API is processed wherever that provider runs it; the database, the chunks and the index stay in Montréal.
- Memory: your app and the instance share one memory budget, and the instance comes with 0.5 GB guaranteed. An HNSW index is fastest when it fits in memory. The instance has a hard memory limit, so an oversized
maintenance_work_memstops the build inside your instance rather than slowing anyone else. - Connections: each database accepts up to 20 connections at once. An ingestion script with its own pool counts against the same budget as the app (see too many connections).
- Slow queries: turn on query insights on the instance to see which retrieval queries are slow, then read find slow queries.
Questions
Is pgvector good enough for RAG in production?
For most apps, yes. With an HNSW index, retrieval stays fast for a typical app’s document set, and keeping vectors next to your data gives you joins, transactions, permissions and backups without a second system. Move to a dedicated vector store when scale or query rates outgrow one Postgres server.
Why does my pgvector query return fewer rows than the LIMIT?
The WHERE clause is applied after the approximate index scan, which only looks at ef_search candidates (40 by default). A selective filter leaves few survivors. Turn on hnsw.iterative_scan (pgvector 0.8.0+), raise hnsw.ef_search, or add an index that serves the filter.
HNSW or IVFFlat?
HNSW, in most cases: better recall for the speed, and you can create it on an empty table. IVFFlat builds faster and uses less memory, but it must be created after the data is loaded because it trains on the rows present.
Can I use text-embedding-3-large with pgvector?
Yes, but its 3,072 dimensions exceed the 2,000-dimension limit for indexing the vector type. Request fewer dimensions with the API’s dimensions parameter, or index the column as halfvec, which indexes up to 4,000.
Does Canner support pgvector?
Yes, on the dedicated Postgres instance, a $9 a month add-on per project. Install it from the database’s Extensions list or with canner db extensions <name> install vector. The shared database tier has no extensions.
Postgres with pgvector, hosted in Montréal.
Add the dedicated instance to a project and install vector from the Extensions list. See pricing.