Dev tools
pgvector Tutorial: Vector Search in Postgres
A practical pgvector tutorial: install the extension, store embeddings, run similarity queries, add an HNSW index and use it from Python for semantic search.
pgvector is an open-source extension that adds vector search to PostgreSQL. It lets you store embeddings, the lists of numbers that AI models use to represent the meaning of text or images, right next to your normal data, and find the rows most similar to a query. For many teams that means semantic search, recommendations and retrieval-augmented generation (RAG) without running a separate vector database.
This tutorial goes from an empty database to working semantic search: installing pgvector, creating tables, inserting embeddings, querying by similarity, adding an index and using it from Python. Every SQL statement and Python snippet here was tested on PostgreSQL 16; the iterative scan setting near the end needs pgvector 0.8.0 or later. If embeddings are new to you, our guide to embeddings explains them in plain terms.
Why Use pgvector for Postgres Vector Search?
Dedicated vector databases are powerful, but Postgres vector search with pgvector has practical advantages:
- One database: embeddings live in the same tables as your users, products and documents.
- Normal SQL: filter, join and sort with the queries you already know.
- Transactions and backups: vectors get the same reliability as the rest of your data.
- Widely available: most managed Postgres services, including Supabase, Amazon RDS, Google Cloud SQL, Azure and Neon, offer pgvector.
pgvector handles millions of vectors well on suitable hardware. At very large scale or with very demanding latency needs, a dedicated system may still be worth it. Our vector database guide compares the options.
Step 1: Install pgvector
On a managed service, pgvector is usually already available; you just enable it. On your own server, install the package for your Postgres version, for example postgresql-16-pgvector on Debian and Ubuntu, or build it from source following the project's instructions.
Then enable the extension in each database where you want to use it:
CREATE EXTENSION IF NOT EXISTS vector;Check which version you have:
SELECT extversion FROM pg_extension WHERE extname = 'vector';Step 2: Create a Table With a Vector Column
A vector column has a fixed number of dimensions, which must match your embedding model. Here's a tiny example with three dimensions so you can see how it works:
CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3));
INSERT INTO items (embedding) VALUES ('[1,2,3]'), ('[4,5,6]');For real text, use the dimension your embedding model outputs. Many popular models produce 768, 1,024 or 1,536 dimensions. A table for searchable documents might look like this:
CREATE TABLE documents (
id bigserial PRIMARY KEY,
content text NOT NULL,
category text,
embedding vector(1536)
);Keep the original text in the same row, so a search result gives you both the match and the content to show or pass to a language model.
Step 3: Query by Similarity
Finding similar rows means ordering by distance to a query vector:
SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5;pgvector provides several distance operators:
| Operator | Distance | Typical use |
|---|---|---|
<-> | Euclidean (L2) distance | General-purpose distance |
<=> | Cosine distance | Text embeddings, the most common choice |
<#> | Negative inner product | Normalised embeddings, slightly faster |
<+> | L1 distance | Specialised uses |
For text embeddings, cosine distance is usually the right choice. Smaller distance means more similar. To see the score, select it as a column:
SELECT id, embedding <=> '[3,1,2]' AS distance
FROM items
ORDER BY distance
LIMIT 5;If you prefer a similarity score where higher is better, use 1 - (embedding <=> '[3,1,2]').
Step 4: Add an HNSW Index
Without an index, pgvector compares the query against every row. That gives perfect results but slows down as the table grows. An approximate index trades a little accuracy for much faster queries.
An HNSW index builds a layered graph of vectors and is the best default for most applications:
CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops);The operator class must match the operator you query with:
vector_cosine_opsfor<=>vector_l2_opsfor<->vector_ip_opsfor<#>
You can tune how thorough searches are. A higher hnsw.ef_search (default 40) improves recall at the cost of speed:
SET hnsw.ef_search = 100;The index also accepts build options, m (default 16) and ef_construction (default 64); higher values give better recall but slower builds and more memory.
IVFFlat, the alternative
pgvector also offers IVFFlat, which groups vectors into lists. It builds faster and uses less memory than HNSW but usually gives a worse balance of speed and recall, and it should be created after the table has data:
CREATE INDEX ON documents USING ivfflat (embedding vector_cosine_ops) WITH (lists = 100);
SET ivfflat.probes = 10;A good starting point for lists is the number of rows divided by 1,000 for tables up to a million rows. Most new projects should simply use HNSW.
Dimension limits
A standard vector column can only be indexed up to 2,000 dimensions; Postgres returns an error if you try to build an HNSW index on, say, a 3,072-dimension column. For larger embeddings, index a half-precision version, which supports up to 4,000 dimensions:
CREATE INDEX ON documents_large USING hnsw ((embedding::halfvec(3072)) halfvec_cosine_ops);Queries must then use the same cast, ordering by embedding::halfvec(3072) <=> .... Alternatively, many embedding models let you request fewer dimensions.
Step 5: Use pgvector From Python
The pgvector Python package adds vector support to common database drivers. With psycopg 3:
import numpy as np
import psycopg
from pgvector.psycopg import register_vector
conn = psycopg.connect("postgresql://user:password@localhost/mydb", autocommit=True)
conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
register_vector(conn)
def add_document(content, category, embedding):
conn.execute(
"INSERT INTO documents (content, category, embedding) VALUES (%s, %s, %s)",
(content, category, np.array(embedding, dtype=np.float32)),
)
def search(query_embedding, limit=5):
return conn.execute(
"SELECT id, content, embedding <=> %s AS distance "
"FROM documents ORDER BY distance LIMIT %s",
(np.array(query_embedding, dtype=np.float32), limit),
).fetchall()The embeddings come from your embedding model, either an API from a provider such as OpenAI, Google or Cohere, or a local model. Two rules matter:
- Use the same model for documents and queries. Vectors from different models aren't comparable.
- Store which model and version created each embedding, so you know what to re-embed when you change models.
Libraries exist for many other languages too, including Node.js, Go, Ruby, Java and Rust.
Building Semantic Search
Semantic search finds results by meaning rather than exact words. A search for "how do I get my money back" can find a page titled "Refund policy". The full flow is:
- Split your content into chunks, such as paragraphs or sections.
- Create an embedding for each chunk and store it with the text.
- Embed the user's query with the same model.
- Find the nearest chunks with an ORDER BY on cosine distance.
- Show the results, or pass them to a language model to write an answer, which is the core of RAG. Our guide to what RAG is explains that step.
Filtering Results
Because it's just SQL, you can combine similarity with normal filters:
SELECT id, content
FROM documents
WHERE category = 'faq'
ORDER BY embedding <=> $1
LIMIT 5;There is one catch with approximate indexes: the filter is applied after the index search. If only a small share of rows match the filter, you can get fewer results than you asked for. From pgvector 0.8.0, iterative index scans fix this by automatically searching more of the index when needed:
SET hnsw.iterative_scan = strict_order;For filters on a few distinct values, such as a tenant or language, a regular B-tree index on that column or a partial index per value can also help.
Hybrid Search: Combining Keywords and Meaning
Vector search is great at meaning but can miss exact terms like product codes and names. Postgres full-text search is great at exact words. Running both and combining the rankings, often with a method called reciprocal rank fusion, usually gives better results than either alone, and you can do it all in one database.
Performance Tips
- Create the HNSW index after loading data when you have a large initial import; building it at the end is faster.
- Give index builds more memory by raising
maintenance_work_memfor the session. - Keep the index in memory: query speed drops sharply if the index doesn't fit in RAM.
- Check your plan with EXPLAIN to make sure queries actually use the index; it needs an ORDER BY on the distance and a LIMIT.
- Measure recall by comparing indexed results with exact results on sample queries.
FAQ
What is pgvector?
pgvector is an open-source PostgreSQL extension that adds a vector data type, distance operators and approximate indexes, so you can store embeddings and run similarity search with normal SQL.
Should I use HNSW or IVFFlat?
For most applications, HNSW. It gives a better balance of speed and recall and can be built on an empty table. IVFFlat builds faster and uses less memory, which can matter for very large tables or limited hardware.
Should I use cosine distance or L2 distance?
For text embeddings, cosine distance is the usual choice. If your embeddings are normalised to length one, cosine, L2 and inner product produce the same ranking, and inner product is slightly faster.
How many dimensions can pgvector index?
Standard vector columns can be indexed with up to 2,000 dimensions. Half-precision vectors support up to 4,000, and binary quantization goes further. Columns can store more dimensions without an index.
Is pgvector good enough for production?
Yes, for many workloads. It powers search and RAG in many production apps, especially up to millions of vectors. For billions of vectors or very strict latency targets, a dedicated vector database may be a better fit.