Skip to content

pgvector: EXPLAIN shows Seq Scan although an HNSW index exists

PostgreSQLtested on Ubuntu 24.04, k3s v1.37.3+k3s1, CloudNativePG 1.30.2, PostgreSQL 18.7, pgvector 0.8.7, 13 220 Vektoren × 768

The HNSW index is built and the answer is even correct – but it takes 274 ms instead of 11 ms. EXPLAIN shows that PostgreSQL reads every row.

Symptom

kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "EXPLAIN (ANALYZE, COSTS OFF) SELECT id FROM doku ORDER BY embedding <-> (SELECT embedding FROM doku WHERE id = 1) LIMIT 10;"
   ->  Sort (actual time=274.031..274.033 rows=10.00 loops=1)
         Sort Key: ((doku.embedding <-> (InitPlan 1).col1))
         Sort Method: top-N heapsort  Memory: 25kB
         Buffers: shared hit=80893
         ->  Seq Scan on doku (actual time=0.409..264.295 rows=13220.00 loops=1)
               Buffers: shared hit=80890
 Planning Time: 3.066 ms
 Execution Time: 274.200 ms

A similarity search over 13,220 vectors with 768 dimensions that has an HNSW index.

Diagnosis

The index is built with vector_cosine_ops.

kubectl -n archiv exec archiv-1 -c postgres -- psql bibliothek -c "\d doku"
Indexes:
    "doku_pkey" PRIMARY KEY, btree (id)
    "doku_hnsw" hnsw (embedding vector_cosine_ops) WITH (m='16', ef_construction='100')

Causes

operator<-> against vector_cosine_ops

<-> is the Euclidean distance, <=> the cosine distance, <#> the negative inner product. An index with vector_cosine_ops only speeds up <=>; any other ordering leaves only the Seq Scan.

plannerSeq Scan is cheaper

If a filter leaves only a few rows, the planner chooses the Seq Scan on purpose – exact and 14 ms in the course.

Fix

Use <=> in the query when comparing by cosine (as in Qdrant). If you really need the Euclidean distance, build a second index with vector_l2_ops. Check with EXPLAIN (ANALYZE): Index Scan using doku_hnsw, 11 ms instead of 274 ms in the course.

Don't: Conclude from the correct answer that the index works. The results are right with a Seq Scan too – only the time gives it away.

▶
Break it yourself and find it – free
Vector database engineering on Kubernetes, day 13: pgvector – the branch in the city archive.
Go to day 13 →

FAQ

Which operator belongs to which operator class?

<-> to vector_l2_ops, <=> to vector_cosine_ops, <#> to vector_ip_ops.

Why does a filtered search return fewer hits than LIMIT?

The index returns only ef_search candidates, and the filter then drops some. In the course 3 instead of 10 came back; with hnsw.iterative_scan (pgvector 0.8 and later) all ten came back.

Related error patterns

More