Skip to content
Visual explainer 3h to learn 4 steps

Vector databases & pgvector

Store and query embeddings with an approximate nearest-neighbour index.

By Invicly Tech, , in AI Engineering with Python. About 12 minutes to read.

Topic 13 of 33

In short

A vector database stores embeddings with metadata and finds the nearest ones to a query vector quickly. pgvector adds this to Postgres, so vectors live alongside your regular data.

Explained simply

Once you have thousands or millions of embeddings, you need somewhere to keep them and a fast way to find the closest ones to a question. That is what a vector database does: it stores vectors next to the text and details they came from, and answers which ones are nearest to this.

Comparing a question with every stored vector is exact but gets slow as data grows. Vector databases use special indexes that find almost the closest vectors far faster, by checking only a small, smart part of the data. This is called approximate nearest neighbour search (ANN).

pgvector is an extension for PostgreSQL, the popular open-source database. It adds a vector column type, distance operators and ANN indexes. Your embeddings then live in the same database as your users, documents and permissions, and you can query them with normal SQL.

The basics are simple: create the extension, add a vector column of the right size, insert rows, and sort by distance. The skill is in the details: choosing the index, tuning it, and filtering results without losing them.

Press Play on a diagram to walk through it one step at a time.

SequenceStore and query with pgvector
App
Embedding model
Postgres + pgvector
  1. 1Embed document chunks
    App to Embedding model: Embed document chunks
  2. 2Vectors
    Embedding model to App: Vectors
  3. 3INSERT text, metadata, vector
    App to Postgres + pgvector: INSERT text, metadata, vector
  4. 4Embed user query
    App to Embedding model: Embed user query
  5. 5ORDER BY distance LIMIT 5
    App to Postgres + pgvector: ORDER BY distance LIMIT 5
  6. 6Nearest chunks with metadata
    Postgres + pgvector to App: Nearest chunks with metadata
CompareHNSW vs IVFFlat in pgvector
HNSW
  • Layered graph of neighbours
  • Better speed and recall trade-off
  • Slower to build, more memory
  • Can be created on an empty table
  • Tune with m, ef_construction, ef_search
IVFFlat
  • Vectors grouped into lists
  • Faster to build, less memory
  • Build after the data is loaded
  • Tune with lists and probes

In depth

Installing pgvector and getting data in

