Sub topic 9
Creating and querying an HNSW index
This chapter assumes you can write basic SQL, have pgvector enabled, and have a table with a vector column. It also assumes you know the difference between exact and approximate search from the previous chapter. The items table from earlier chapters is used throughout.
What HNSW is
HNSW stands for Hierarchical Navigable Small World. It is a graph-based index for approximate nearest-neighbor search. Each vector becomes a node. Each node is linked to a limited number of nearby nodes.
The graph has several layers. The top layers hold few nodes with long links. The bottom layer holds every node with short links. A search enters at the top, moves greedily toward the query vector, then drops one layer and repeats. At the bottom layer it explores a wider set of candidates and returns the best ones.
HNSW has two properties that matter in practice:
- It gives a good speed and recall balance, usually better than IVFFlat at the same recall.
- It does not need training data. You can create the index on an empty table and add rows later, because the graph grows as rows arrive.
The cost is build time and memory. HNSW indexes build more slowly and use more space than IVFFlat indexes.
Creating the index
This statement builds an HNSW index for cosine distance.
CREATE INDEX items_embedding_hnsw
ON items USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);Three parts need attention.
USING hnswselects the index method.vector_cosine_opsis the operator class. It must match the operator in your queries. For<=>usevector_cosine_ops. For<->usevector_l2_ops. For<#>usevector_ip_ops. The next chapter covers this in detail.mandef_constructionare build parameters.
| Parameter | Meaning | Default |
|---|---|---|
| `m` | Maximum number of links per node in each layer | 16 |
| `ef_construction` | Size of the candidate list used while inserting a row | 64 |
| `hnsw.ef_search` | Size of the candidate list used during a query | 40 |
A higher m builds a denser graph. A higher ef_construction makes the builder look at more candidates before choosing links. Both raise recall, and both increase build time and index size. ef_construction must be at least twice m.
HNSW supports at most 2,000 dimensions for the vector type. If your embeddings are larger, see the chapter on halfvec and other types.
Querying with the index
You do not call the index directly. You write the same query as for exact search, and the planner decides whether to use the index.
SET hnsw.ef_search = 100;
SELECT id, content
FROM items
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5;hnsw.ef_search is the number of candidates the search keeps while it explores the bottom layer. A larger value checks more of the graph, so recall rises and queries slow down. The default is 40.
ef_search also caps how many rows an index scan can return. If you ask for LIMIT 100 with ef_search = 40, the index returns at most 40 rows. Set ef_search to at least your LIMIT.
You can set the value in three scopes:
-- For the current session
SET hnsw.ef_search = 100;
-- For one transaction only
BEGIN;
SET LOCAL hnsw.ef_search = 200;
SELECT id FROM items ORDER BY embedding <=> '[3,1,2]' LIMIT 20;
COMMIT;
-- As a default for a database
ALTER DATABASE mydb SET hnsw.ef_search = 100;Prefer SET LOCAL inside a transaction when only some queries need high recall. It avoids changing behavior for unrelated queries on the same connection.
Checking that the index is used
The index is used only when the query has the shape the planner can match: an ORDER BY on the distance operator, in ascending order, with a LIMIT. Run EXPLAIN to confirm.
EXPLAIN
SELECT id FROM items
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5;Look for Index Scan using items_embedding_hnsw. If you see Seq Scan followed by Sort, the planner chose an exact scan. Common reasons:
- The operator class does not match the operator. An index built with
vector_l2_opscannot serve a<=>query. - The query has no
LIMIT. - The query orders by an expression, such as
1 - (embedding <=> ...), instead of the bare distance. - The table is small, and a sequential scan is cheaper. This is normal for a three-row table.
Build behavior and memory
Building an HNSW index is much faster when the graph fits in memory. The relevant setting is maintenance_work_mem. If the graph exceeds it, PostgreSQL logs a notice and the build slows down considerably.
SET maintenance_work_mem = '2GB';
SET max_parallel_maintenance_workers = 7;
CREATE INDEX items_embedding_hnsw
ON items USING hnsw (embedding vector_cosine_ops);Parallel workers speed up the build. The number of workers is limited by max_parallel_workers and max_worker_processes, so check those too.
For best build speed, load your data first and create the index afterward. Inserting rows one by one into an existing index works, but each insert updates the graph.
On a production table, use CREATE INDEX CONCURRENTLY to avoid blocking writes. It is slower and cannot run inside a transaction block.
CREATE INDEX CONCURRENTLY items_embedding_hnsw
ON items USING hnsw (embedding vector_cosine_ops);Behavior with updates and deletes
HNSW accepts inserts, updates, and deletes at any time. Deleted rows leave dead entries in the graph until VACUUM removes them. Vacuuming an HNSW index can be slow, so for tables with heavy churn, reindexing a concurrent copy is sometimes faster:
REINDEX INDEX CONCURRENTLY items_embedding_hnsw;Index size can be checked with:
SELECT pg_size_pretty(pg_relation_size('items_embedding_hnsw'));Common errors
- Recall that is lower than expected. Raise
hnsw.ef_searchfirst, since it needs no rebuild. If that is not enough, rebuild with highermandef_construction. - Fewer rows returned than the
LIMIT. This happens whenef_searchis smaller thanLIMIT, or when aWHEREfilter removes rows after the index scan. The filtering chapter covers the second case. - Index not used. Check the operator class, the
ORDER BYform, and theLIMIT, as described above. - Slow index build. Raise
maintenance_work_mem, enable parallel workers, and build after loading data. - Error about dimensions. The
vectortype needs a fixed dimension on the column, such asvector(3), for any index to be built. A column declared as plainvectorcannot be indexed.
Exercise
A table has embedding vector(768) and an HNSW index created with vector_l2_ops. A query uses ORDER BY embedding <=> $1 LIMIT 10 and EXPLAIN shows a sequential scan. What is the likely cause, and how do you fix it?
Show answer
The operator class does not match the operator. vector_l2_ops serves only <->, while the query uses <=> (cosine distance). Either change the query to use <->, or create a second index with vector_cosine_ops. If the embeddings are normalized, both give the same ranking, but the planner still needs an index whose operator class matches the operator used.
Exercise
You run a query with LIMIT 100 against an HNSW index using the default settings and get only 40 rows back, with no filter in the query. Why, and what do you change?
Show answer
The default hnsw.ef_search is 40, and an index scan returns at most that many rows. Set hnsw.ef_search to at least 100 (for example SET LOCAL hnsw.ef_search = 100; in the transaction), and consider a higher value if recall also matters.