Topic 1 of 5 · 5 min read
Vector search inside PostgreSQL with pgvector
Goal: Write a pgvector table, index and top-k query for a chunk store and explain which distance operator matches the embedding model.
pgvector adds a vector(n) column type and distance operators to PostgreSQL, so a RAG chunk store can live in the same table, transaction and backup as the rows it describes.
Check yourself · 1 of 3
Which pgvector operator returns cosine distance?
Why it matters
Most teams already run Postgres. Keeping chunks, their text, their owner and their embedding in one row means one insert, one delete and one backup. When a document is deleted, its vectors go with it in the same transaction. A separate vector database needs a sync job for that, and sync jobs drift.
How to do it
- Enable the extension:
CREATE EXTENSION vector; - Declare the dimension to match the embedding model, for example
embedding vector(1536). Inserting a vector of another length fails, which is a useful check. - Pick the operator that matches the model. pgvector has
<->(Euclidean distance),<=>(cosine distance),<#>(negative inner product) and<+>(L1 distance). - Order by the operator and limit:
ORDER BY embedding <=> $1 LIMIT 5. Postgres returns the 5 nearest rows. - Without an index this is an exact scan of every row. That is correct and fine for tens of thousands of rows. Add an index later (next topic).
Distance is not similarity. <=> returns cosine distance, so 0 means identical and smaller is better. <#> returns the inner product multiplied by -1, because Postgres index scans only go in ascending order. To show a similarity score, convert: 1 - (embedding <=> $1) for cosine.
Before and after
-- Before: wrong operator, no limit, no way to trace a hit
SELECT content FROM chunks
ORDER BY embedding <-> $1;
This ranks by Euclidean distance although the model was trained for cosine, and sorts the whole table. The fix:
CREATE TABLE chunks (
id bigserial PRIMARY KEY,
doc_id bigint NOT NULL REFERENCES docs(id) ON DELETE CASCADE,
content text NOT NULL,
embedding vector(1536) NOT NULL
);
SELECT id, doc_id, content, embedding <=> $1 AS distance
FROM chunks
ORDER BY embedding <=> $1
LIMIT 5;
What goes wrong
- Dimension drift. The table says 1536, the team switches to a 3072-dimension model, and inserts start failing. A new model means a new column and a full re-embed.
- Operator and index disagree. An index built with
vector_l2_opsis not used by a query that orders by<=>. The query still works, as a slow exact scan. - Reading distance as similarity. A threshold like
score > 0.8written against a distance column keeps the worst matches.
Examples
Top 5 chunks for one tenant
SELECT id, content
FROM chunks
WHERE tenant_id = 42
ORDER BY embedding <=> $1
LIMIT 5;
One query returns the text and the ids needed to cite the source. No second lookup in another system.
Negative inner product
A query using <#> returns -0.83 for a good match. That is not a bug: the value is the inner product times -1 so that ascending order puts the best match first. Multiply by -1 to display it.
Key points
- pgvector stores embeddings in a
vector(n)column, so chunks, metadata and vectors share one table, transaction and backup. - The declared dimension must equal the embedding model's output length; a mismatch is rejected on insert.
<->is Euclidean distance,<=>is cosine distance and<#>is negative inner product, and smaller always means closer.- A top-k query is
ORDER BY embedding <=> $1 LIMIT k; without an index it is an exact scan of every row. - Convert cosine distance to similarity with
1 - distancebefore comparing it to a threshold.
Common mistakes
- Using
<->for a model that expects cosine, then wondering why rankings look off. - Treating the cosine distance column as a similarity score and keeping results above a threshold.
- Declaring the vector column without checking the model's output dimension.
- Forgetting
LIMIT, so Postgres sorts the entire table.
Check yourself · 2 of 3
Why does <#> return negative numbers for good matches?
Check yourself · 3 of 3
A table has embedding vector(1536). The team switches to a model that outputs 3072 numbers. What happens on insert?
Practice items, not counted towards your mastery.
Start here
- pgvector: open-source vector similarity search for Postgres (opens in a new tab)ToolFree
The README lists the column type, operators, operator classes, HNSW and IVFFlat options and their defaults.
- Efficient and robust approximate nearest neighbor search using HNSW graphs (opens in a new tab)PaperFree
The original HNSW paper: how the layered graph works and why M and the search width trade recall for speed.
- Filtering (Qdrant documentation) (opens in a new tab)DocsFree
Shows how a dedicated vector database applies payload filters inside graph search.