pgvector must be installed on the database server, then enabled per database with CREATE EXTENSION vector. On Debian or Ubuntu with the PostgreSQL apt repository, the package is named postgresql-17-pgvector (match your server's major version). For local work, the Docker image pgvector/pgvector:pg17 comes ready to use. Most managed Postgres services already include it; you only run CREATE EXTENSION.

Declare the column with the exact dimension of your embedding model, such as vector(384) or vector(768). Inserting a vector of a different size fails.

From Python, install the pgvector package and call register_vector on a psycopg connection, so numpy arrays are sent and received as vectors. For bulk loads, insert in batches inside one transaction, or use COPY, and build the index after loading when you can, which is faster.

  • CREATE EXTENSION IF NOT EXISTS vector; once per database
  • vector(n) must match the model's dimension
  • pip install pgvector psycopg[binary]
  • Bulk load first, then create the index

Distance operators and index types

pgvector has one operator per distance. <-> is Euclidean (L2) distance, <=> is cosine distance (1 minus cosine similarity), <#> is the negative inner product, and <+> is L1 distance. In all of them, smaller means closer, which is why queries use ORDER BY ... LIMIT k.

An index only helps when it was built for the same operator: vector_cosine_ops for <=>, vector_l2_ops for <->, vector_ip_ops for <#>. And the query must have the shape ORDER BY embedding operator value LIMIT k; otherwise Postgres does an exact scan.

The two index types are HNSW and IVFFlat. Indexes on the vector type support up to 2,000 dimensions; the halfvec type, which stores half-precision numbers, can be indexed up to 4,000 and halves storage. With normalised vectors, inner product gives the same ranking as cosine and is slightly faster.

  • <=> cosine distance, <-> L2, <#> negative inner product
  • Index operator class must match the query operator
  • Use ORDER BY distance LIMIT k to use the index
  • Index limit: 2,000 dims for vector, 4,000 for halfvec

How HNSW finds neighbours, and how to tune it

HNSW (hierarchical navigable small world) builds a graph in layers. The top layer has few vectors with long links; each lower layer has more vectors and shorter links; the bottom layer has every vector. A search starts at the top, greedily walks toward the query, then drops down a layer and repeats, ending with a careful local search at the bottom.

Two build settings matter: m, the links per node (default 16), and ef_construction, the candidate list size while building (default 64). Higher values give better recall but slower builds and more memory. At query time, hnsw.ef_search (default 40) sets how many candidates are kept; raise it for better recall at some cost in speed.

IVFFlat instead groups vectors into lists (clusters). A query checks only the nearest ivfflat.probes lists (default 1). Build it after loading data; a starting point is lists = rows / 1000 up to a million rows, and probes around the square root of lists.

LayersAn HNSW search, top to bottom
  1. 1
    Top layer

    Few nodes, long jumps toward the query

  2. 2
    Middle layers

    More nodes, shorter jumps

  3. 3
    Bottom layer

    Every vector, careful local search

  4. 4
    Candidate list

    Keeps the best ef_search nodes

  5. 5
    Result

    Return the top k by distance

Filtering by metadata without losing results

Real queries filter: only this customer's documents, only the last year, only manuals. With an ANN index, Postgres first gets candidates from the index, then applies the WHERE clause. If the filter removes most candidates, you can get fewer rows than your LIMIT, even zero, although matching rows exist.

pgvector 0.8.0 added iterative index scans: SET hnsw.iterative_scan = relaxed_order (or strict_order) makes the scan keep fetching more candidates until enough rows pass the filter, up to a limit you can tune.

Other fixes depend on the filter. For a few large categories, a partial index per category (CREATE INDEX ... WHERE category = 'manual') works well. For many tenants, partitioning by tenant helps. For very selective filters, a normal B-tree index on the filter column lets Postgres pick the few matching rows and compare them exactly, which is fast because there are few.

FlowWhy a filter can return too few rows
  1. Step 1
    ANN index scan

    Returns about ef_search candidates

  2. Step 2
    WHERE tenant_id = 7

    Most candidates belong to others

  3. Step 3
    Only 3 rows survive

    LIMIT 10 is not met

  4. Step 4
    Fix

    Iterative scan, partial index or partitioning

Checking recall, and when to use a dedicated vector database

ANN means approximate, so measure how approximate. Take 50 to 100 real queries, get the exact top 10 by running them with index scans turned off (SET enable_indexscan = off inside a transaction), then compare with the indexed results. Recall at 10 is the share of the exact top 10 that the index also returned. Raise ef_search until recall is good enough for your app, while watching latency.

pgvector is a strong default: one database, transactions, joins with your other tables, and backups you already run. Dedicated vector databases such as Qdrant, Weaviate, Milvus or Pinecone can make sense at very large scale, for heavy filtered search across many tenants, or when you want built-in features like hybrid search and automatic sharding. Most apps can start with pgvector and move later if measurements say so.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Install pgvector~45m
  2. 2
    Store embeddings with metadata~45m
  3. 3
    Query nearest neighbours~45m
  4. 4
    Add an HNSW or IVFFlat index~45m

Key points

  • Exact search compares every row; ANN indexes trade a little recall for big speed.
  • HNSW gives fast, accurate queries; IVFFlat builds faster and uses less memory.
  • Store metadata like source, date and owner next to each vector for filtering.
  • In pgvector, <=> is cosine distance, so smaller means more similar.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE chunks (
  id bigserial PRIMARY KEY,
  source text,
  content text,
  embedding vector(768)
);

CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops);

SELECT source, content
FROM chunks
ORDER BY embedding <=> $1
LIMIT 5;

A vector column, an HNSW index and a nearest-neighbour query.

Inserting and querying from Python

You have chunk texts and their 768-dimension embeddings and want to store and search them. Step 1: install psycopg and pgvector, and make sure the chunks table from the explainer exists. Step 2: register the vector type on the connection so numpy arrays work. Step 3: insert a row with its source and content. Step 4: query the 5 nearest chunks by cosine distance, also returning the distance. The random vector stands in for a real embedding.

