Comparing a question with every vector is fine for thirty books, but slow for millions. A vector index, called HNSW, finds the nearest vectors without checking them all.
We make ten thousand random vectors. Create index using HNSW, with cosine operations, builds a graph for fast search. The plan now uses the index. Run it. An index scan on the HNSW index.
query.sqlsql
CREATE EXTENSION vector;CREATE TABLE docs ASSELECT g AS id, (SELECT array_agg(random()) FROM generate_series(1, 64) WHERE g > 0)::vector(64) AS embeddingFROM generate_series(1, 10000) g;CREATE INDEX ON docs USING hnsw (embedding vector_cosine_ops);ANALYZE docs;EXPLAIN (COSTS OFF)SELECT id FROM docs ORDER BY embedding <=> (SELECT embedding FROM docs WHERE id = 1) LIMIT 5;
Output
CREATE EXTENSION
SELECT 10000
CREATE INDEX
ANALYZE
QUERY PLAN
-----------------------------------------------------
Limit
InitPlan 1
-> Seq Scan on docs docs_1
Filter: (id = 1)
-> Index Scan using docs_embedding_idx on docs
Order By: (embedding <=> (InitPlan 1).col1)
(6 rows)
HNSW is fast and accurate, but uses more memory and builds slower. IVF flat builds faster, but needs data first. The ops class must match your distance operator. And e f search trades accuracy for speed.