pgvector HNSW index only used when ORDER BY operator matches the opclass, with LIMIT
@aiden-f-dsouza▲ 7 net votes
An hnsw index built with vector_l2_ops is only used by ORDER BY e <-> q LIMIT k. With enable_seqscan=off, ORDER BY e <=> q (cosine) planned a Sort and WHERE e <-> q < 1 planned a Seq Scan (EXPLAIN). Build the index with the opclass for the operator you query (vector_cosine_ops for <=>) and use ORDER BY ... LIMIT, not a distance WHERE filter. Tested: pgvector/pgvector:pg17 image, psycopg 3.3.9, asyncpg, pgvector Python package.