Sub topic 3
Creating and Querying an IVFFlat Index
This chapter assumes you have pgvector enabled, a table named items with a vector(3) column, and working knowledge of SQL. You should also know what an embedding is and how L2, cosine, and inner product distances differ.
IVFFlat is an approximate nearest-neighbor index. At build time it groups vectors into lists, each centered on a cluster centroid. A query then scans only a few lists instead of the whole table. This is faster, but the true nearest neighbors may sit in a list that the query skips.
Creating and querying an IVFFlat index
Build the index after loading the data, because the cluster centroids come from the rows present at build time.
CREATE INDEX items_embedding_ivfflat
ON items USING ivfflat (embedding vector_l2_ops)
WITH (lists = 100);
SET ivfflat.probes = 10;
SELECT id, content
FROM items
ORDER BY embedding <-> '[3,1,2]'
LIMIT 5;Matching the operator class to the query operator
The index helps only when its operator class matches the query operator. Use vector_l2_ops with <->, vector_cosine_ops with <=>, and vector_ip_ops with <#>. If they do not match, PostgreSQL skips the index and runs an exact scan.
Tuning lists, probes, and HNSW parameters
| Parameter | Index | Effect | Default |
|---|---|---|---|
| lists | IVFFlat (build) | Number of clusters; more lists means smaller clusters | none, must set |
| ivfflat.probes | IVFFlat (query) | Lists scanned per query; higher means better recall, slower queries | 1 |
| m | HNSW (build) | Connections per node; higher means better recall and more memory | 16 |
| ef_construction | HNSW (build) | Candidate breadth during build; higher means a slower build and better graph | 64 |
| hnsw.ef_search | HNSW (query) | Candidate breadth per query; higher means better recall, slower queries | 40 |
Combining vector search with WHERE filters
PostgreSQL applies the WHERE clause to candidates that the index returns. A selective filter can therefore leave fewer than LIMIT rows. Run EXPLAIN to see which index the planner chose.
ALTER TABLE items ADD COLUMN category_id integer;
CREATE INDEX items_category_idx ON items (category_id);
EXPLAIN
SELECT id FROM items
WHERE category_id = 1
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5;Querying from Python with psycopg
import numpy as np
import psycopg
from pgvector.psycopg import register_vector
conn = psycopg.connect('dbname=mydb', autocommit=True)
conn.execute('CREATE EXTENSION IF NOT EXISTS vector')
register_vector(conn)
query = np.array([3, 1, 2])
rows = conn.execute(
'SELECT id, content FROM items ORDER BY embedding <=> %s LIMIT 5',
(query,),
).fetchall()
print(rows)Measuring recall against exact search
Recall is the share of exact top-k results that the index also returns. Disable index scans for one transaction to get the exact answer.
BEGIN;
SET LOCAL enable_indexscan = off;
SELECT id FROM items
ORDER BY embedding <=> '[3,1,2]'
LIMIT 10;
COMMIT;Run the same query with the index enabled. If 8 of the 10 IDs match, recall is 0.8.
Smaller and sparse vector types
| Type | Stores | Typical use |
|---|---|---|
| halfvec | 16-bit floats, half the space of vector | Large collections where small precision loss is acceptable |
| sparsevec | Only nonzero values and their positions | Mostly-zero vectors, such as keyword weights |
| bit | One bit per dimension | Binary embeddings, compared with Hamming distance |
Index build time, memory, and maintenance
IVFFlat builds faster and uses less memory than HNSW. Its cluster centroids reflect the data at build time. After many inserts or deletes, rebuild the index with REINDEX to restore recall.
Exercise
You built an IVFFlat index with lists = 100 and queries return 3 rows where you expected 5. What should you try first, and how do you check whether it helped?
Show answer
Raise ivfflat.probes (for example, to 10) and rerun the query. Then compare the results with exact search, using the recall method above, to confirm that more of the true neighbors appear.