Topic 3 of 5 · 5 min read
Running pgvector next to application data
Goal: Pick an index type and settings for a pgvector table of a given size and plan how embeddings are refreshed when source rows change.
Keep embeddings in a vector column beside the row they describe, add an approximate index sized to your data, and store enough information to know when an embedding is stale. One database means one transaction, one backup, and a plain join between a similarity match and the rest of your data.
Check yourself · 1 of 3
Why store pgvector embeddings in the same Postgres database as the rest of the app data?
Why it matters
Embeddings turn text into a list of numbers so that similar meanings sit close together. pgvector, a Postgres extension, stores them as vector(n) and finds nearest neighbours with operators such as <=> for cosine distance. For a few thousand rows an exact scan is fine. Past that you need an index, and every index trades accuracy for speed.
How to do it
- Match the dimension.
vector(1536)must equal the embedding model's output size. Switching models means a new column and a full re-embed, because vectors from different models are not comparable. - Start without an index on small tables. Exact search is correct and often fast enough.
- Choose HNSW by default. It gives better speed and recall and can be built on an empty table, but it builds slower and uses more memory. Its settings are
mandef_constructionat build time andhnsw.ef_searchat query time. - Choose IVFFlat for fast builds and low memory. Build it after the table has data, because it clusters existing rows into
lists. Query withivfflat.probes; more probes means better recall and more time. - Filter carefully. An approximate index returns its nearest candidates first, then the WHERE clause removes rows. A strict filter can leave fewer rows than the LIMIT. Raise
ef_search, use iterative scans where your pgvector version has them, or index the filter column (or partition). - Track staleness. Save
embedded_hash(a hash of the source text) andembedding_modelnext to the vector. A job re-embeds rows whose hash no longer matches.
Before and after
-- Weak: index built, but no way to know which vectors are stale
ALTER TABLE docs ADD COLUMN embedding vector(1536);
CREATE INDEX ON docs USING hnsw (embedding vector_cosine_ops);
ALTER TABLE docs
ADD COLUMN embedding vector(1536),
ADD COLUMN embedded_hash text,
ADD COLUMN embedding_model text;
CREATE INDEX ON docs USING hnsw (embedding vector_cosine_ops);
-- refresh job selects rows needing work
SELECT id, body FROM docs
WHERE embedded_hash IS DISTINCT FROM md5(body) OR embedding_model <> 'text-embed-v2';
What goes wrong
- Index operator mismatch. An index built with
vector_l2_opsis ignored by a query that orders by<=>. - Build runs out of memory. An HNSW build whose graph does not fit in
maintenance_work_membecomes much slower. - Silent staleness. Someone edits a document and the vector keeps describing the old text.
- Filter returns too few rows. The index handed back 40 candidates, the tenant filter removed 38.
Examples
Tenant-filtered nearest neighbours
SET hnsw.ef_search = 100;
SELECT id, title
FROM docs
WHERE tenant_id = 42
ORDER BY embedding <=> $1
LIMIT 10;
The higher ef_search gives the index more candidates, so more survive the tenant filter. If one tenant is huge, a partial index per tenant or partitioning by tenant is safer.
IVFFlat sized to the data
-- after loading about 400,000 rows
CREATE INDEX ON docs USING ivfflat (embedding vector_cosine_ops) WITH (lists = 400);
SET ivfflat.probes = 20;
Building before loading data gives poor clusters. Check the pgvector README for the suggested starting values for your row count, then measure recall against exact search.
Key points
- The vector dimension must equal the embedding model's output size, and vectors from different models cannot be mixed.
- Small tables can use exact search with no index; add an approximate index only when queries get slow.
- HNSW usually gives better speed and recall but builds slower and uses more memory; IVFFlat builds faster and must be created after data exists.
- The query's distance operator must match the index's operator class, or the index is not used.
- With an approximate index, filters are applied after candidates are found, so strict filters can return fewer rows than requested.
- Store a source hash and model name with each embedding so a job can find and refresh stale rows.
Common mistakes
- Building an IVFFlat index on an empty table, so the clusters mean nothing.
- Ordering by a different distance operator than the one the index was built for.
- Changing the embedding model without re-embedding every row.
- Adding a strict WHERE filter to an approximate search and assuming LIMIT 10 always returns ten rows.
Check yourself · 2 of 3
You are loading 2 million rows into a new table and want the HNSW or IVFFlat index with the fewest surprises. Which statement is right?
Check yourself · 3 of 3
A document's text was edited yesterday, but similarity search still returns it for the old topic. What is the most likely cause?
Practice items, not counted towards your mastery.
Start here
- PostgreSQL: JSON types (opens in a new tab)DocsFree
jsonb versus json, the containment operator and the GIN operator classes.
- PostgreSQL: Full text search (opens in a new tab)DocsFree
tsvector, tsquery, ranking, configurations and indexes for text search.
- pgvector: open-source vector similarity search for Postgres (opens in a new tab)ToolFree
Vector types, HNSW and IVFFlat settings, filtering and the trade-offs of each index.