Use pgvector for Vector Similarity Search
Enable pgvector on Managed PostgreSQL, store embeddings, run similarity searches, and index them so that searches stay fast as the table grows.
Enable the Extension
The SQL name of pgvector is vector. Connect as avnadmin (see
Connect with psql) and
create it in each database that needs similarity search:
CREATE EXTENSION vector;SELECT extname, extversion FROM pg_extension WHERE extname = 'vector';vectorscale (pgvectorscale) is also available. It adds the diskann index type and depends on
vector: create it with CREATE EXTENSION vectorscale CASCADE;. Without CASCADE, and without
vector installed, it fails with ERROR: required extension "vector" is not installed. Start
with the HNSW index described below.
Store Vectors
Declare a vector column with the number of dimensions of your embedding model, for example
1536:
CREATE TABLE documents (
id bigserial PRIMARY KEY,
title text NOT NULL,
body text NOT NULL,
language text NOT NULL DEFAULT 'en',
created_at timestamptz NOT NULL DEFAULT now(),
embedding vector(1536)
);Write embeddings as a bracketed list of numbers, usually as a bound parameter from your application:
INSERT INTO documents (title, body, language, embedding)
VALUES ('Release notes', 'Text of the document', 'en', $1);pgvector stores and compares vectors; it does not compute embeddings. Generate them in your application with the model of your choice.
Dimension Limits
| Type | Values | Maximum dimensions | Maximum dimensions in an HNSW or IVFFlat index |
|---|---|---|---|
vector | 4-byte floats | 16000 | 2000 |
halfvec | 2-byte floats | 16000 | 4000 |
sparsevec | non-zero elements only | 16000 non-zero elements | 1000 non-zero elements |
bit | bits | bit type limit | 64000 |
An HNSW index on a vector(2001) column fails with
column cannot have more than 2000 dimensions for hnsw index. For a model with more dimensions,
for example 3072, ask the model for fewer dimensions, or index the column as halfvec.
A vector(1536) value takes about 6 KB, so it is stored out of line (TOAST). If rows also carry
large text columns, consider keeping embeddings in a separate table keyed by document ID.
Distance Operators
Each distance has an operator and a matching index operator class. An index built with
vector_cosine_ops is only used by queries that order by <=>.
| Operator | Distance | Operator class |
|---|---|---|
<-> | L2 (Euclidean) | vector_l2_ops |
<=> | Cosine distance, 1 - cosine similarity | vector_cosine_ops |
<#> | Negative inner product | vector_ip_ops |
<+> | L1 (taxicab) | vector_l1_ops, HNSW only |
<~> | Hamming, on bit | bit_hamming_ops |
<%> | Jaccard, on bit | bit_jaccard_ops |
For vectors normalized to length 1, which many embedding APIs return, cosine distance and inner product give the same ranking.
Without an index, a search reads every row and returns exact results:
SELECT id, title, embedding <=> $1 AS distance
FROM documents
ORDER BY embedding <=> $1
LIMIT 5;To show a similarity instead of a distance:
SELECT id, title, 1 - (embedding <=> $1) AS similarity
FROM documents
ORDER BY embedding <=> $1
LIMIT 5;Order by the operator expression, not by the computed column: ORDER BY embedding <=> $1 can use
an index, ORDER BY similarity DESC cannot.
Index for Approximate Search
An index makes searches approximate: much faster, with recall below 100%.
HNSW
HNSW builds a graph of the vectors. It can be created on an empty table and stays accurate as rows are added.
CREATE INDEX documents_embedding_hnsw
ON documents
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);Build parameters:
m: connections per node, 16 by default. Higher values improve recall and enlarge the index.ef_construction: candidate list size during the build, 64 by default. Higher values improve recall and slow the build.
At query time, hnsw.ef_search sets the candidate list size, 40 by default. Raise it for better
recall at the cost of speed, for the session or for one transaction:
SET hnsw.ef_search = 100;Tip
An HNSW build is fast while the graph fits in maintenance_work_mem. Read the value with
SHOW maintenance_work_mem; and raise it for the session before a large build, for example
SET maintenance_work_mem = '1GB';, within the memory of your plan. Parallel build workers are
limited by max_parallel_maintenance_workers. For more memory, see
Scale a service.
IVFFlat
IVFFlat groups vectors into lists and searches only the closest lists. It builds faster and uses less memory than HNSW, but it computes its lists from the rows present at build time. Load the data first.
CREATE INDEX documents_embedding_ivfflat
ON documents
USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 1000);lists: number of lists. A common start isrows / 1000up to one million rows, andsqrt(rows)above.ivfflat.probes: lists searched per query, 1 by default. Start aroundsqrt(lists):SET ivfflat.probes = 32;
An IVFFlat index built on an empty or unrepresentative table gives poor recall. Rebuild it with
REINDEX INDEX CONCURRENTLY after the data has changed a lot.
Choose Between the Two
| HNSW | IVFFlat | |
|---|---|---|
| Build time and memory | Higher | Lower |
| Speed at equal recall | Better | Lower |
| Can be built on an empty table | Yes | No, build after loading |
| Many inserts after the build | Handled | Needs rebuilds |
Use HNSW unless the build cost is a problem.
To halve the index size, index the column cast to halfvec, and use the same cast in queries:
CREATE INDEX documents_embedding_half
ON documents
USING hnsw ((embedding::halfvec(1536)) halfvec_cosine_ops);SELECT id FROM documents
ORDER BY embedding::halfvec(1536) <=> $1::halfvec(1536)
LIMIT 5;Check That the Index Is Used
EXPLAIN
SELECT id FROM documents ORDER BY embedding <=> $1 LIMIT 5;The plan shows Index Scan using documents_embedding_hnsw. A sequential scan with a sort means
the query uses another operator than the index, has no LIMIT, or orders by an expression that
differs from the indexed one.
Filter and Search Together
With a WHERE clause, the index returns its nearest candidates first and the filter then removes
some of them, so the query can return fewer rows than its LIMIT. Iterative scans keep reading
candidates until the LIMIT is reached:
SET hnsw.iterative_scan = strict_order;
SET ivfflat.iterative_scan = relaxed_order;strict_order(HNSW only) keeps exact distance order.relaxed_ordercan return rows slightly out of order and reads less.- The scan stops at
hnsw.max_scan_tuplesorivfflat.max_probes.
For a filter on a few fixed values, a partial index is simpler:
CREATE INDEX documents_embedding_hnsw_de
ON documents
USING hnsw (embedding vector_cosine_ops)
WHERE language = 'de';Worked Example: Document Search
CREATE TABLE kb_articles (
id bigserial PRIMARY KEY,
slug text UNIQUE NOT NULL,
title text NOT NULL,
body text NOT NULL,
language text NOT NULL DEFAULT 'en',
updated_at timestamptz NOT NULL DEFAULT now(),
embedding vector(1536) NOT NULL
);Load the articles from your application, then index and analyze:
CREATE INDEX kb_articles_embedding_hnsw
ON kb_articles
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
ANALYZE kb_articles;Embed the question with the same model, then search with that vector as $1. SET LOCAL only
works inside a transaction:
BEGIN;
SET LOCAL hnsw.ef_search = 100;
SELECT
slug,
title,
round((1 - (embedding <=> $1))::numeric, 4) AS similarity
FROM kb_articles
WHERE language = 'en'
ORDER BY embedding <=> $1
LIMIT 10;
COMMIT;To drop weak matches, filter on the distance in an outer query, so that the inner query keeps its index-friendly order:
SELECT slug, title
FROM (
SELECT slug, title, embedding <=> $1 AS distance
FROM kb_articles
WHERE language = 'en'
ORDER BY embedding <=> $1
LIMIT 50
) candidates
WHERE distance < 0.35
ORDER BY distance;Important
Stored vectors and query vectors must come from the same model, with the same number of dimensions. Distances between vectors of different models are computed without error, but mean nothing.
Useful Functions
vector_dims(embedding): number of dimensions.l2_distance(a, b),cosine_distance(a, b),inner_product(a, b),l1_distance(a, b): function forms of the operators.avg(embedding),sum(embedding): aggregates, for example to compute a centroid.subvector(embedding, start, count): part of a vector.binary_quantize(embedding): abitvalue, for a cheap first pass.
Remove the Extension
DROP EXTENSION vector;The statement fails while columns or extensions depend on vector, and lists them.
DROP EXTENSION vector CASCADE also drops those columns, embeddings included.