← Back to dashboard
pgvectordatabasefreshReader view (for NotebookLM)

pgvector Integration Guide

Why put vectors inside Postgres?

The real model

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.

Index trade-off playground1,000,000 rows
Dataset size (log scale)1,000,000 rows
1K10K100K1M10M
Strategy
Query latency (lower better)1.0 ms
Build time8.0 min
Recall@10 (higher better)99%

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.

Text
██████╗  ██████╗ ██╗   ██╗███████╗ ██████╗████████╗ ██████╗ ██████╗
██╔══██╗██╔════╝ ██║   ██║██╔════╝██╔════╝╚══██╔══╝██╔═══██╗██╔══██╗
██████╔╝██║  ███╗██║   ██║█████╗  ██║        ██║   ██║   ██║██████╔╝
██╔═══╝ ██║   ██║╚██╗ ██╔╝██╔══╝  ██║        ██║   ██║   ██║██╔══██╗
██║     ╚██████╔╝ ╚████╔╝ ███████╗╚██████╗   ██║   ╚██████╔╝██║  ██║
╚═╝      ╚═════╝   ╚═══╝  ╚══════╝ ╚═════╝   ╚═╝    ╚═════╝ ╚═╝  ╚═╝

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 vector column, query with distance operators, index with HNSW, and turn on iterative scans whenever a query filters. This is the counterpoint to the managed pinecone guide.

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 JOIN the 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)

ComponentVersionNotes
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.
Supabaseup 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.
Neon0.8.0 on PG 14 to 17, 0.8.6 on PG 18From Neon's extension table. One version back is installable.
npm pgvector (node client)0.3.0ESM-only, Node >= 22. registerType is deprecated, so use registerTypes. The pgvector/utils import was removed.
PyPI pgvector0.5.1
Docker (local dev)pgvector/pgvector:0.8.7-pg18-trixieSee [[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


1. Enable and create the table

SQL
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

ModelDefault dimsOther sizesNormalized?Price (per 1M tokens)
OpenAI text-embedding-3-small1536any smaller, via dimensionsyes$0.02
OpenAI text-embedding-3-large3072any smaller, via dimensionsyes$0.13
Voyage voyage-4 / voyage-4-lite / voyage-4-large1024256, 512, 2048yes$0.06 / $0.02 / $0.12 (first 200M tokens free)
Gemini gemini-embedding-23072128 to 3072 (768, 1536, 3072 recommended)yes, including truncated sizes$0.20 text ($0.10 batch)
Gemini gemini-embedding-001 (legacy)3072128 to 3072only at 3072; normalize truncated output yourselfnot 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 (OpenAI dimensions, Voyage output_dimension, Gemini output_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, because task_type isn't supported there.

2. Insert and query (raw SQL)

OperatorDistancevector / halfvec ops classIndex support
<->L2 (Euclidean)vector_l2_opsHNSW, IVFFlat
<=>cosinevector_cosine_opsHNSW, IVFFlat
<#>negative inner productvector_ip_opsHNSW, IVFFlat
<+>L1 (taxicab)vector_l1_opsHNSW only
<~>Hamming (bit)bit_hamming_opsHNSW, IVFFlat
<%>Jaccard (bit)bit_jaccard_opsHNSW only
SQL
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) DESC gives 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.) NULL vectors aren't indexed, and neither are zero vectors under cosine.

3. Choose and build an index

SQL
-- 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. Use CREATE INDEX CONCURRENTLY in 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 see NOTICE: 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-size must be at least that large.
  • SET max_parallel_maintenance_workers = 7; (default 2) for parallel builds. You may also need to raise max_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

KnobIndexDefaultRangeWhen to change
m (build)HNSW162 to 100Only if raising ef_search can't reach your recall target. Requires a rebuild.
ef_construction (build)HNSW644 to 1000Same as m. A higher value means a slower build and slower inserts.
hnsw.ef_search (query)HNSW401 to 1000First dial. It also caps the rows a non-iterative scan can return.
lists (build)IVFFlat1001 to 32768rows/1000 up to 1M rows, sqrt(rows) above
ivfflat.probes (query)IVFFlat11 to listsStart at sqrt(lists). Setting probes = lists means exact search, and the index stops being used.
SQL
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:

  1. 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.
  2. Iterative index scans (pgvector 0.8.0+, off by default):
    SQL
    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_order gives better recall but can return rows slightly out of order. Re-sort with a materialized CTE. + 0 is required on Postgres 17 and later:
    SQL
    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;
    A distance threshold (WHERE distance < 0.3) goes outside the CTE. Other filters go inside it.
  3. Partial index when you filter on only a few distinct values (... USING hnsw (...) WHERE (category_id = 123)).
  4. 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

TypeStorage per vectorMax dims storedMax dims indexedUse it for
vector4 × d + 8 bytes16,0002,000the default
halfvec2 × d + 8 bytes16,0004,000half the storage and index size, small recall loss; 3072-dim models
bitd / 8 + 8 bytesPostgres bit limit64,000binary quantization, Hamming/Jaccard
sparsevec8 × nnz + 16 bytes16,000 non-zero1,000 non-zeroSPLADE / BM25-style sparse vectors (HNSW only)
SQL
-- 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.

SQL
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 a SELECT policy for authenticated.
  • 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 sets hnsw.iterative_scan via set_config(..., true). SECURITY DEFINER bypasses 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, extensions on the function, since Supabase installs vector into extensions.

9. TypeScript

node-postgres + pgvector (examples/search.ts)

TypeScript
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.

TypeScript
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 generates ORDER 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

OptionWhat it isWhere
halfvec + binary quantizationSmaller working set; stays plain pgvectorEverywhere
Read replicas / partitioningHorizontal reads; one tenant per partitionEverywhere
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 searchSelf-hosted / Tiger Data. Not on Supabase or Neon.
VectorChord 1.1.1 (AGPLv3 or ELv2)RaBitQ IVF index, pgvector-compatibleSelf-hosted. Not on Supabase or Neon. Check the license before embedding it in a product.
[[pinecone]]Managed vector DB with integrated inferenceSeparate service

Environment

Secrets (server-side only, stored in the vault; never NEXT_PUBLIC_):

Bash
DATABASE_URL=postgresql://...?sslmode=require
OPENAI_API_KEY=sk-...

Non-secret settings:

SettingExampleNotes
Embedding modeltext-embedding-3-smallMust match the column's dimension
Embedding dimensions1536Must match vector(N)
hnsw.ef_search100Set per transaction with SET LOCAL
hnsw.iterative_scanrelaxed_orderTurn 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.md audience. 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-small stays the default (cheap, 1536 dims, indexable as vector). Use Voyage voyage-4-lite when you want 200M free tokens and 1024 dims. Use gemini-embedding-2 for 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-dim vector index 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.