python
# pip install "psycopg[binary]" pgvector numpy
import numpy as np
import psycopg
from pgvector.psycopg import register_vector

conn = psycopg.connect("dbname=rag", autocommit=True)
register_vector(conn)
emb = np.random.rand(768).astype(np.float32)   # stand-in for a real embedding
conn.execute("INSERT INTO chunks (source, content, embedding) VALUES (%s, %s, %s)",
             ("faq.md", "Refunds take 5 working days.", emb))
rows = conn.execute("SELECT source, content, embedding <=> %s AS dist FROM chunks "
                    "ORDER BY embedding <=> %s LIMIT 5", (emb, emb)).fetchall()
for source, content, dist in rows:
    print(f"{dist:.3f} {source}: {content}")

Tuning HNSW recall on a real table

Search on 2 million chunks sometimes misses an obvious answer. Step 1: build the HNSW index with the default settings written out, so the choice is visible. Step 2: in a session, raise hnsw.ef_search from 40 to 100. Step 3: check with EXPLAIN ANALYZE that the plan uses the index and see the time. Step 4: compare results with an exact search (index scans off) for a sample of queries to measure recall, and keep the lowest ef_search that gives the recall you need.

sql
CREATE INDEX chunks_embedding_hnsw ON chunks
  USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64);

SET hnsw.ef_search = 100;   -- default 40; higher = better recall, slower

EXPLAIN ANALYZE
SELECT id FROM chunks ORDER BY embedding <=> $1 LIMIT 10;

-- exact results for comparison:
BEGIN;
SET LOCAL enable_indexscan = off;
SELECT id FROM chunks ORDER BY embedding <=> $1 LIMIT 10;
COMMIT;

Quick reference

  • CREATE EXTENSION IF NOT EXISTS vector; enables pgvector in the current database
  • <=> cosine distance, <-> L2 distance, <#> negative inner product; smaller is closer
  • Index ops must match the operator: vector_cosine_ops goes with <=>
  • HNSW defaults: m = 16, ef_construction = 64, hnsw.ef_search = 40
  • IVFFlat: lists about rows / 1000 (up to 1M rows); probes about sqrt(lists)
  • Filtered ANN can return too few rows: try SET hnsw.iterative_scan = relaxed_order (0.8.0+)
  • Measure recall against an exact search before and after tuning

Common mistakes

  • Declaring a vector size that does not match the embedding model.
  • Creating an index with a different distance operator than your queries use.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1Your index uses vector_l2_ops but queries sort by embedding <=> $1. What happens?

Question 2

2Which setting improves HNSW recall at query time?

Question 3

3A query with WHERE tenant_id = 7 ORDER BY embedding <=> $1 LIMIT 10 returns only 2 rows, though tenant 7 has thousands. Why?

Question 4

4When should you create an IVFFlat index?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Start pgvector in Docker, create a table with a vector(3) column, insert three vectors and return them ordered by cosine distance to [1,0,0].

  2. Exercise 2medium

    Add tenant_id and created_at columns to the chunks table and write a query that returns the 5 nearest chunks for one tenant from the last 90 days, with iterative scans enabled.

  3. Exercise 3hard

    Measure recall at 10 for your HNSW index at ef_search 20, 40, 100 and 200 on 50 sample queries, and record the median query time for each.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Do I need a separate vector database for RAG?
Usually not at first. pgvector handles millions of vectors well and keeps everything in one database; move to a dedicated store only if measurements show you need its scale or features.
Should I use HNSW or IVFFlat?
Start with HNSW for its better speed and recall trade-off. Choose IVFFlat if build time or memory is the main constraint.
How much storage do vectors need?
A vector uses 4 bytes per dimension plus a small header, so a 768-dimension vector is about 3 KB. A million of them is about 3 GB before indexes; halfvec halves that.
Does pgvector work on managed Postgres?
Most major managed Postgres services include pgvector. You enable it with CREATE EXTENSION vector, but check which version they offer, since features like iterative scans need 0.8.0 or newer.

Go deeper

ShareXLinkedInWhatsApp