pgvector Integration Guide
Technology: pgvector · Category: database · Last reviewed: 2026-10-20
Source: https://tech-stack.codeamanilabs.org/guide/pgvector
Insight:
The cheapest retrieval layer: pgvector is a Postgres extension, so vectors live in the Supabase/Neon database you already pay for, next to your relational rows. You get SQL joins to business data and RLS for tenant isolation, under one backup and one bill. The catch is that an HNSW index applies
WHEREand RLS filters after it returns candidates, so selective filters silently return too few rows unless you turn on iterative index scans (0.8.0+). You also bring your own embeddings and tune the index yourself. Good up to a few million vectors per index; past that, look athalfvecplus binary quantization, Neon'slakebase_ann, or [[pinecone]].
██████╗ ██████╗ ██╗ ██╗███████╗ ██████╗████████╗ ██████╗ ██████╗
██╔══██╗██╔════╝ ██║ ██║██╔════╝██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗
██████╔╝██║ ███╗██║ ██║█████╗ ██║ ██║ ██║ ██║██████╔╝
██╔═══╝ ██║ ██║╚██╗ ██╔╝██╔══╝ ██║ ██║ ██║ ██║██╔══██╗
██║ ╚██████╔╝ ╚████╔╝ ███████╗╚██████╗ ██║ ╚██████╔╝██║ ██║
╚═╝ ╚═════╝ ╚═══╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝
pgvector Integration Guide
Focus: Vector search inside your existing Postgres (Supabase or Neon). It's the cheapest RAG retrieval layer because it adds no new service. Store embeddings in a
vectorcolumn, query with distance operators, index with HNSW, and turn on iterative scans whenever a query filters. This is the counterpoint to the managedpineconeguide.
Overview
Here is the whole pgvector loop at a glance. Once you see it, the SQL below makes sense.
flowchart LR
A["Your text"] --> B["Embedding model<br/>AI SDK embed"]
B --> C["number array"]
C --> D["Postgres table<br/>vector column + HNSW"]
E["User query"] --> B
D --> F["ORDER BY distance LIMIT k<br/>iterative scan on"]
F --> G["Nearest rows<br/>RLS applied, JOIN to business data"]
pgvector is an open-source Postgres extension (SQL name: vector) that adds vector
column types, distance operators, and two approximate-nearest-neighbour (ANN) index types.
Because it lives in Postgres:
- Embeddings sit next to relational data, so you can
JOINthe nearest neighbours to user, order, or product rows in one statement. - RLS policies apply to vector queries too. Read the RLS section below: there's a recall trap.
- It uses the WAL, so replication and point-in-time recovery work unchanged.
You bring your own embeddings (OpenAI, Voyage, Gemini, or an open model). pgvector stores and searches vectors; it doesn't generate them.
Versions (verified 2026-10-20)
| Component | Version | Notes |
|---|---|---|
| pgvector extension (upstream) | 0.8.7 (2026-10-01) | Fixes an IVFFlat build buffer overflow. 0.8.3 to 0.8.6 fixed HNSW vacuum index corruption and other IVFFlat bugs. |
| Supabase | up to 0.8.2 in the supabase/postgres image (PG 15/17) |
Check yours: SELECT extversion FROM pg_extension WHERE extname = 'vector';. Supabase's docs say to upgrade the project's Postgres from the dashboard's project settings. |
| Neon | 0.8.0 on PG 14 to 17, 0.8.6 on PG 18 | From Neon's extension table. One version back is installable. |
npm pgvector (node client) |
0.3.0 | ESM-only, Node >= 22. registerType is deprecated, so use registerTypes. The pgvector/utils import was removed. |
PyPI pgvector |
0.5.1 | |
| Docker (local dev) | pgvector/pgvector:0.8.7-pg18-trixie |
See [[local-database]]. |
Hosted versions lag upstream. Neon's PG 14 to 17 computes and Supabase are below 0.8.3, which has the HNSW vacuum-corruption fix. Prefer PG 18 on Neon for new projects, and on Supabase keep the project's Postgres upgraded. See NOTES.md.
Official Documentation
| Resource | URL |
|---|---|
| pgvector README | https://github.com/pgvector/pgvector |
| pgvector CHANGELOG | https://github.com/pgvector/pgvector/blob/master/CHANGELOG.md |
| pgvector-node | https://github.com/pgvector/pgvector-node |
| Supabase pgvector | https://supabase.com/docs/guides/database/extensions/pgvector |
| Supabase HNSW indexes | https://supabase.com/docs/guides/ai/vector-indexes/hnsw-indexes |
| Supabase hybrid search | https://supabase.com/docs/guides/ai/hybrid-search |
| Supabase RAG with permissions | https://supabase.com/docs/guides/ai/rag-with-permissions |
| Neon pgvector | https://neon.com/docs/extensions/pgvector |
| Neon Lakebase Search | https://neon.com/docs/ai/lakebase-search |
| Drizzle pg extensions | https://orm.drizzle.team/docs/extensions/pg |
1. Enable and create the table
CREATE EXTENSION IF NOT EXISTS vector; -- Neon / self-hosted
-- Supabase convention: CREATE EXTENSION IF NOT EXISTS vector WITH SCHEMA extensions;
CREATE TABLE documents (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id text NOT NULL,
content text NOT NULL,
embedding vector(1536) -- must equal the model's output dimension
);
Full schema with the tenant index, the FTS column, and RLS: examples/schema.sql.
Choosing the embedding model and dimension
| Model | Default dims | Other sizes | Normalized? | Price (per 1M tokens) |
|---|---|---|---|---|
OpenAI text-embedding-3-small |
1536 | any smaller, via dimensions |
yes | $0.02 |
OpenAI text-embedding-3-large |
3072 | any smaller, via dimensions |
yes | $0.13 |
Voyage voyage-4 / voyage-4-lite / voyage-4-large |
1024 | 256, 512, 2048 | yes | $0.06 / $0.02 / $0.12 (first 200M tokens free) |
Gemini gemini-embedding-2 |
3072 | 128 to 3072 (768, 1536, 3072 recommended) | yes, including truncated sizes | $0.20 text ($0.10 batch) |
Gemini gemini-embedding-001 (legacy) |
3072 | 128 to 3072 | only at 3072; normalize truncated output yourself | not listed on the pricing page (see NOTES) |
Rules:
- A vector index tops out at 2,000 dims. A 3072-dim model needs
halfvec(section 6), or ask the model for fewer dims (OpenAIdimensions, Voyageoutput_dimension, Geminioutput_dimensionality). Smaller vectors mean a smaller index and faster queries, with little quality loss on Matryoshka-trained models. - Never mix models in one column. Re-embed everything when you switch models. The exception is the Voyage 4 series, whose models share one embedding space.
- For normalized embeddings, cosine (
<=>) and inner product (<#>) rank results the same.<#>is slightly faster. Cosine is the safe default. - Voyage: send
input_type: "document"when indexing and"query"when searching. Gemini 2: put the task in the prompt, becausetask_typeisn't supported there.
2. Insert and query (raw SQL)
| Operator | Distance | vector / halfvec ops class |
Index support |
|---|---|---|---|
<-> |
L2 (Euclidean) | vector_l2_ops |
HNSW, IVFFlat |
<=> |
cosine | vector_cosine_ops |
HNSW, IVFFlat |
<#> |
negative inner product | vector_ip_ops |
HNSW, IVFFlat |
<+> |
L1 (taxicab) | vector_l1_ops |
HNSW only |
<~> |
Hamming (bit) |
bit_hamming_ops |
HNSW, IVFFlat |
<%> |
Jaccard (bit) |
bit_jaccard_ops |
HNSW only |
SELECT id, content, embedding <=> $1 AS distance
FROM documents
ORDER BY embedding <=> $1 -- the bare operator, ascending: index-eligible
LIMIT 5;
The index is used only for
ORDER BY <operator> ASC LIMIT n.ORDER BY 1 - (embedding <=> $1) DESCgives the same ranking but seq-scans. Compute similarity in the SELECT list if you need it, but sort by distance. (Verified with EXPLAIN on 0.8.7.)NULLvectors aren't indexed, and neither are zero vectors under cosine.
3. Choose and build an index
flowchart TD
Q0{"Under ~10k rows<br/>or selective filter?"} -->|"yes"| X["No ANN index<br/>exact scan, B-tree on filter"]
Q0 -->|"no"| Q1{"Default choice"}
Q1 --> A["HNSW<br/>best speed-recall, no training"]
Q1 -->|"build time or RAM bound"| B["IVFFlat<br/>build after data loads"]
A --> C["Ops class must match<br/>the query operator"]
B --> C
-- HNSW (default). No training step, so it can be built on an empty table.
CREATE INDEX CONCURRENTLY documents_embedding_hnsw_idx
ON documents USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64); -- the defaults
-- IVFFlat. Build only AFTER the data is loaded.
-- lists: rows/1000 up to 1M rows, sqrt(rows) above that
CREATE INDEX CONCURRENTLY ON documents USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 100);
Build-time tips (from the README, plus Neon's docs):
- Build after the bulk
COPY. UseCREATE INDEX CONCURRENTLYin production. It can't run inside a transaction, so put it in its own migration step. SET maintenance_work_mem = '2GB';for the session. If the graph doesn't fit you'll seeNOTICE: hnsw graph no longer fits into maintenance_work_mem. Neon advises keeping it at or below 50 to 60% of compute RAM. In Docker,--shm-sizemust be at least that large.SET max_parallel_maintenance_workers = 7;(default 2) for parallel builds. You may also need to raisemax_parallel_workers(default 8).- Watch progress:
SELECT phase, round(100.0 * blocks_done / nullif(blocks_total, 0), 1) FROM pg_stat_progress_create_index;
4. Tuning: recall vs speed
| Knob | Index | Default | Range | When to change |
|---|---|---|---|---|
m (build) |
HNSW | 16 | 2 to 100 | Only if raising ef_search can't reach your recall target. Requires a rebuild. |
ef_construction (build) |
HNSW | 64 | 4 to 1000 | Same as m. A higher value means a slower build and slower inserts. |
hnsw.ef_search (query) |
HNSW | 40 | 1 to 1000 | First dial. It also caps the rows a non-iterative scan can return. |
lists (build) |
IVFFlat | 100 | 1 to 32768 | rows/1000 up to 1M rows, sqrt(rows) above |
ivfflat.probes (query) |
IVFFlat | 1 | 1 to lists |
Start at sqrt(lists). Setting probes = lists means exact search, and the index stops being used. |
BEGIN;
SET LOCAL hnsw.ef_search = 100; -- SET LOCAL: this transaction only (safe behind poolers)
SELECT id FROM documents ORDER BY embedding <=> $1 LIMIT 10;
COMMIT;
Measure recall. Compare the ANN results with an exact search:
BEGIN; SET LOCAL enable_indexscan = off; SELECT ...; COMMIT;. Debug plans with
EXPLAIN (ANALYZE, BUFFERS).
5. Filtering and iterative index scans (the big pitfall)
With an ANN index, WHERE filters, including RLS policies, are applied after the index
returns candidates. HNSW returns at most ef_search (40) candidates. If your filter
matches 10% of rows, you get about 4 rows back for LIMIT 10. There's no error; the
results are just short.
flowchart LR
Q["WHERE tenant = x<br/>ORDER BY dist LIMIT 10"] --> I["HNSW returns 40<br/>nearest overall"]
I --> F["Filter keeps 4"]
F --> R["4 rows returned"]
I -.->|"iterative_scan on"| M["Keeps scanning until 10 match<br/>or max_scan_tuples"]
Fixes, in the order the README recommends:
- B-tree on the filter column (
CREATE INDEX ON documents (tenant_id)). For selective filters the planner picks it and does an exact scan of just those rows. - Iterative index scans (pgvector 0.8.0+, off by default):
SET LOCAL hnsw.iterative_scan = relaxed_order; -- or strict_order SET LOCAL hnsw.max_scan_tuples = 20000; -- default 20,000 (approximate) SET LOCAL hnsw.scan_mem_multiplier = 1; -- x work_mem, default 1; raise if max_scan_tuples doesn't help -- IVFFlat: SET LOCAL ivfflat.iterative_scan = relaxed_order; SET LOCAL ivfflat.max_probes = 100;relaxed_ordergives better recall but can return rows slightly out of order. Re-sort with a materialized CTE.+ 0is required on Postgres 17 and later:
A distance threshold (WITH nearest AS MATERIALIZED ( SELECT id, embedding <=> $1 AS distance FROM documents WHERE tenant_id = $2 ORDER BY distance LIMIT 10 ) SELECT * FROM nearest ORDER BY distance + 0;WHERE distance < 0.3) goes outside the CTE. Other filters go inside it. - Partial index when you filter on only a few distinct values
(
... USING hnsw (...) WHERE (category_id = 123)). - List partitioning by tenant (
PARTITION BY LIST (tenant_id)) when tenants are large or must not affect each other's recall and speed. The README recommends this for real multitenancy, since a shared index means one tenant's vectors affect another's recall.
6. Quantization: halfvec, bit, sparsevec
| Type | Storage per vector | Max dims stored | Max dims indexed | Use it for |
|---|---|---|---|---|
vector |
4 × d + 8 bytes | 16,000 | 2,000 | the default |
halfvec |
2 × d + 8 bytes | 16,000 | 4,000 | half the storage and index size, small recall loss; 3072-dim models |
bit |
d / 8 + 8 bytes | Postgres bit limit |
64,000 | binary quantization, Hamming/Jaccard |
sparsevec |
8 × nnz + 16 bytes | 16,000 non-zero | 1,000 non-zero | SPLADE / BM25-style sparse vectors (HNSW only) |
-- Index a 3072-dim model at half precision. The query must use the same cast.
CREATE INDEX ON docs_large USING hnsw ((embedding::halfvec(3072)) halfvec_cosine_ops);
SELECT id FROM docs_large ORDER BY embedding::halfvec(3072) <=> $1::halfvec(3072) LIMIT 10;
-- Or store halfvec directly (Supabase's automatic-embeddings guide does this).
CREATE TABLE docs_half (id bigint PRIMARY KEY, embedding halfvec(1536));
CREATE INDEX ON docs_half USING hnsw (embedding halfvec_cosine_ops);
-- Binary quantization: a tiny index, then re-rank with full vectors for recall.
CREATE INDEX ON items USING hnsw ((binary_quantize(embedding)::bit(1536)) bit_hamming_ops);
SELECT * FROM (
SELECT * FROM items
ORDER BY binary_quantize(embedding)::bit(1536) <~> binary_quantize($1)
LIMIT 40 -- over-fetch
) ORDER BY embedding <=> $1 LIMIT 10; -- re-rank exactly
The README's scaling advice is to use halfvec for the table and binary quantization with
re-ranking for the index. Both keep the working set in memory.
7. Hybrid search (keyword + semantic)
Pure vector search misses exact terms (SKUs, names, error codes, M-Pesa receipt codes).
Pure full-text search misses synonyms. Run both and fuse the results with Reciprocal
Rank Fusion: score = Σ weight / (k + rank), with k around 50 to 60.
ALTER TABLE documents ADD COLUMN fts tsvector
GENERATED ALWAYS AS (to_tsvector('english', content)) STORED;
CREATE INDEX ON documents USING gin (fts);
examples/hybrid-search.sql is a ready hybrid_search(query_text, query_embedding, match_count, ...) function adapted from Supabase's guide. It's RLS-safe (SECURITY
INVOKER), enables the iterative scan, and keeps the semantic subquery index-eligible.
Tested on pgvector 0.8.7 / PG 18. On Neon you can instead use Lakebase Search
(lakebase_text gives BM25 ranking that GIN lacks; see section 10).
8. RLS with vector queries (Supabase)
RLS works on vector queries exactly as on any other SELECT. A policy is just another
filter, so it hits the same post-filter trap as section 5. We tested this on 0.8.7:
a user owning about 2% of 3,000 rows got 1 of 5 requested rows from a plain RLS + HNSW
query, and 5 of 5 (correctly ordered, nothing leaked) through a function that enables
relaxed_order.
Checklist (examples/supabase-rls.sql):
ALTER TABLE ... ENABLE ROW LEVEL SECURITY, plus aSELECTpolicy forauthenticated.- Wrap the auth call:
owner_id = (select auth.jwt() ->> 'sub')for Clerk third-party auth, or(select auth.uid())for Supabase Auth. Without the wrapper it's evaluated per row. - Index the policy column (
owner_id). The planner can then choose an exact scan of the user's rows. - Expose search through an RPC function that is
SECURITY INVOKER(the default) and setshnsw.iterative_scanviaset_config(..., true).SECURITY DEFINERbypasses RLS. - Call it with the user's token (publishable key + Clerk session). The secret key
(
sb_secret_...) bypasses RLS. Don't use it for user-facing retrieval. - Set
search_path = public, extensionson the function, since Supabase installsvectorintoextensions.
9. TypeScript
node-postgres + pgvector (examples/search.ts)
import pg from "pg";
import pgvector from "pgvector/pg";
import { embed } from "ai";
import { openai } from "@ai-sdk/openai";
const pool = new pg.Pool({
connectionString: process.env.DATABASE_URL,
onConnect: async (client) => { await pgvector.registerTypes(client); }, // every pooled connection
});
const { embedding } = await embed({
model: openai.embeddingModel("text-embedding-3-small"),
value: "how do refunds work?",
});
const { rows } = await pool.query(
"SELECT id, content FROM documents ORDER BY embedding <=> $1 LIMIT 5",
[pgvector.toSql(embedding)],
);
The full example adds a tenant filter, an iterative scan inside BEGIN/SET LOCAL/COMMIT,
and the materialized-CTE re-sort. It type-checks under tsc --strict with
pgvector@0.3.0, pg@8.23.1, ai@7.0.146, and @ai-sdk/openai@4.0.98.
Drizzle ORM (examples/drizzle.ts)
Drizzle 0.31.0 and later ships vector / halfvec / bit / sparsevec columns plus the
cosineDistance, l2Distance, innerProduct, l1Distance, hammingDistance, and
jaccardDistance helpers. Current stable is 0.45.4; 1.0 is in beta/rc.
import { cosineDistance, sql } from "drizzle-orm";
import { drizzle } from "drizzle-orm/node-postgres";
import { bigint, index, pgTable, text, vector } from "drizzle-orm/pg-core";
export const documents = pgTable(
"documents",
{
id: bigint("id", { mode: "number" }).primaryKey().generatedAlwaysAsIdentity(),
content: text("content").notNull(),
embedding: vector("embedding", { dimensions: 1536 }),
},
(t) => [index("emb_idx").using("hnsw", t.embedding.op("vector_cosine_ops"))],
);
const db = drizzle(process.env.DATABASE_URL ?? "");
export async function nearest(queryEmbedding: number[]) {
const distance = cosineDistance(documents.embedding, queryEmbedding);
return db
.select({ id: documents.id, distance: sql<number>`${distance}` })
.from(documents)
.orderBy(distance) // ascending distance: index-eligible
.limit(5);
}
Drizzle's own similarity guide does
orderBy(desc(1 - cosineDistance(...))). That generatesORDER BY 1 - (embedding <=> $1) DESC, which can't use the HNSW index (EXPLAIN shows Seq Scan + Sort). Order by the distance itself.
Drizzle doesn't run CREATE EXTENSION. Put it in your first migration.
Other clients: Postgres.js, Kysely, Prisma, TypeORM, MikroORM, Knex, Sequelize, and Bun SQL
are covered in the pgvector-node README. With supabase-js you pass a
plain number[] to .rpc().
10. Scaling beyond plain pgvector
| Option | What it is | Where |
|---|---|---|
halfvec + binary quantization |
Smaller working set; stays plain pgvector | Everywhere |
| Read replicas / partitioning | Horizontal reads; one tenant per partition | Everywhere |
Neon Lakebase Search (lakebase_vector 1.1.1, lakebase_ann index) |
IVF + RaBitQ index over the same pgvector types and operators. Neon says it scales to 1B+ vectors with 50 to 100× faster builds than HNSW, and the index lives in storage (fast cold starts, branch-friendly). Needs PG 16+. Has lakebase_ann.prefilter. |
Neon only |
| pgvectorscale 0.9.1 (PostgreSQL License) | StreamingDiskANN index (USING diskann) plus label-filtered search |
Self-hosted / Tiger Data. Not on Supabase or Neon. |
| VectorChord 1.1.1 (AGPLv3 or ELv2) | RaBitQ IVF index, pgvector-compatible | Self-hosted. Not on Supabase or Neon. Check the license before embedding it in a product. |
| [[pinecone]] | Managed vector DB with integrated inference | Separate service |
Environment
Secrets (server-side only, stored in the vault; never NEXT_PUBLIC_):
DATABASE_URL=postgresql://...?sslmode=require
OPENAI_API_KEY=sk-...
Non-secret settings:
| Setting | Example | Notes |
|---|---|---|
| Embedding model | text-embedding-3-small |
Must match the column's dimension |
| Embedding dimensions | 1536 |
Must match vector(N) |
hnsw.ef_search |
100 |
Set per transaction with SET LOCAL |
hnsw.iterative_scan |
relaxed_order |
Turn on for any filtered or RLS query |
codeAmani notes
- Cheapest by default: reuses the Supabase/Neon Postgres already in the stack. There's no
extra service and no extra bill, which suits SME-scale features and the cost-conscious
AFRICAN_MARKET_GUIDE.mdaudience. Start here; graduate only when you outgrow it. - Filtered or RLS query = iterative scan on. Treat
SET LOCAL hnsw.iterative_scan = relaxed_order(plus a materialized-CTE re-sort) as mandatory for every tenant-scoped or RLS-protected search. Silent short results are the #1 pgvector bug. - Colocate and isolate: keep embeddings in the same DB as their source rows. Use RLS (Supabase, with Clerk third-party auth) for per-user isolation, and list partitioning when one tenant's volume would affect another's recall.
- Model choice (AI routing): OpenAI
text-embedding-3-smallstays the default (cheap, 1536 dims, indexable asvector). Use Voyagevoyage-4-litewhen you want 200M free tokens and 1024 dims. Usegemini-embedding-2for multimodal. Before shipping Swahili / East African retrieval, run your own recall test; no vendor publishes Swahili retrieval numbers we could verify. - 3072-dim models: use
halfvec(3072)or ask for fewer dims. Don't fight the 2,000-dimvectorindex limit. - Hosted versions lag: run
SELECT extversion ...at project start. Prefer Neon PG 18 (0.8.6) for new Neon projects; on Supabase keep Postgres upgraded so you get the HNSW vacuum fixes (0.8.3+) when they ship. - Security: the connection string and embedding keys stay server-side (
.env.local, Vercel env, or the Hazina vault). Never use the Supabase secret key for user-facing vector search, because it bypasses RLS. - Payments context: vector search has no payment surface. Stripe stays the default rail; M-Pesa receipt codes are a good reason to use hybrid search in Kenya-targeted support bots.
Official docs:
- https://github.com/pgvector/pgvector
- https://github.com/pgvector/pgvector/blob/master/CHANGELOG.md
- https://github.com/pgvector/pgvector-node
- https://supabase.com/docs/guides/database/extensions/pgvector
- https://supabase.com/docs/guides/ai/rag-with-permissions
- https://neon.com/docs/extensions/pgvector
- https://orm.drizzle.team/docs/extensions/pg