# HNSW or IVFFlat for pgvector?

> **Quick answer:** Use HNSW unless index build time is your binding constraint.
> At matched recall it answered queries roughly four times faster in measurement
> here. IVFFlat builds an order of magnitude faster on the same data, so it suits
> tables that are rebuilt often or are too large to wait on. The build ratio
> measured between 9 and 37 times depending on the machine, so measure your own
> rather than taking a number off this page.

## What is the question?

pgvector offers two approximate index types. Both trade exact results for speed,
and both have a setting that moves along that tradeoff. The question is which
curve you would rather use.

- **HNSW** builds a navigable graph. Search walks the graph from an entry point
  towards the query. `hnsw.ef_search` sets how many candidates it keeps in flight.
- **IVFFlat** clusters the vectors into lists and records a centroid for each.
  Search compares the query to the centroids and then scans the nearest few lists.
  `ivfflat.probes` sets how many lists.

Everything below was measured on pgvector 0.8.6 on PostgreSQL 17, on a table of
100,000 rows of `vector(768)`, 403 MB, with `maintenance_work_mem` at 2GB.
Recall is recall@10 against an exact sequential scan over the same 50 query
vectors.

## How do I confirm it?

Build both and measure them yourself. The table:

<!-- sql-check: pgvector -->
```sql
CREATE TABLE items (
  id        bigserial PRIMARY KEY,
  category  int NOT NULL,
  embedding vector(768)
);
```

The two indexes, one at a time:

<!-- sql-check: pgvector -->
```sql
CREATE INDEX items_hnsw ON items USING hnsw (embedding vector_l2_ops);
```

<!-- sql-check: pgvector -->
<!-- sql-check: discard -->
```sql
CREATE INDEX items_ivf ON items USING ivfflat (embedding vector_l2_ops)
  WITH (lists = 100);
```

Then a query, with the setting specified rather than left at the default:

<!-- sql-check: pgvector -->
```sql
SET hnsw.ef_search = 100;
```

<!-- sql-check: pgvector -->
```sql
SELECT id
FROM items
WHERE id <> 1
ORDER BY embedding <-> (SELECT embedding FROM items WHERE id = 1)
LIMIT 10;
```

**`WHERE id <> 1` matters.** A row is its own nearest neighbour at distance
zero, so without that predicate one of your ten results is the query itself, in
the truth set and in the indexed result alike. Measured on 50 query vectors
here, all 50 were their own top-10 member, so it is not an occasional effect.
It is worth 0.01 of recall rather than the 0.1 you might guess,
and it moved the number **down** when the row was included rather than up,
because the inclusive form asks the index for ranks one to nine instead of one
to ten. The effect is small either way, and the predicate costs nothing.

To get a recall number you need a truth set, which means the same queries with
no index in reach:

<!-- sql-check: pgvector -->
```sql
SET enable_indexscan = off;

SELECT id
FROM items
WHERE id <> 1
ORDER BY embedding <-> (SELECT embedding FROM items WHERE id = 1)
LIMIT 10;

RESET enable_indexscan;
```

Compute the truth set before you build either index. Then it is exact by
construction and no planner setting can affect it. That is how the method here
was re-checked, and it avoids one failure mode of the `enable_indexscan`
approach below.

Use plain `SET`, not `SET LOCAL`. Outside a transaction block `SET LOCAL` has no
effect: it emits `WARNING: SET LOCAL can only be used in transaction blocks` and
the previous value stays in force. So `enable_indexscan` remains **on**, the
query you thought was your truth set used the index after all, and your recall
comes out at 1.000 because you compared the index against itself. If you prefer
`SET LOCAL`, wrap it in `BEGIN` and `COMMIT`.

Take the top 10 results for each query, then count how many of them the indexed
query also returned. That fraction is recall@10. Without it, you are measuring
only how fast you got an answer, not whether it was the answer.

## What the measurements said

### Build

| index | build, serial | build, 4 workers | size |
|---|---|---|---|
| HNSW | 300.8 s | 132.1 s | 391 MB |
| IVFFlat, `lists = 100` | 8.0 s | 9.0 s | 391 MB |

**Compare the ratio, not just the seconds.** The same fixture regenerated on a
second, faster machine (identical shape: 100,000 rows, 403 MB table, 736 heap pages,
391 MB index) built HNSW in 65.7 s serial and IVFFlat in 7.2 s. The gap moved
from 37 times to 9 times on hardware alone, with the row count, dimensions and
index parameters held constant. The absolute seconds belong to the machine
that produced them. Build your own before scheduling work around one.

The index sizes came out at 391 MB each on both machines, to the rounded
megabyte. These are the three indexes, built one at a time on the same table:

<!-- sql-check: pgvector -->
<!-- sql-check: discard -->
```sql
SET maintenance_work_mem = '2GB';

CREATE INDEX items_h16 ON items USING hnsw (embedding vector_l2_ops)
  WITH (m = 16, ef_construction = 64);

CREATE INDEX items_h32 ON items USING hnsw (embedding vector_l2_ops)
  WITH (m = 32, ef_construction = 128);

CREATE INDEX items_ivf100 ON items USING ivfflat (embedding vector_l2_ops)
  WITH (lists = 100);
```

This query reports their sizes. `pg_relation_size` is the index's own
bytes, and `relpages` is the same thing counted in pages:

<!-- sql-check: pgvector -->
```sql
SELECT c.relname, pg_relation_size(c.oid) AS bytes, c.relpages
FROM pg_class c
WHERE c.relname IN ('items_h16', 'items_h32', 'items_ivf100')
ORDER BY c.relname;
```

Measured on 2026-09-21 on pgvector 0.8.6 in a `pgvector/pgvector:0.8.6-pg17`
container, on 100,000 rows of `vector(768)`:

```
   relname    |   bytes   | relpages
--------------+-----------+----------
 items_h16    | 409608192 |    50001
 items_h32    | 409608192 |    50001
 items_ivf100 | 410066944 |    50057
```

The two HNSW figures are stable across rebuilds. The IVFFlat one is not quite:
a separate build of the same index on the same table, same day and same
pgvector 0.8.6 in `pgvector/pgvector:0.8.6-pg17`, came out at 410,058,752 bytes
and 50,056 pages, one page smaller, on that same pgvector 0.8.6 container on
2026-09-21. IVFFlat picks its centroids from a sample, so a rebuild is not
bit-for-bit the previous build. That is a difference of 8 kB
in 391 MB. It is why the HNSW result can be read as exact and this one as
approximate.

**Doubling `m` changed the index size by zero bytes.** That is exact: on
2026-09-21 on pgvector 0.8.6 in `pgvector/pgvector:0.8.6-pg17`, the two HNSW
indexes are byte-identical, and they were built separately on the same table.
The usual caveat, that raising `m` grows the graph, is not what happens at this
shape. 50,001 pages holding 100,000 tuples is two
tuples to a page, and a 768-dimensional vector is about 3 kB of that page
before any graph links are stored. The vector payload makes up most of the
index, and at both `m` values the links still fit in what is left.

That is a statement about the 768 dimensions and 100,000 rows measured on
2026-09-21 on pgvector 0.8.6 in `pgvector/pgvector:0.8.6-pg17`, not a general rule
in the other direction. Fewer dimensions leave more of each page for links, and
there `m` should start to tell. You cannot read index size off the parameters, so
measure the shape you have.

Disk is not the only resource in the comparison. pgvector's documentation
describes the trade in both directions. On
[HNSW](https://github.com/pgvector/pgvector/blob/v0.8.6/README.md#hnsw):

> It has better query performance than IVFFlat (in terms of speed-recall
> tradeoff), but has slower build times and uses more memory.

And on [IVFFlat](https://github.com/pgvector/pgvector/blob/v0.8.6/README.md#ivfflat):

> It has faster build times and uses less memory than HNSW, but has lower query
> performance (in terms of speed-recall tradeoff).

That is memory, not bytes on disk, and the two should be kept separate: these
indexes measured the same size while having different memory characteristics.

Both index types build in parallel in pgvector 0.8.6, measured by counting rows
in `pg_stat_activity` with `backend_type = 'parallel worker'` during each build.
HNSW gained 2.3 times from it. IVFFlat gained little: on the second machine,
7.2 s serial against 5.7 s with workers running. Do not read the 8.0 against 9.0
as a slowdown. Nine repeated IVFFlat builds on a second table of the same shape
ran between 7.3 s and 14.8 s with the arms overlapping completely, so at this
size the run-to-run spread is larger than anything parallelism does.

These timings do not establish why IVFFlat gains so little. The
k-means pass that produces the centroids is one possible cause and pgvector
reports it as its own phase, but attributing the result to it would need phase
timings from `pg_stat_progress_create_index` rather than a total. The measured
result is the total, and at this size the total barely moves.

**Getting four workers takes more than the setting.** Setting
`max_parallel_maintenance_workers = 4` on this table launched zero workers, for
both index types, and the build time did not move: 296.5 s against 300.8 s
serial for HNSW. PostgreSQL decides how many workers to **request** with a cost
model, and the dominant input to it is the size of the heap. The `vector` type
is stored `EXTERNAL`, so every vector lives in the TOAST table and the heap is
tiny. This 403 MB table has a 5,888 kB heap, 736 pages, under the 1,024 pages
that `min_parallel_table_scan_size` asks for before the model will consider one
worker. The planner therefore sees a 403 MB table, measures 5 MB, and declines.

This reproduced on a second table built by the same generator: 308.2 s serial,
313.7 s with `max_parallel_maintenance_workers = 4` and no workers launched,
141.1 s once the table allowed them. It also reproduced on different hardware:
736 heap pages, `max_parallel_maintenance_workers = 4`, zero workers sampled
throughout, 70.9 s against 65.7 s serial.

Check the heap rather than the table:

<!-- sql-check: pgvector -->
```sql
SELECT pg_size_pretty(pg_relation_size('items')) AS heap,
       pg_size_pretty(pg_total_relation_size('items')) AS total,
       pg_relation_size('items') / 8192 AS heap_pages;
```

If `heap_pages` is under 1,024, raising `max_parallel_maintenance_workers` will
not get you a parallel build, because that setting is a ceiling on a number the
cost model is declining to ask for. Parallelism is still possible. Override the
cost model on the table instead, which asks directly:

<!-- sql-check: pgvector -->
```sql
ALTER TABLE items SET (parallel_workers = 4);

ALTER TABLE items RESET (parallel_workers);
```

That produced the four-worker column above, confirmed by counting rows
in `pg_stat_activity` with `backend_type = 'parallel worker'` during each build.
On the second machine that sampling read four workers in 120 of 129 samples
across an HNSW build, and four in a 6.6 s IVFFlat build as well.

`parallel_workers` is a request, not a guarantee. Workers still have to be
available under `max_parallel_workers` and `max_worker_processes`, and the build
needs shared memory in proportion to `maintenance_work_mem`. In a container with
the default 64 MB `/dev/shm`, the four-worker HNSW build with
`maintenance_work_mem = 2GB` died with
`could not resize shared memory segment ... No space left on device`. That error
comes from the container limit, not from pgvector.

Reset the setting afterwards: it applies to queries against the table too, not
only to index builds.

**Sample fast enough to see them.** A 6 s IVFFlat build launches workers for
part of that window, and a once-a-second sample missed them entirely on the
first attempt here, which led to the conclusion that "IVFFlat does not
parallelise at all". It does. If you are counting workers, poll in a tight loop
rather than on a timer.

### Recall against latency

HNSW, varying `hnsw.ef_search`:

| `ef_search` | recall@10 | mean latency |
|---|---|---|
| 40 (default) | 0.718 | 21.9 ms |
| 100 | 0.814 | 19.1 ms |
| 200 | 0.880 | 27.8 ms |
| 400 | 0.946 | 53.2 ms |

IVFFlat, varying `ivfflat.probes`:

| `probes` | recall@10 | mean latency |
|---|---|---|
| 1 (default) | 0.166 | 3.6 ms |
| 10 | 0.510 | 25.0 ms |
| 32 | 0.786 | 75.2 ms |
| 100 | 1.000 | 914.1 ms |

Compare those tables at similar recall rather than reading each one from top
to bottom. Around recall 0.8, HNSW cost 19.1 ms and IVFFlat cost 75.2 ms.

The IVFFlat table shows two more things. Its default of one probe gave
recall 0.166, which is a sixth of the right answers, and nothing warns you.
And `probes = 100` against `lists = 100` is every list, so it is an exhaustive
scan through an index: recall 1.000, and 914 ms against 1,284 ms for the plain
sequential scan it was supposed to beat.

## How do I choose?

**Choose HNSW** when the table serves queries and you can afford the build. The
latency at a given recall is better, the default is more usable, and it
degrades as you insert rows.

**Choose IVFFlat** when build time is the constraint: a table rebuilt nightly, a
table so large that a multi-hour HNSW build is not a thing you can schedule, or an
index you need back quickly after a restore. Set `probes` deliberately,
because the default is too low to rely on.

**Build IVFFlat only on populated data.** Its lists come from clustering the rows
present at build time. Build it on an empty table and it will succeed, but its
centroids will describe nothing.

**Do not choose on size alone.** They measured identical here, at the default
HNSW parameters. Raising `m` to 32 did not change that either.

**Check what your queries filter on before you choose either.** Everything above
is an unfiltered nearest-neighbour search. Add
`WHERE category = $1 ORDER BY embedding <-> $2 LIMIT 10` and the result changes,
because an approximate index finds neighbours in the whole collection and the
filter is applied to what comes back. A selective predicate can therefore leave
you with fewer than ten rows. pgvector added a remedy for this, from
[Iterative Index Scans](https://github.com/pgvector/pgvector/blob/v0.8.6/README.md#iterative-index-scans):

> Starting with 0.8.0, you can enable iterative index scans, which will
> automatically scan more of the index until enough results are found (or it
> reaches `hnsw.max_scan_tuples` or `ivfflat.max_probes`).

Those scans come in strict and relaxed ordering, which is a separate tradeoff.
For a highly
selective filter, a plain B-tree on the filter column plus an exact scan over
the small surviving set may be faster and correct, with no recall question.
That needs its own measurement.

**Account for churn, not only for the first build.** These numbers are from a
table that was loaded once. HNSW graph maintenance under heavy updates and
deletes is a running cost, and pgvector's
[Vacuuming](https://github.com/pgvector/pgvector/blob/v0.8.6/README.md#vacuuming) section is two
sentences long:

> Vacuuming can take a while for HNSW indexes. Speed it up by reindexing first.

The order it gives is `REINDEX INDEX CONCURRENTLY index_name;` and then
`VACUUM table_name;`. If your table is update-heavy or delete-heavy rather than
append-only, measure the steady state and not just the build, because that cost
is not in any number on this page.

## Why does AI-generated code cause this?

Ask an assistant for vector search in Postgres and you often get
`CREATE INDEX ... USING ivfflat ... WITH (lists = 100)` and a query, with no
`probes` and no recall check. That is the shape of the example in circulation. It
runs, it is fast, and at the default one probe it returned a sixth of the correct
neighbours in measurement here. Nothing in that code is wrong enough to raise an
error, which is why it survives review.

## How do I stop it coming back?

**Measure recall, not only latency.** An approximate index that returns the wrong
rows quickly looks like a win in a latency dashboard.

**Set `ef_search` or `probes` explicitly in the application**, next to the query,
so the trade is visible to whoever reads it next.

**Re-measure after the data grows.** Both indexes were measured at 100,000 rows.
IVFFlat's centroids in particular go stale as the distribution moves.

**Benchmark on your own embeddings.** The same HNSW index measured recall 0.718 at
`ef_search = 40` on clustered data and 0.185 on uniform random vectors of the same
width. Random vectors have no neighbourhoods to find, so every approximate index
looks broken and the numbers tell you about your generator.

## How DBGorilla helps

DBGorilla connects read-only and reports the vector index the way it reports any
other: topology snapshots of each index definition, and index and table sizes
recorded as metrics over time, so a
graph index growing against its table is visible over time, and workload by
query fingerprint with duration and buffer counters, so the search query's real
latency is there rather than the one from your benchmark. All of
that was verified in a live session.
[Get started free →](https://app.dbgorilla.com/signup)

## Related

- [Why is my pgvector HNSW index taking forever to build?](https://www.dbgorilla.com/learn/postgres/why-is-my-pgvector-hnsw-index-taking-forever-to-build/)
- [Why are vector results slow after adding a metadata filter?](https://www.dbgorilla.com/learn/postgres/why-are-vector-results-slow-after-adding-a-metadata-filter/)
- [When to leave pgvector for a dedicated vector database](https://www.dbgorilla.com/learn/postgres/when-to-leave-pgvector-for-a-dedicated-vector-database/)