Sub topic 9
Creating and Querying an HNSW Index
Prerequisites
This chapter assumes that you know basic PostgreSQL statements such as CREATE INDEX, SELECT, WHERE, ORDER BY, and LIMIT. It also assumes that you have enabled the pgvector extension and have a table with a vector column.
An HNSW index is an approximate nearest-neighbor index. It helps PostgreSQL find vectors that are close to a query vector without comparing the query with every row. “Approximate” means that the index can sometimes miss the mathematically closest rows in exchange for lower query time.
How HNSW search works
HNSW means Hierarchical Navigable Small World. The index organizes vectors into several graph layers. Higher layers contain fewer connections and help the search move quickly across the dataset. Lower layers contain more detail and help the search reach nearby vectors.
The search begins with a small set of candidate vectors. It follows graph connections toward vectors that are closer to the query. Because it does not inspect every row, the result can differ from exact search.
The following diagram shows the general search path:
Creating an HNSW index
Suppose items.embedding contains three-dimensional vectors and your queries use cosine distance. Create the index with the cosine operator class:
CREATE INDEX items_embedding_hnsw
ON items USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);The operator class tells PostgreSQL which distance calculation the index supports. vector_cosine_ops matches the cosine-distance operator, <=>.
The m value controls how many graph connections each vector can have. A larger value can improve search quality, but it usually increases index size and build time.
The ef_construction value controls the amount of work used while building the graph. A larger value can create a better graph, but it makes index creation slower and may use more memory.
Querying the index
Write the query with the indexed distance operator in ORDER BY:
SET hnsw.ef_search = 100;
SELECT id, content, 1 - (embedding <=> '[3,1,2]') AS cosine_similarity
FROM items
ORDER BY embedding <=> '[3,1,2]'
LIMIT 5;ef_search controls the number of candidates considered during a query. A higher value usually improves recall, which is the fraction of the true nearest neighbors that the query returns. The trade-off is higher query latency and more computation.
The expression in SELECT converts cosine distance into cosine similarity. The ORDER BY clause still uses cosine distance because the HNSW index expects that ordering.
Choosing initial settings
| Setting | Controls | Increasing it usually does |
|---|---|---|
| `m` | Connections per vector | Improves graph quality and increases index size |
| `ef_construction` | Build-time search effort | Improves graph quality and slows index creation |
| `hnsw.ef_search` | Query-time candidate count | Improves recall and increases query time |
Start with moderate values, then measure latency and recall using your own data. The best settings depend on vector count, dimension, query volume, and the recall your application requires.
Exercise
Which operator class and distance operator should you use for cosine-based HNSW search?
Show answer
Use vector_cosine_ops when creating the index, and use <=> in the nearest-neighbor ORDER BY clause.