Lesson 2 of 4 Vector Search and RAG with PostgreSQL

Tuning pgvector Indexes

This lesson explains HNSW, IVFFlat and DiskANN indexes, their parameters, how to build them efficiently and how to reduce the cost of vector search.

Learning outcomes

After completing this lesson, you will be able to:

  • Describe the build and query parameters of HNSW.
  • Compare HNSW, IVFFlat and DiskANN.
  • Explain how maintenance_work_mem affects builds.
  • Identify techniques that reduce vector compute overhead.

HNSW indexes

HNSW (Hierarchical Navigable Small World) builds a multi-layer graph in which each vector is linked to nearby vectors. A search enters at the sparse top layer and moves greedily towards the query, descending through denser layers until it reaches the closest neighbours. HNSW gives an excellent balance of speed and recall, needs no training step, and can be built on an empty table, so new rows are indexed as they arrive.

Two parameters are set when the index is built: m, the maximum number of connections per node (default 16), and ef_construction, the size of the candidate list used while building (default 64). Higher values improve recall but make the index larger and slower to build. At query time, hnsw.ef_search (default 40) sets how many candidates the search keeps; raising it improves recall at the cost of latency. It also caps the number of results: a query with LIMIT 100 and the default ef_search of 40 cannot return 100 rows through the index.

CREATE INDEX chunks_embedding_hnsw ON chunks
USING hnsw (embedding vector_cosine_ops) WITH (m = 16, ef_construction = 64);

BEGIN;
SET LOCAL hnsw.ef_search = 100;
SELECT id FROM chunks ORDER BY embedding <=> %s LIMIT 10;
COMMIT;

The following diagram shows two approaches to indexing embeddings that exceed the HNSW dimension limit, and the check that follows either one.

Two ways to index 3,072-dimension embeddings, which exceed the 2,000-dimension HNSW limit for the vector type. The team can index the column as halfvec, which allows up to 4,000 dimensions and halves index memory, or re-embed with the dimensions parameter at 1,536 or less. In both cases recall is measured against exact search before production queries switch.
The two approaches can be combined.
Match the pairs

HNSW parameters

Exam skills 2.2.3

Match each HNSW parameter with its default and effect.

Log in to try this activity Interactive activities are free with an account.

IVFFlat and DiskANN indexes

IVFFlat (inverted file with flat compression) clusters the vectors into lists with k-means and, at query time, searches only the ivfflat.probes lists whose centres are closest to the query. It builds faster and uses less memory than HNSW but has a worse speed-recall trade-off, and because the clusters are trained from existing data, the index should be built after the table is loaded and rebuilt if the data changes substantially. Starting points are lists of rows divided by 1,000 (for up to a million rows) and probes of lists divided by 10.

DiskANN, a Microsoft Research algorithm, is available on flexible server through the pg_diskann extension. It keeps compressed vectors in memory and the graph largely on SSD, giving high recall and query throughput with fast builds and lower memory needs, which suits very large collections. Its build options include max_neighbors (default 32) and l_value_ib (default 50), and diskann.l_value_is tunes the search list at query time.

HNSW
BuildSlower, more memory
Speed-recall trade-offVery good
Query parameterhnsw.ef_search
Empty tableWorks
Choose when Default choice for most workloads
IVFFlat
BuildFast, needs data first
Speed-recall trade-offModerate
Query parameterivfflat.probes
Empty tablePoor clusters
Choose when Fast, cheap builds on static data
DiskANN (pg_diskann)
BuildFast, lower memory
Speed-recall trade-offVery good
Query parameterdiskann.l_value_is
Empty tableWorks
Choose when Very large collections on flexible server
Fill in the value

Starting IVFFlat settings

Exam skills 2.2.3

Work out starting values for IVFFlat from the rules of thumb.

Log in to try this activity Interactive activities are free with an account.

Operator classes and building efficiently

Every vector index is built for one metric through its operator class: vector_l2_ops, vector_cosine_ops or vector_ip_ops (with halfvec_ equivalents). A query uses the index only when it sorts by the matching operator, and also only when it has an ORDER BY ... LIMIT shape.

Index builds are memory- and CPU-intensive. An HNSW build is much faster when the graph fits in maintenance_work_mem; when it does not, PostgreSQL prints a notice and continues more slowly. Raising maintenance_work_mem for the building session, and allowing parallel workers with max_parallel_maintenance_workers, shortens builds considerably. Bulk-loading data first and building the index afterwards is faster than inserting into an indexed table, and pg_stat_progress_create_index reports build progress.

SET maintenance_work_mem = '4GB';
SET max_parallel_maintenance_workers = 4;
CREATE INDEX CONCURRENTLY chunks_embedding_hnsw ON chunks USING hnsw (embedding vector_cosine_ops);
Select all that apply

Faster index builds

Exam skills 2.2.3

Identify the practices that make an HNSW build on 20 million rows faster.

Log in to try this activity Interactive activities are free with an account.

Reducing compute overhead

Vector search costs CPU in proportion to the number and size of vectors compared, and memory in proportion to the index size. Several techniques reduce both, usually with a small and measurable effect on recall.

  • Half precision: storing embeddings as halfvec, or indexing an expression such as (embedding::halfvec(1536)) with halfvec_cosine_ops, halves index memory; queries must use the same cast to use the index.
  • Fewer dimensions: requesting shorter embeddings from models that support it, such as 512 or 1,024 dimensions from text-embedding-3 models, shrinks every comparison.
  • Binary quantization with re-ranking: an index on a bit representation finds candidates very cheaply, and the full-precision vectors re-rank the top candidates.
  • Smaller search scopes: partial indexes per common filter value, or table partitioning by tenant, mean each search covers fewer vectors.
  • Right-sized query parameters: ef_search or probes only as high as the measured recall target requires.

Recall should be measured, not assumed: run a sample of queries with the index and with an exact search (for example with SET enable_indexscan = off in a test session) and compare the overlap of the top results.

Match the pairs

Reducing vector overhead

Exam skills 2.2.3

Match each technique with how it reduces compute or memory.

Log in to try this activity Interactive activities are free with an account.
Worked example

An index that will not fit

A team stores 10 million chunks with 3,072-dimension embeddings from text-embedding-3-large. Creating an HNSW index fails because the column has more than 2,000 dimensions. They also want to reduce the server's memory requirements, and a 1% drop in recall is acceptable.

Two approaches fit, and they can be combined. The team can index the embedding as halfvec, which supports up to 4,000 dimensions for HNSW and halves index memory, and cast the query vector the same way. Or they can re-embed with the model's dimensions parameter set to 1,536 or less, which fits vector indexes and shrinks every comparison. In both cases, they measure recall against exact search before switching production queries.

An IVFFlat index has the same 2,000-dimension limit for vector. Raising maintenance_work_mem speeds a build but does not lift the dimension limit. Dropping the index and relying on exact search would make 10-million-row queries far too slow.

Check yourself

A query with LIMIT 100 returns only 40 rows through an HNSW index. Which setting explains this?

Show answer

hnsw.ef_search, which defaults to 40, sets the candidate list size and therefore caps the rows an index scan can return. Raising it above 100 allows the full result.

Exam Tips

Remember for the exam

  • HNSW: m and ef_construction at build, hnsw.ef_search (default 40) at query time.
  • IVFFlat: build after loading data; lists and ivfflat.probes control the trade-off.
  • The operator class must match the query operator, and the query must use ORDER BY ... LIMIT.
  • Cut overhead with halfvec, fewer dimensions, quantization and smaller search scopes.