AI Hints
Home›PostgreSQL Tutorial›Vector Search in Postgres
PostgreSQL · Lesson 101 of 120

Vector Indexes

Fast nearest neighbours.

⏱ 2 min read▶ Video at 1:31:19🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

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.

  • Millions of vectors
  • Check each? Slow
  • HNSW index

An HNSW index

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 AS
SELECT g AS id, (SELECT array_agg(random()) FROM generate_series(1, 64) WHERE g > 0)::vector(64) AS embedding
FROM 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)
Also uses _empty
1

Index choices

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.

keyvalue
HNSWfast, accurate
IVFFlatquick to build
vector_cosine_opsmatches <=>
hnsw.ef_searchspeed vs recall

Summary

HNSW indexes make vector search fast at scale. Next, hybrid search, mixing words and meaning.

Key takeaways
  • HNSW
  • vector_cosine_ops
  • Fast
Next up: Hybrid Search — words plus meaning