Semantic search in PostgreSQL with pgvector: indexes, operators and filters
Store embeddings next to your data with pgvector. Choose the right distance operator, pick HNSW or IVFFlat, and avoid the filtering trap that returns too few rows.
- Author
- Salon Rai
- 4 min read
pgvector adds a vector type and similarity search to PostgreSQL. If your application already runs on Postgres, it lets embeddings live in the same table as the rows they describe, filtered with ordinary WHERE clauses, joined to other tables and backed up with everything else. This guide covers the parts that decide whether search is correct and fast: the distance operator, the index type, and filtering. The SQL follows the pgvector README for version 0.8.7. pgvector on GitHub
Create a table and store embeddings
Enable the extension once in each database that uses it, then declare a column with the embedding dimension. Three dimensions keep the example readable; real embedding models produce hundreds or thousands.
CREATE EXTENSION vector;
CREATE TABLE items (
id bigserial PRIMARY KEY,
category_id int,
embedding vector(3)
);
INSERT INTO items (category_id, embedding) VALUES
(1, '[1,2,3]'),
(1, '[4,5,6]'),
(2, '[1,2,4]');
Pick the operator that matches your embeddings
pgvector exposes distances as operators. Smaller means closer for all of them, which is why queries sort ascending.
| Operator | Distance | Typical use |
|---|---|---|
<-> |
L2 (Euclidean) | Embeddings trained for Euclidean distance |
<=> |
Cosine distance | Most text embedding models |
<#> |
Negative inner product | Normalized embeddings, fastest to compute |
<+> |
L1 (taxicab) | Less common, supported for vector |
<~> / <%> |
Hamming / Jaccard | Binary (bit) vectors |
The inner-product operator returns the negative value because Postgres index scans only run in ascending order. To get the actual similarity numbers, convert:
-- Five nearest neighbours by cosine distance
SELECT id, 1 - (embedding <=> '[3,1,2]') AS cosine_similarity
FROM items
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5;
-- Inner product as a positive number
SELECT id, (embedding <#> '[3,1,2]') * -1 AS inner_product
FROM items;
Use the metric your embedding model was trained for. For normalized vectors, cosine distance and inner product produce the same ranking; for unnormalized ones they can disagree, as shown in cosine similarity vs. dot product for embedding search.
Add an approximate index: HNSW or IVFFlat
Without an index, every query compares the query vector with every row. That is exact, and fine for thousands of rows. For more, pgvector offers two approximate index types, which trade a little recall for a large speed-up. The index operator class must match the operator in your queries: an index built with vector_cosine_ops serves <=>.
HNSW builds a multilayer graph. The README describes it as having better query performance than IVFFlat in terms of the speed–recall trade-off, with slower build times and more memory. It can be created on an empty table because there is no training step.
CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops);
-- Build parameters, shown with their defaults
CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
-- Query-time candidate list size (default 40). Higher: better recall, slower.
SET hnsw.ef_search = 100;
IVFFlat divides vectors into lists and searches the closest ones. It builds faster and uses less memory than HNSW, with a weaker speed–recall trade-off. Because it learns its lists from the data, create it after the table has data. The README suggests starting with rows / 1,000 lists for up to 1 million rows and the square root of the row count above that, and about the square root of the list count for probes.
CREATE INDEX ON items USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
-- Lists searched per query (default 1)
SET ivfflat.probes = 10;
For most applications HNSW is the better default. Choose IVFFlat when build time or memory is the binding constraint. In both cases, the README recommends adding indexes after loading the initial data.
Advertisement
The filtering trap: fewer results than you asked for
This is the problem that surprises most teams. With approximate indexes, filtering is applied after the index is scanned. The README’s example: with HNSW’s default ef_search of 40, a condition that matches 10% of rows returns only about 4 rows on average, even if the query asks for 10.
SELECT id FROM items
WHERE category_id = 123
ORDER BY embedding <=> '[3,1,2]'
LIMIT 10; -- may return fewer than 10 rows
There are four fixes, depending on the data:
-
Index the filter column with an ordinary B-tree index. For conditions matching a small share of rows, Postgres can use it and compute exact distances on the few matching rows.
CREATE INDEX ON items (category_id); -
Use iterative index scans, available since pgvector 0.8.0. The index keeps scanning until enough rows pass the filter.
SET hnsw.iterative_scan = strict_order; -- results in exact distance order SET hnsw.iterative_scan = relaxed_order; -- better recall, slightly out of order -
Create partial indexes when the filter has only a few distinct values.
CREATE INDEX ON items USING hnsw (embedding vector_l2_ops) WHERE (category_id = 123); -
Raise
hnsw.ef_searchso more candidates survive the filter, at some cost in speed.
Test with your real filters. A search that looks perfect without a WHERE clause can quietly return half-empty pages with one.
Mind the dimension limits
The vector type stores up to 16,000 dimensions, but HNSW and IVFFlat indexes on vector support up to 2,000. Some current embedding models produce more than that. Half-precision vectors index up to 4,000 dimensions, which covers them at half the storage. Check your model’s output size before designing the table.
Measure recall, not just speed
An approximate index can be fast and wrong. Before tuning, compute exact results for a sample of queries (without the index, or with a large ef_search) and compare them with the indexed results. The share of exact neighbours the index returns is its recall@k, the same measure used for RAG retrieval in Recall@k vs. MRR. Tune ef_search or probes until recall meets your bar, then check latency.
Next steps
Start with an HNSW index using the operator class that matches your embedding model, add a B-tree index on every column you filter by, and turn on iterative scans if filtered queries return short pages. The document Q&A with RAG project uses this setup for its retrieval layer.

Written by
Advertisement