pgvector Integration Guide
Why put vectors inside Postgres?
ANN inside Postgres — IVFFlat or HNSW, indexed at the planner level.
`CREATE EXTENSION vector` registers the types and operators. You index with `USING hnsw` or `USING ivfflat` and an ops class that matches your operator (`vector_cosine_ops` for `<=>`). The index is used only for `ORDER BY embedding <=> $1 LIMIT k`; sorting by `1 - distance DESC` seq-scans. The big trap is that `WHERE` filters and RLS policies run after the index returns `hnsw.ef_search` (40) candidates, so selective filters silently return too few rows. Set `hnsw.iterative_scan = relaxed_order` (0.8.0+) on every filtered query. A `vector` index tops out at 2,000 dims, so index 3072-dim models as `halfvec`. Postgres fits well up to a few million vectors per index. Beyond that, use halfvec plus binary quantization, Neon's `lakebase_ann`, or a dedicated vector DB.
Three index strategies
Same query, three structures. Pick by how you weigh build cost vs query latency vs recall.
Watch the trade-off at scale
Slide the dataset size and flip between strategies. Notice how “no index” is fine at 1K rows and unusable by 10M — and how HNSW pays a one-time build cost to keep query latency in the single-digit-ms range regardless of size.
At 1,000,000 rows, HNSW answers a top-K query in 1.0 ms with 99% recall — at the cost of 8.0 min spent building the index once. Numbers are illustrative scaling, not benchmarked guarantees — your mileage varies with dimensions, distance, hardware, and `lists`/`m` tuning.
Numbers are scaling intuition, not benchmarks. Real workloads vary on dimension count, distance operator, page-cache hit rate, and how aggressively you tune probes / ef_search.
The filter trap
With an approximate index, Postgres filters after the index scan. Make the filter selective, then flip on iterative scans (pgvector 0.8.0+). The estimate follows the pgvector README: about ef_search times the share of matching rows.
SELECT … WHERE tenant_id = $2
ORDER BY embedding <=> $1 LIMIT 10;~4 of 10 rows HNSW handed back 40 nearest rows overall, and only about 10% of them survive the filter. There's no error; the results are just short. RLS policies behave the same way.
██████╗ ██████╗ ██╗ ██╗███████╗ ██████╗████████╗ ██████╗ ██████╗
██╔══██╗██╔════╝ ██║ ██║██╔════╝██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗
██████╔╝██║ ███╗██║ ██║█████╗ ██║ ██║ ██║ ██║██████╔╝
██╔═══╝ ██║ ██║╚██╗ ██╔╝██╔══╝ ██║ ██║ ██║ ██║██╔══██╗
██║ ╚██████╔╝ ╚████╔╝ ███████╗╚██████╗ ██║ ╚██████╔╝██║ ██║
╚═╝ ╚═════╝ ╚═══╝ ╚══════╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚═╝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.
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
-- 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.
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 exactlyThe 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.