Tuning a pgvector HNSW index comes down to four settings: m and ef_construction at build time (defaults 16 and 64), hnsw.ef_search at query time (default 40), and, for filtered queries, hnsw.iterative_scan, which pgvector added in 0.8.0. Raise hnsw.ef_search first, because it trades latency for recall without a rebuild; turn on iterative scans for any query with a WHERE clause; and give the build enough maintenance_work_mem to hold the graph. Measure every change with recall@k against exact search, because "the index is used" says nothing about whether it returns the right rows.

Everything below was run on PostgreSQL 18.6 with pgvector 0.8.7, the latest release at the time of writing (October 1, 2026, per the pgvector changelog), on an Apple Silicon laptop. The recall@k script is included in full so you can reproduce the numbers on your own data, which is the only place they actually matter.

How pgvector HNSW works, in the parts you can tune

HNSW builds a layered proximity graph. At build time each vector is linked to up to m neighbours per layer, chosen from a candidate list of size ef_construction. At query time the search walks the graph keeping a candidate list of size hnsw.ef_search, and returns the best LIMIT rows from it.

Setting Where Default What raising it does
m CREATE INDEX ... WITH (m = ...) 16 Better recall, bigger index, slower build
ef_construction CREATE INDEX ... WITH (ef_construction = ...) 64 Better graph quality, slower build
hnsw.ef_search SET per session or transaction 40 Better recall, slower queries
hnsw.iterative_scan SET off Keeps scanning until filtered queries fill LIMIT
hnsw.max_scan_tuples SET 20,000 Upper bound on tuples an iterative scan visits
hnsw.scan_mem_multiplier SET 1 (x work_mem) Memory ceiling for iterative scans

Defaults are from the pgvector README. One limit worth knowing before you design a schema: HNSW indexes vector up to 2,000 dimensions, halfvec up to 4,000, and bit up to 64,000. If your embedding model outputs 3,072 dimensions, you need halfvec (or a dimension-reduced model) to index it at all.

You can check every setting's current value in one query:

SELECT name, setting FROM pg_settings WHERE name LIKE 'hnsw.%' ORDER BY 1;
           name           | setting
--------------------------+---------
 hnsw.ef_search           | 40
 hnsw.iterative_scan      | off
 hnsw.max_scan_tuples     | 20000
 hnsw.scan_mem_multiplier | 1

A reproducible recall@k measurement for pgvector HNSW

Recall@k is the fraction of the true top-k neighbours (from an exact scan) that the index returns. The script below loads 100,000 normalised 384-dimension vectors, builds a cosine HNSW index, computes ground truth with index scans disabled, and then sweeps hnsw.ef_search and the iterative scan modes.

The data is synthetic: clusters in a 32-dimensional latent space projected up to 384 dimensions, which behaves more like real embeddings than uniform noise. I tried pure Gaussian clusters in the full 384 dimensions first and got recall@10 of only 0.715 at the default ef_search, because in very high intrinsic dimension "nearest" neighbours are almost equidistant. That is a useful warning in itself: your recall depends on your data, so swap make_data for a sample of your real embeddings.

Setup, using a throwaway database:

createdb pgv_hnsw_scratch
psql -d pgv_hnsw_scratch -c "CREATE EXTENSION vector"
python3.12 -m venv .venv && .venv/bin/pip install "psycopg[binary]" numpy pgvector

I used psycopg 3.3.9, numpy 2.5.5 and pgvector-python 0.5.1.

"""Measure HNSW recall@k against exact search in pgvector.

Usage:
  python recall_at_k.py --load      # create table, load data, build index
  python recall_at_k.py             # measure only (re-run after changing settings)
"""
import argparse
import statistics
import time

import numpy as np
import psycopg
from pgvector.psycopg import register_vector


def parse_args():
    p = argparse.ArgumentParser()
    p.add_argument("--dsn", default="postgresql:///pgv_hnsw_scratch")
    p.add_argument("--rows", type=int, default=100_000)
    p.add_argument("--dim", type=int, default=384)
    p.add_argument("--queries", type=int, default=200)
    p.add_argument("--k", type=int, default=10)
    p.add_argument("--m", type=int, default=16)
    p.add_argument("--ef-construction", type=int, default=64)
    p.add_argument("--load", action="store_true", help="(re)create table and index")
    return p.parse_args()


