pg.ddx.io pgvector/pgvector GitHub issues and pull requests
help / color / mirror / Atom feed[pgvector/pgvector] issue #1032: Planner rejects HNSW for `ORDER BY embedding <=> $q LIMIT k` with an `= ANY(...)` equality filter — estimated cost ~79x too high for a path that is 14.5x faster (PG 17.11, pgvector 0.8.6)
3+ messages / 2 participants
[nested] [flat]
* [pgvector/pgvector] issue #1032: Planner rejects HNSW for `ORDER BY embedding <=> $q LIMIT k` with an `= ANY(...)` equality filter — estimated cost ~79x too high for a path that is 14.5x faster (PG 17.11, pgvector 0.8.6)
@ 2026-09-27 21:29 "moreirawebmaster (@moreirawebmaster)" <noreply+moreirawebmaster@github.com>
0 siblings, 0 replies; 3+ messages in thread
From: moreirawebmaster (@moreirawebmaster) @ 2026-09-27 21:29 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
# Planner rejects HNSW for `ORDER BY embedding <=> $q LIMIT k` with an `= ANY(...)` equality filter — estimated cost ~79x too high for a path that is 14.5x faster (PG 17.11, pgvector 0.8.6)
## Summary
On PostgreSQL 17.11 with pgvector 0.8.6, the planner consistently rejects the HNSW
index for an ordered nearest-neighbor query of the form:
```sql
ORDER BY embedding <=> $q LIMIT $k
```
...when the query also carries an equality filter on a non-vector column
(`page_id = ANY($ids::bigint[])`, i.e. the same shape as `page_id IN (...)`) plus a
residual qual on a pgvector expression (`vector_norm(embedding) > 0`).
With fresh statistics (`ANALYZE` run immediately before capture), the planner picks a
Bitmap Heap Scan on the btree index over `page_id` plus a top-N Sort. That plan has an
estimated total cost of **800.45** and an actual execution time of **14.412 ms** — it
deserializes all 1,992 in-scope heap tuples, each carrying a 1536-dim vector, to
compute distances for the sort. The HNSW ordered Index Scan it refuses has an
estimated total cost of **63,044.08** (~79x the chosen plan) but an actual execution
time of **0.992 ms** — **14.5x faster**, with 598 buffer touches instead of 12,302.
The `hnsw.iterative_scan` GUC does **not** change the choice: it is an executor
setting, and with the planner free to choose, `relaxed_order` and `strict_order`
still pick the bitmap+sort plan (13.895 ms / 13.831 ms measured).
## Environment
- PostgreSQL 17.11 (Homebrew build, macOS, Apple Silicon)
- pgvector 0.8.6 (`SELECT extversion FROM pg_extension WHERE extname = 'vector'`)
- GUCs at capture time: `hnsw.ef_search = 40` (default), `hnsw.iterative_scan = off`
(default). The forced-HNSW EXPLAIN below ran with these same defaults.
## Minimal schema
```sql
CREATE EXTENSION vector;
CREATE TABLE chunks (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
page_id bigint NOT NULL,
embedding vector(1536)
);
-- btree on the equality filter used to scope the search
CREATE INDEX chunks_page_id_idx ON chunks (page_id);
-- ANN index, built with defaults (m = 16, ef_construction = 64)
CREATE INDEX chunks_embedding_hnsw_idx ON chunks USING hnsw (embedding vector_cosine_ops);
```
## Data shape and scale
- 15,000 rows over 1,250 distinct `page_id` values (12 rows per page).
- Random non-zero 1536-dim vectors, so `vector_norm(embedding) > 0` holds for 100% of
rows (in the captured plans the bitmap scan removed 0 rows by that filter).
- The scope predicate selects 166 of the 1,250 pages: 1,992 rows, ~13% of the table.
```sql
SELECT setseed(42);
DO $$
DECLARE
p int; s int; components text[];
BEGIN
FOR p IN 1..1250 LOOP
FOR s IN 1..12 LOOP
SELECT array_agg(round((random() * 2 - 1)::numeric, 6))
INTO components
FROM generate_series(1, 1536);
INSERT INTO chunks (page_id, embedding)
VALUES (p, ('[' || array_to_string(components, ',') || ']')::vector);
END LOOP;
END LOOP;
END $$;
ANALYZE chunks;
```
## Query shape
```sql
PREPARE q(vector, bigint[], int) AS
SELECT s.page_id,
s.embedding <=> $1
FROM chunks s
WHERE s.page_id = ANY($2)
AND s.embedding IS NOT NULL
AND vector_norm(s.embedding) > 0
ORDER BY s.embedding <=> $1
LIMIT $3;
```
`$2` holds the 166 scoped page ids, `$3 = 30`. The plan below is the custom plan of the
named statement's first execution (values known) — the same planning path a driver with
named prepared statements produces. Any subset of ~170 of the 1,250 pages reproduces
the plan choice.
## Reproduction
```sql
-- 1. Free planner
EXPLAIN (ANALYZE, BUFFERS) EXECUTE q('[...]'::vector, ARRAY[...166 ids...], 30);
-- 2. Force the HNSW path to measure its actual cost
BEGIN;
SET LOCAL enable_seqscan = off;
SET LOCAL enable_sort = off;
EXPLAIN (ANALYZE, BUFFERS) EXECUTE q('[...]'::vector, ARRAY[...166 ids...], 30);
ROLLBACK;
-- 3. Confirm iterative_scan does not change the choice
BEGIN;
SET LOCAL hnsw.iterative_scan = 'relaxed_order'; -- also try 'strict_order'
EXPLAIN (ANALYZE, BUFFERS) EXECUTE q('[...]'::vector, ARRAY[...166 ids...], 30);
ROLLBACK;
```
## Observed
| Plan | Est. total cost | Actual time | Buffers (hit+read) | Rows at LIMIT 30 |
|---|---|---|---|---|
| A. Free planner — Bitmap Heap Scan (`chunks_page_id_idx`) + top-N Sort (**chosen**) | 800.45 | **14.412 ms** | 12,302 | 30 |
| B. HNSW forced (`enable_seqscan`/`enable_sort` off) — ordered Index Scan (`chunks_embedding_hnsw_idx`) | 63,044.08 | **0.992 ms** | 598 | 12 |
| C. Free planner + `hnsw.iterative_scan = 'relaxed_order'` | 800.45 (bitmap+sort again) | 13.895 ms | 12,302 | 30 |
| D. Free planner + `hnsw.iterative_scan = 'strict_order'` | 800.45 (bitmap+sort again) | 13.831 ms | 12,302 | 30 |
The chosen plan's cost is dominated by fetching and re-checking every in-scope heap
tuple (`Bitmap Heap Scan ... rows=1992`, `Heap Blocks: exact=246`, ~12.2k buffer
hits): with 1536-dim vectors each row is ~6 KB, and all of it is read just to feed a
top-30 heapsort. The refused plan streams candidates from the HNSW graph in index
order and touches 598 buffers in total.
## Notes on the forced plan (fairness)
At the captured defaults (`ef_search = 40`, `iterative_scan = off`) the forced HNSW
scan emitted exactly 40 tuples — 12 kept, 28 removed by the post-index quals — so the
LIMIT 30 was under-filled (12 rows returned). That is the known post-filter behavior
that `hnsw.iterative_scan` exists to address, and it does not change the planning
question: even a result-complete iterative HNSW path would not approach a 63k cost on
this data, yet the planner's estimate rejects the path outright.
## Suspected mechanism
The residual qual `vector_norm(embedding) > 0` is an expression over the indexed
column for which the planner has no statistics, so it falls back to the default
inequality selectivity (1/3). On this data the predicate is true for every row, i.e.
the real selectivity is 1.0. For the ordered index scan, the planner scales the number
of tuples it must fetch from the index by the inverse of the filter selectivity, so
the unknown-selectivity qual alone inflates the planned tuples-to-fetch ~3x. The
remainder of the ~79x gap comes from the per-tuple costing of the ordered KNN scan
(each fetched tuple priced as an index+heap access), which does not match how cheaply
the scan actually streams candidates. The bitmap+sort path, by contrast, benefits from
exact btree statistics on `page_id = ANY(...)` and pays no selectivity penalty, so its
estimate is close to reality — and the planner picks the plan that reads every vector
in scope.
Two things that would help:
1. A selectivity estimate (support function or documented workaround) for quals on
pgvector built-ins such as `vector_norm(embedding) > 0`, which in deployments like
this one are degenerate-embedding guards that hold for ~all rows.
2. A review of the ordered-scan cost model when post-index quals are present — the
current combination prices a path that is 14.5x faster at 79x the cost of the
chosen one.
## Appendix — raw EXPLAIN (ANALYZE, BUFFERS) outputs
Captured on the environment above. Sanitization is limited to: table/index renames
(`chunks`, `chunks_page_id_idx`, `chunks_embedding_hnsw_idx`), the tenant uuid
rewritten to all zeros (an additional multi-tenant equality qual
`tenant_id = '...'::uuid` was present and is preserved shape-only), and the elision of
the 1536-float vector literal and the 166-integer array literal. Costs, row counts,
timings and buffer counters are verbatim.
#### A. Free planner (chosen plan) — Bitmap Heap Scan + top-N Sort
```text
Limit (cost=800.37..800.45 rows=30 width=16) (actual time=14.402..14.404 rows=30 loops=1)
Buffers: shared hit=12219 read=83
-> Sort (cost=800.37..802.03 rows=664 width=16) (actual time=14.401..14.402 rows=30 loops=1)
Sort Key: ((embedding <=> '[1536 float values elided]'::vector))
Sort Method: top-N heapsort Memory: 26kB
Buffers: shared hit=12219 read=83
-> Bitmap Heap Scan on chunks s (cost=93.28..780.76 rows=664 width=16) (actual time=0.605..14.297 rows=1992 loops=1)
Recheck Cond: (page_id = ANY ('{166 integer ids elided}'::bigint[]))
Filter: ((embedding IS NOT NULL) AND (tenant_id = '00000000-0000-0000-0000-000000000000'::uuid) AND (vector_norm(embedding) > '0'::double precision))
Heap Blocks: exact=246
Buffers: shared hit=12219 read=83
-> Bitmap Index Scan on chunks_page_id_idx (cost=0.00..92.70 rows=1992 width=0) (actual time=0.580..0.580 rows=1992 loops=1)
Index Cond: (page_id = ANY ('{166 integer ids elided}'::bigint[]))
Buffers: shared hit=46 read=58
Planning:
Buffers: shared hit=1
Planning Time: 0.201 ms
Execution Time: 14.412 ms
```
#### B. HNSW forced (SET LOCAL enable_seqscan = off, enable_sort = off)
```text
Limit (cost=2280.62..5025.96 rows=30 width=16) (actual time=0.790..0.987 rows=12 loops=1)
Buffers: shared hit=598
-> Index Scan using chunks_embedding_hnsw_idx on chunks s (cost=2280.62..63044.08 rows=664 width=16) (actual time=0.790..0.986 rows=12 loops=1)
Order By: (embedding <=> '[1536 float values elided]'::vector)
Filter: ((embedding IS NOT NULL) AND (tenant_id = '00000000-0000-0000-0000-000000000000'::uuid) AND (vector_norm(embedding) > '0'::double precision) AND (page_id = ANY ('{166 integer ids elided}'::bigint[])))
Rows Removed by Filter: 28
Buffers: shared hit=598
Planning:
Buffers: shared hit=1
Planning Time: 0.193 ms
Execution Time: 0.992 ms
```
#### C. Free planner + hnsw.iterative_scan = relaxed_order
```text
Limit (cost=800.37..800.45 rows=30 width=16) (actual time=13.885..13.888 rows=30 loops=1)
Buffers: shared hit=12302
-> Sort (cost=800.37..802.03 rows=664 width=16) (actual time=13.885..13.886 rows=30 loops=1)
Sort Key: ((embedding <=> '[1536 float values elided]'::vector))
Sort Method: top-N heapsort Memory: 26kB
Buffers: shared hit=12302
-> Bitmap Heap Scan on chunks s (cost=93.28..780.76 rows=664 width=16) (actual time=0.181..13.751 rows=1992 loops=1)
Recheck Cond: (page_id = ANY ('{166 integer ids elided}'::bigint[]))
Filter: ((embedding IS NOT NULL) AND (tenant_id = '00000000-0000-0000-0000-000000000000'::uuid) AND (vector_norm(embedding) > '0'::double precision))
Heap Blocks: exact=246
Buffers: shared hit=12302
-> Bitmap Index Scan on chunks_page_id_idx (cost=0.00..92.70 rows=1992 width=0) (actual time=0.156..0.156 rows=1992 loops=1)
Index Cond: (page_id = ANY ('{166 integer ids elided}'::bigint[]))
Buffers: shared hit=104
Planning:
Buffers: shared hit=1
Planning Time: 0.203 ms
Execution Time: 13.895 ms
```
#### D. Free planner + hnsw.iterative_scan = strict_order
```text
Limit (cost=800.37..800.45 rows=30 width=16) (actual time=13.820..13.822 rows=30 loops=1)
Buffers: shared hit=12302
-> Sort (cost=800.37..802.03 rows=664 width=16) (actual time=13.819..13.820 rows=30 loops=1)
Sort Key: ((embedding <=> '[1536 float values elided]'::vector))
Sort Method: top-N heapsort Memory: 26kB
Buffers: shared hit=12302
-> Bitmap Heap Scan on chunks s (cost=93.28..780.76 rows=664 width=16) (actual time=0.195..13.725 rows=1992 loops=1)
Recheck Cond: (page_id = ANY ('{166 integer ids elided}'::bigint[]))
Filter: ((embedding IS NOT NULL) AND (tenant_id = '00000000-0000-0000-0000-000000000000'::uuid) AND (vector_norm(embedding) > '0'::double precision))
Heap Blocks: exact=246
Buffers: shared hit=12302
-> Bitmap Index Scan on chunks_page_id_idx (cost=0.00..92.70 rows=1992 width=0) (actual time=0.170..0.170 rows=1992 loops=1)
Index Cond: (page_id = ANY ('{166 integer ids elided}'::bigint[]))
Buffers: shared hit=104
Planning:
Buffers: shared hit=1
Planning Time: 0.202 ms
Execution Time: 13.831 ms
```
^ permalink raw [nested|flat] 3+ messages in thread
* Re: [pgvector/pgvector] issue #1032: Planner rejects HNSW for `ORDER BY embedding <=> $q LIMIT k` with an `= ANY(...)` equality filter — estimated cost ~79x too high for a path that is 14.5x faster (PG 17.11, pgvector 0.8.6)
@ 2026-09-27 21:43 ` "ankane (@ankane)" <noreply+ankane@github.com>
1 sibling, 0 replies; 3+ messages in thread
From: ankane (@ankane) @ 2026-09-27 21:43 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Hi @moreirawebmaster, I don't think there's anything for pgvector to do here. The planner won't have statistics for `vector_norm(embedding) > 0` and there are existing ways to get the planner to use the index.
^ permalink raw [nested|flat] 3+ messages in thread
* Re: [pgvector/pgvector] issue #1032: Planner rejects HNSW for `ORDER BY embedding <=> $q LIMIT k` with an `= ANY(...)` equality filter — estimated cost ~79x too high for a path that is 14.5x faster (PG 17.11, pgvector 0.8.6)
@ 2026-09-27 21:43 ` "ankane (@ankane)" <noreply+ankane@github.com>
1 sibling, 0 replies; 3+ messages in thread
From: ankane (@ankane) @ 2026-09-27 21:43 UTC (permalink / raw)
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
@ankane closed this.
^ permalink raw [nested|flat] 3+ messages in thread
end of thread, other threads:[~2026-09-27 21:43 UTC | newest]
Thread overview: 3+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-09-27 21:29 [pgvector/pgvector] issue #1032: Planner rejects HNSW for `ORDER BY embedding <=> $q LIMIT k` with an `= ANY(...)` equality filter — estimated cost ~79x too high for a path that is 14.5x faster (PG 17.11, pgvector 0.8.6) "moreirawebmaster (@moreirawebmaster)" <noreply+moreirawebmaster@github.com>
2026-09-27 21:43 ` "ankane (@ankane)" <noreply+ankane@github.com>
2026-09-27 21:43 ` "ankane (@ankane)" <noreply+ankane@github.com>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox