Sub topic 10
Creating and Querying an IVFFlat Index
Assume you know basic PostgreSQL, including CREATE INDEX, SELECT, ORDER BY, and LIMIT. You should also understand that an embedding is a vector of numbers and that nearest-neighbor search finds vectors close to a query vector.
IVFFlat is an approximate nearest-neighbor index provided by pgvector. It divides vectors into groups called lists. During a query, PostgreSQL searches only some of those lists instead of comparing the query with every stored vector. This usually reduces query time, but it can miss the true nearest neighbors.
Build an IVFFlat index
The table below uses three-dimensional vectors for demonstration:
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE items (
id bigserial PRIMARY KEY,
content text NOT NULL,
embedding vector(3)
);
INSERT INTO items (content, embedding) VALUES
('a', '[1,2,3]'),
('b', '[4,5,6]'),
('c', '[1,1,1]');Create an IVFFlat index after loading representative data:
CREATE INDEX items_embedding_ivfflat
ON items USING ivfflat (embedding vector_l2_ops)
WITH (lists = 10);The lists value controls how many groups the index creates. More lists can reduce the amount of data searched per query, but they can also increase index build time and reduce recall when too few lists are searched. Recall is the fraction of the correct nearest neighbors that a search returns.
The vector_l2_ops operator class makes this index compatible with the L2 distance operator, <->.
Query the index
Set the number of lists searched for each query with ivfflat.probes:
SET ivfflat.probes = 3;
SELECT id, content, embedding <-> '[3,1,2]' AS l2_distance
FROM items
ORDER BY embedding <-> '[3,1,2]'
LIMIT 5;The default is one probe. Increasing probes searches more lists, which usually improves recall but takes more time. A value equal to lists searches every list and produces exact results, although it removes the speed advantage of the index.
You can create indexes for other metrics by matching the operator class to the query:
| Query operator | Meaning | IVFFlat operator class |
|---|---|---|
| `<->` | L2 distance | `vector_l2_ops` |
| `<=>` | Cosine distance | `vector_cosine_ops` |
| `<#>` | Negative inner product | `vector_ip_ops` |
Check whether PostgreSQL uses the index
Use EXPLAIN to inspect the query plan:
EXPLAIN
SELECT id
FROM items
ORDER BY embedding <-> '[3,1,2]'
LIMIT 5;The plan can change with table size, cost settings, and the value of ivfflat.probes. Always measure latency and recall with production-like data rather than choosing lists from a small test table.
Exercise
What happens when ivfflat.probes increases from 1 to 10?
Show answer
The query searches more lists. Recall usually improves, but query time and resource use can also increase.