def make_data(n, dim, rng):
    # Synthetic stand-in for real embeddings: clusters in a 32-dim latent
    # space projected to `dim` dims, plus a little noise. Swap in your own
    # vectors for numbers that mean something for your workload.
    latent = 32
    centers = rng.standard_normal((200, latent)).astype(np.float32)
    labels = rng.integers(0, 200, n)
    z = centers[labels] + 0.5 * rng.standard_normal((n, latent)).astype(np.float32)
    proj = rng.standard_normal((latent, dim)).astype(np.float32)
    x = z @ proj + 0.1 * rng.standard_normal((n, dim)).astype(np.float32)
    x /= np.linalg.norm(x, axis=1, keepdims=True)
    tenants = rng.integers(0, 10, n)  # 10 tenants, independent of content
    return x, tenants


def load(conn, args, rng):
    x, tenants = make_data(args.rows, args.dim, rng)
    conn.execute("DROP TABLE IF EXISTS items")
    conn.execute(
        f"CREATE TABLE items (id bigint PRIMARY KEY, tenant_id int NOT NULL,"
        f" embedding vector({args.dim}) NOT NULL)"
    )
    with conn.cursor().copy(
        "COPY items (id, tenant_id, embedding) FROM STDIN WITH (FORMAT BINARY)"
    ) as copy:
        copy.set_types(["int8", "int4", "vector"])
        for i, vec in enumerate(x):
            copy.write_row((i, int(tenants[i]), vec))
    conn.execute("ANALYZE items")
    conn.execute("SET maintenance_work_mem = '1GB'")
    t0 = time.perf_counter()
    conn.execute(
        f"CREATE INDEX items_embedding_hnsw ON items USING hnsw (embedding vector_cosine_ops)"
        f" WITH (m = {args.m}, ef_construction = {args.ef_construction})"
    )
    print(f"index build: {time.perf_counter() - t0:.1f}s")
    size = conn.execute(
        "SELECT pg_size_pretty(pg_relation_size('items_embedding_hnsw'))"
    ).fetchone()[0]
    print(f"index size: {size}")


def query_vectors(conn, n, rng):
    # Perturbed copies of stored rows, so queries look like the data.
    ids = rng.choice(conn.execute("SELECT count(*) FROM items").fetchone()[0], n, replace=False)
    rows = conn.execute(
        "SELECT embedding FROM items WHERE id = ANY(%s)", (ids.tolist(),)
    ).fetchall()
    q = np.array([np.asarray(r[0].to_list()) for r in rows], dtype=np.float32)
    q += 0.05 * rng.standard_normal(q.shape).astype(np.float32)
    return q


SQL = "SELECT id FROM items {where} ORDER BY embedding <=> %s LIMIT %s"


def run(conn, queries, k, where="", params=()):
    results, latencies = [], []
    for q in queries:
        t0 = time.perf_counter()
        rows = conn.execute(SQL.format(where=where), (*params, q, k)).fetchall()
        latencies.append((time.perf_counter() - t0) * 1000)
        results.append([r[0] for r in rows])
    return results, latencies


def exact(conn, queries, k, where="", params=()):
    with conn.transaction():
        conn.execute("SET LOCAL enable_indexscan = off")
        conn.execute("SET LOCAL enable_bitmapscan = off")
        return run(conn, queries, k, where, params)[0]


def recall(approx, truth, k):
    hits = sum(len(set(a) & set(t)) for a, t in zip(approx, truth))
    return hits / (k * len(truth))


def main():
    args = parse_args()
    rng = np.random.default_rng(42)
    with psycopg.connect(args.dsn, autocommit=True) as conn:
        conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
        register_vector(conn)
        if args.load:
            load(conn, args, rng)
        queries = query_vectors(conn, args.queries, rng)

        truth = exact(conn, queries, args.k)
        print(f"\nunfiltered, k={args.k}, {len(queries)} queries")
        print("ef_search  recall@k  p50_ms  p95_ms")
        for ef in (10, 20, 40, 80, 160, 320):
            conn.execute(f"SET hnsw.ef_search = {ef}")
            got, lat = run(conn, queries, args.k)
            p95 = statistics.quantiles(lat, n=20)[18]
            print(f"{ef:>9}  {recall(got, truth, args.k):8.3f}  {statistics.median(lat):6.2f}  {p95:6.2f}")

        where, params = "WHERE tenant_id = %s", (3,)
        ftruth = exact(conn, queries, args.k, where, params)
        conn.execute("SET hnsw.ef_search = 40")
        print(f"\nfiltered (tenant_id = 3, ~10% of rows), ef_search=40")
        print("iterative_scan   recall@k  avg_rows  p50_ms")
        for mode in ("off", "strict_order", "relaxed_order"):
            conn.execute(f"SET hnsw.iterative_scan = {mode}")
            got, lat = run(conn, queries, args.k, where, params)
            avg_rows = sum(len(g) for g in got) / len(got)
            print(f"{mode:<15}  {recall(got, ftruth, args.k):8.3f}  {avg_rows:8.1f}  {statistics.median(lat):6.2f}")
        conn.execute("RESET hnsw.iterative_scan")


if __name__ == "__main__":
    main()

Run it once with --load, then without it every time you change a setting. Measurement runs use a fixed seed, so the same query set is reused and the recall numbers are repeatable. Latencies are client-measured over a local socket and include Python overhead; treat them as relative, not absolute.

Tuning hnsw.ef_search: the first knob to turn

With the default build (m = 16, ef_construction = 64), the measurement run printed:

unfiltered, k=10, 200 queries
ef_search  recall@k  p50_ms  p95_ms
       10     0.950    0.44    0.71
       20     0.963    0.51    0.76
       40     0.974    0.62    0.76
       80     0.994    0.79    1.09
      160     0.999    0.89    1.20
      320     0.999    1.01    1.36

On this data the default ef_search of 40 misses about 2.6% of true neighbours, and doubling it to 80 gets recall@10 to 0.994 for roughly 0.2 ms more median latency. Past 160 there is nothing left to gain. That curve shape (fast rise, then flat) is typical; where the knee sits is what you need to measure.

Two practical rules:

  • hnsw.ef_search caps how many rows a query can return. The README notes that results are limited by the size of the candidate list. If you ask for LIMIT 100 with ef_search = 40, you will not get 100 rows. Set it at least as high as your largest LIMIT, and higher for good recall.
  • Scope it to the query, not the server. Use SET LOCAL inside the transaction so a high value for a reranking job does not slow every other query:
BEGIN;
SET LOCAL hnsw.ef_search = 100;
SELECT id FROM items ORDER BY embedding <=> $1 LIMIT 20;
COMMIT;

Choosing m and ef_construction

Build parameters cost a rebuild to change, so only touch them when raising ef_search alone does not reach your recall target at acceptable latency. Rebuilding the same table with m = 32, ef_construction = 128:

ef_search  recall@k  p50_ms  p95_ms
       10     0.985    0.53    0.90
       20     0.990    0.59    0.69
       40     0.995    0.68    0.79
       80     0.995    0.77    0.88
      160     1.000    0.84    0.96
      320     1.000    0.95    1.18

At the default ef_search of 40, recall went from 0.974 to 0.995, and the index grew from 195 MB to 202 MB. The build took 31.3 seconds versus 13.4 seconds for the default parameters (both with 1 GB of maintenance_work_mem and the default two parallel workers; build times on a laptop are noisy, but the direction is consistent). In other words, on this data m = 32 buys the same recall at ef_search = 40 that the default graph needs ef_search = 80 for.

My rule of thumb: keep the defaults unless your target is above about 0.99 recall and you are latency-bound at query time, in which case a denser graph lets you run a lower ef_search. If you are write-heavy, remember that higher m and ef_construction also slow every insert, since each new row is linked into the graph.

Speeding up pgvector HNSW index builds

Build time is where most teams first feel pain, and the fix is almost always memory. pgvector builds much faster when the whole graph fits in maintenance_work_mem. With the PostgreSQL default of 64 MB, building the same index printed:

NOTICE:  hnsw graph no longer fits into maintenance_work_mem after 29801 tuples
DETAIL:  Building will take significantly more time.
HINT:  Increase maintenance_work_mem to speed up builds.

Measured on the same 100,000-row table, default index parameters:

maintenance_work_mem max_parallel_maintenance_workers Build time
64 MB 0 2 min 44 s
1 GB 0 37.4 s
1 GB 4 12.6 s

Memory gave a 4.4x speed-up; parallel workers gave another 3x. The README's example goes further with SET max_parallel_maintenance_workers = 7; -- plus leader; for large tables you may also need to raise max_parallel_workers so the workers can actually start. Two cautions: maintenance_work_mem is allocated per operation, so do not set it server-wide to a value that would hurt if autovacuum and a build ran together; and in production, build with CREATE INDEX CONCURRENTLY to avoid blocking writes.

To watch a long build:

SELECT phase, round(100.0 * blocks_done / nullif(blocks_total, 0), 1) AS "%"
FROM pg_stat_progress_create_index;

HNSW builds report two phases, initializing and loading tuples.

Filtered search pitfalls and iterative index scans

This is the failure mode I see most in production RAG systems. With an approximate index, the WHERE clause is applied after the index returns its candidates. The README puts it precisely: if a condition matches 10% of rows, with the default hnsw.ef_search of 40, only about 4 rows will match on average. You asked for 10, you get 4, and nothing errors.

The plan makes this visible. The filter sits on top of the index scan, not inside it:

 Limit
   ->  Index Scan using items_embedding_hnsw on items
         Order By: (embedding <=> (InitPlan 1).col1)
         Filter: (tenant_id = 3)

My measurements for WHERE tenant_id = 3 (10 tenants, so about 10% of rows match), ef_search = 40:

iterative_scan   recall@k  avg_rows  p50_ms
off                 0.379       3.9    0.74
strict_order        0.971      10.0    1.06
relaxed_order       0.982      10.0    0.98

With iterative scans off, queries returned 3.9 rows on average against a LIMIT 10, almost exactly the README's prediction, and recall was 0.379. Turning on iterative scans (available since pgvector 0.8.0, released October 30, 2024) fixed both, for about 0.3 ms.

SET hnsw.iterative_scan = relaxed_order;  -- or strict_order

strict_order guarantees results come back exactly sorted by distance. relaxed_order allows slight disorder in exchange for better recall, which it delivered here. If you need exact ordering with relaxed scans, re-sort in a materialized CTE. Note the + 0, which the README says is needed on PostgreSQL 17 and later:

WITH relaxed AS MATERIALIZED (
    SELECT id, embedding <=> $1 AS distance
    FROM items
    WHERE tenant_id = 3
    ORDER BY distance
    LIMIT 10
)
SELECT * FROM relaxed ORDER BY distance + 0;

Iterative scans stop at hnsw.max_scan_tuples (20,000 by default) or when they hit the work_mem x hnsw.scan_mem_multiplier memory ceiling. For very selective filters (say 0.1% of rows) they may hit that limit and still return short. The README's advice for those cases is the right one:

  • Very selective filters: a B-tree index on the filter column, so the planner can choose an exact scan over the few matching rows instead of the HNSW index.
  • A few distinct filter values: partial HNSW indexes, one per value (CREATE INDEX ... WHERE tenant_id = 3).
  • Many distinct values: partition the table by the filter column so each partition has its own graph.

For multi-tenant RAG specifically, the partitioning-versus-shared-index decision is covered in more depth in our multi-tenant RAG frameworks guide.

halfvec and binary quantization for smaller indexes

Quantization shrinks the index, which matters when the graph no longer fits in memory. pgvector supports both through expression indexes:

-- Half precision: 2 bytes per dimension instead of 4
CREATE INDEX items_half_hnsw ON items
  USING hnsw ((embedding::halfvec(384)) halfvec_cosine_ops);

SELECT id FROM items
ORDER BY embedding::halfvec(384) <=> $1::halfvec(384)
LIMIT 10;

-- Binary: 1 bit per dimension, then re-rank with full vectors
CREATE INDEX items_bin_hnsw ON items
  USING hnsw ((binary_quantize(embedding)::bit(384)) bit_hamming_ops);

SELECT id FROM (
  SELECT id, embedding FROM items
  ORDER BY binary_quantize(embedding)::bit(384) <~> binary_quantize($1::vector)
  LIMIT 100
) candidates
ORDER BY embedding <=> $1
LIMIT 10;

The query must use the same expression as the index, or the planner will not use it. On the same 100,000 rows, at ef_search = 100:

Index Size recall@10
vector (float32) 195 MB 0.994 to 0.999 (at ef_search 80 to 160)
halfvec 112 MB 0.977
bit + re-rank top 40 33 MB 0.616
bit + re-rank top 100 33 MB 0.822

halfvec is close to a free win: 43% smaller for a small recall cost, and it is the only way to index vectors between 2,001 and 4,000 dimensions. Binary quantization at 384 dimensions loses too much information; even re-ranking 10x the candidates only reached 0.822. Binary quantization is far more effective on high-dimensional embeddings, so test it with your actual model before committing. If you are choosing an embedding model with this in mind, our embedding models guide compares dimensions and trade-offs.

Maintenance: vacuum, bloat and upgrades

HNSW indexes need care on tables with heavy updates and deletes. The README notes that vacuuming can take a while for HNSW indexes and suggests reindexing first:

REINDEX INDEX CONCURRENTLY items_embedding_hnsw;
VACUUM items;

Upgrade matters here too. The 0.8.x changelog includes fixes for HNSW vacuuming errors (0.8.4) and possible HNSW index corruption during vacuuming (0.8.3), so if you are on an earlier 0.8 release, upgrade to 0.8.7 and then run ALTER EXTENSION vector UPDATE; in each database. General table bloat affects vector tables like any other; our PostgreSQL table bloat guide covers detection and fixes.

If you are still deciding whether Postgres is the right home for your vectors at all, see LanceDB vs pgvector and pgvector vs Pinecone. Everything in this post applies once you have chosen pgvector.

Frequently Asked Questions

What is a good hnsw.ef_search value for pgvector?

Start from the default of 40, measure recall@k against exact search, and raise it until recall stops improving or latency exceeds your budget. On my test data, 80 took recall@10 from 0.974 to 0.994 for about 0.2 ms. It must also be at least your query's LIMIT.

Which pgvector version added iterative index scans?

pgvector 0.8.0, released October 30, 2024. Enable them with SET hnsw.iterative_scan = strict_order or relaxed_order. The latest release as of December 2026 is 0.8.7, from October 1, 2026.

Why does my filtered pgvector query return fewer rows than LIMIT?

HNSW applies the WHERE clause after the index scan, so a filter matching 10% of rows with ef_search = 40 returns about 4 rows. Enable iterative scans, or use a B-tree index, partial indexes or partitioning for very selective filters.

How much maintenance_work_mem does an HNSW index need?

Enough to hold the graph in memory; as a rough starting point, budget at least the size of the finished index and watch for the NOTICE pgvector prints when the graph stops fitting. On a 195 MB index, moving from 64 MB to 1 GB cut the build from 2 min 44 s to 37 s single-threaded.

Should I use halfvec or binary quantization with pgvector?

Use halfvec when you need a smaller index or more than 2,000 dimensions; recall loss is usually small. Use binary quantization only with high-dimensional embeddings and always re-rank with full-precision vectors, after measuring recall on your own data.

Should I use HNSW or IVFFlat in pgvector?

HNSW has better speed-recall trade-offs and does not need data present at build time, at the cost of slower builds and more memory. IVFFlat builds faster and uses less memory. For most RAG workloads HNSW is the default choice.

Conclusion

pgvector HNSW tuning is mostly measurement. Keep the default m and ef_construction, raise hnsw.ef_search per query until recall@k flattens, give builds enough maintenance_work_mem and parallel workers, and turn on iterative scans for every filtered query. Use halfvec when the index outgrows memory, and only trust binary quantization after you have measured it on your own embeddings. Run the script above against a sample of your real vectors before and after each change; that single habit catches more bad configurations than any rule of thumb.