pg.ddx.io  pgvector/pgvector GitHub issues and pull requests  
help / color / mirror / Atom feed
[pgvector/pgvector] PR #1031: Remove approximate indexes for ORDER BY queries without a LIMIT
3+ messages / 2 participants
[nested] [flat]

* [pgvector/pgvector] PR #1031: Remove approximate indexes for ORDER BY queries without a LIMIT
@ 2026-09-21 11:35 "oliness (@oliness)" <noreply+oliness@github.com>
  0 siblings, 0 replies; 3+ messages in thread

From: oliness (@oliness) @ 2026-09-21 11:35 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

An HNSW or IVFFlat scan stops after ef_search rows (or the probed lists), so the planner shouldn't pick one for a query that needs every row.

inline patch 1: CHANGELOG.md, src/hnsw.c, src/ivfflat.c and 2 more (+233/-4 lines) download inline-1.patchdiff --git a/CHANGELOG.md b/CHANGELOG.md index d4121a5b5..428054769 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ ## 0.8.7 (unreleased) - Fixed error with `avg` aggregate when no matching rows +- Fixed HNSW and IVFFlat indexes being used for queries without `LIMIT` - [more info](https://github.com/pgvector/pgvector/issues/846) ## 0.8.6 (2026-07-29) diff --git a/src/hnsw.c b/src/hnsw.c index a3f582299..a512ee269 100644 --- a/src/hnsw.c +++ b/src/hnsw.c @@ -13,6 +13,7 @@ #include "hnsw.h" #include "miscadmin.h" #include "nodes/pg_list.h" +#include "optimizer/cost.h" #include "storage/lwlock.h" #include "utils/float.h" #include "utils/guc.h" @@ -144,8 +145,12 @@ hnswcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, double spc_seq_page_cost; Relation index; - /* Never use index without order */ - if (path->indexorderbys == NIL) + /* + * Never use index without order, or when all tuples are needed and seq + * scans are enabled, since scans return a limited number of tuples + */ + if (path->indexorderbys == NIL || + (root->tuple_fraction <= 0 && enable_seqscan)) { *indexStartupCost = get_float8_infinity(); *indexTotalCost = get_float8_infinity(); diff --git a/src/ivfflat.c b/src/ivfflat.c index 8489d936b..435b7705f 100644 --- a/src/ivfflat.c +++ b/src/ivfflat.c @@ -10,6 +10,7 @@ #include "fmgr.h" #include "ivfflat.h" #include "nodes/pg_list.h" +#include "optimizer/cost.h" #include "utils/float.h" #include "utils/guc.h" #include "utils/relcache.h" @@ -96,8 +97,12 @@ ivfflatcostestimate(PlannerInfo *root, IndexPath *path, double loop_count, double spc_seq_page_cost; Relation index; - /* Never use index without order */ - if (path->indexorderbys == NIL) + /* + * Never use index without order, or when all tuples are needed and seq + * scans are enabled, since scans return a limited number of tuples + */ + if (path->indexorderbys == NIL || + (root->tuple_fraction <= 0 && enable_seqscan)) { *indexStartupCost = get_float8_infinity(); *indexTotalCost = get_float8_infinity(); diff --git a/test/t/049_hnsw_no_limit.pl b/test/t/049_hnsw_no_limit.pl new file mode 100644 index 000000000..48ee55e73 --- /dev/null +++ b/test/t/049_hnsw_no_limit.pl @@ -0,0 +1,109 @@ +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +# Scans return a limited number of tuples, so the index should not be used +# when the planner expects every row to be fetched (tuple_fraction = 0) +# https://github.com/pgvector/pgvector/issues/846 + +my $dim = 3; +my $limit = 10; + +my $array_sql = join(",", ('random()') x $dim); + +# Initialize node +my $node = PostgreSQL::Test::Cluster->new('node'); +$node->init; +$node->start; + +# Create tables and index +$node->safe_psql("postgres", "CREATE EXTENSION vector;"); +$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector($dim), c int4);"); +$node->safe_psql("postgres", "CREATE TABLE cat (i int4 PRIMARY KEY, t text);"); +$node->safe_psql("postgres", + "INSERT INTO tst SELECT i, ARRAY[$array_sql], i % 10 FROM generate_series(1, 10000) i;" +); +$node->safe_psql("postgres", "INSERT INTO cat SELECT i, 'cat ' || i FROM generate_series(0, 9) i;"); +$node->safe_psql("postgres", "CREATE INDEX idx ON tst USING hnsw (v vector_l2_ops);"); +$node->safe_psql("postgres", "ANALYZE;"); + +# Generate query +my @r = (); +for (1 .. $dim) +{ + push(@r, rand()); +} +my $query = "[" . join(",", @r) . "]"; +my $dist = "v <-> '$query'"; + +# Disable sorts so the index is used whenever it is allowed +my $settings = "SET enable_sort = off;"; + +sub sorted +{ + my ($res) = @_; + return join("\n", sort { $a cmp $b } split("\n", $res)); +} + +# Check the index is not used and all rows are returned +sub test_no_index +{ + my ($name, $sql) = @_; + + my $explain = $node->safe_psql("postgres", "$settings EXPLAIN $sql;"); + unlike($explain, qr/Index Scan using idx/, "$name: no index scan"); + + my $expected = $node->safe_psql("postgres", "SET enable_indexscan = off; $sql;"); + my $actual = $node->safe_psql("postgres", "$settings $sql;"); + is(sorted($actual), sorted($expected), "$name: all rows"); +} + +# Check the index is used +sub test_index +{ + my ($name, $sql, $extra_settings) = @_; + $extra_settings //= ""; + + my $explain = $node->safe_psql("postgres", "$settings $extra_settings EXPLAIN $sql;"); + like($explain, qr/Index Scan using idx/, "$name: index scan"); +} + +# Test without limit +test_no_index("no limit", "SELECT i FROM tst ORDER BY $dist"); + +# Test subqueries without limit, which get tuple_fraction = 0 when the outer +# query has an aggregate, GROUP BY, HAVING, DISTINCT, ORDER BY, or join +test_no_index("aggregate", "SELECT COUNT(*) FROM (SELECT i FROM tst ORDER BY $dist) s"); +test_no_index("group by", "SELECT c, COUNT(*) FROM (SELECT c FROM tst ORDER BY $dist) s GROUP BY c"); +test_no_index("grouping sets", + "SELECT c, COUNT(*) FROM (SELECT c FROM tst ORDER BY $dist) s GROUP BY ROLLUP (c)"); +test_no_index("having", "SELECT COUNT(*) FROM (SELECT i FROM tst ORDER BY $dist) s HAVING COUNT(*) > 0"); +test_no_index("distinct", "SELECT DISTINCT c FROM (SELECT c FROM tst ORDER BY $dist) s"); +test_no_index("order by", "SELECT i FROM (SELECT i FROM tst ORDER BY $dist) s ORDER BY i LIMIT $limit"); +test_no_index("join", + "SELECT s.i, cat.t FROM (SELECT i, c FROM tst ORDER BY $dist) s INNER JOIN cat ON cat.i = s.c"); + +# Test subqueries without limit when the outer query only reads the first rows +test_no_index("order by distance", + "SELECT i FROM (SELECT i, $dist AS d FROM tst ORDER BY d) s ORDER BY d LIMIT $limit"); +test_no_index("join order by distance", + "SELECT s.i, cat.t FROM (SELECT i, c, $dist AS d FROM tst ORDER BY d) s INNER JOIN cat ON cat.i = s.c ORDER BY s.d LIMIT $limit" +); + +# Test queries that still use the index +test_index("limit", "SELECT i FROM tst ORDER BY $dist LIMIT $limit"); +test_index("outer limit", "SELECT i FROM (SELECT i FROM tst ORDER BY $dist) s LIMIT $limit"); +test_index("aggregate with limit", "SELECT COUNT(*) FROM (SELECT i FROM tst ORDER BY $dist LIMIT $limit) s"); +test_index("order by distance with limit", + "SELECT i FROM (SELECT i, $dist AS d FROM tst ORDER BY d LIMIT $limit) s ORDER BY d"); +test_index("join with limit", + "SELECT s.i, cat.t FROM (SELECT i, c, $dist AS d FROM tst ORDER BY d LIMIT $limit) s INNER JOIN cat ON cat.i = s.c ORDER BY s.d" +); +test_index("no limit with enable_seqscan off", "SELECT i FROM tst ORDER BY $dist", "SET enable_seqscan = off;"); +test_index("subquery with enable_seqscan off", + "SELECT i FROM (SELECT i, $dist AS d FROM tst ORDER BY d) s ORDER BY d LIMIT $limit", + "SET enable_seqscan = off;"); + +done_testing(); diff --git a/test/t/050_ivfflat_no_limit.pl b/test/t/050_ivfflat_no_limit.pl new file mode 100644 index 000000000..ca90f5df9 --- /dev/null +++ b/test/t/050_ivfflat_no_limit.pl @@ -0,0 +1,109 @@ +use strict; +use warnings FATAL => 'all'; +use PostgreSQL::Test::Cluster; +use PostgreSQL::Test::Utils; +use Test::More; + +# Scans return a limited number of tuples, so the index should not be used +# when the planner expects every row to be fetched (tuple_fraction = 0) +# https://github.com/pgvector/pgvector/issues/846 + +my $dim = 3; +my $limit = 10; + +my $array_sql = join(",", ('random()') x $dim); + +# Initialize node +my $node = PostgreSQL::Test::Cluster->new('node'); +$node->init; +$node->start; + +# Create tables and index +$node->safe_psql("postgres", "CREATE EXTENSION vector;"); +$node->safe_psql("postgres", "CREATE TABLE tst (i int4, v vector($dim), c int4);"); +$node->safe_psql("postgres", "CREATE TABLE cat (i int4 PRIMARY KEY, t text);"); +$node->safe_psql("postgres", + "INSERT INTO tst SELECT i, ARRAY[$array_sql], i % 10 FROM generate_series(1, 10000) i;" +); +$node->safe_psql("postgres", "INSERT INTO cat SELECT i, 'cat ' || i FROM generate_series(0, 9) i;"); +$node->safe_psql("postgres", "CREATE INDEX idx ON tst USING ivfflat (v vector_l2_ops) WITH (lists = 100);"); +$node->safe_psql("postgres", "ANALYZE;"); + +# Generate query +my @r = (); +for (1 .. $dim) +{ + push(@r, rand()); +} +my $query = "[" . join(",", @r) . "]"; +my $dist = "v <-> '$query'"; + +# Disable sorts so the index is used whenever it is allowed +my $settings = "SET enable_sort = off;"; + +sub sorted +{ + my ($res) = @_; + return join("\n", sort { $a cmp $b } split("\n", $res)); +} + +# Check the index is not used and all rows are returned +sub test_no_index +{ + my ($name, $sql) = @_; + + my $explain = $node->safe_psql("postgres", "$settings EXPLAIN $sql;"); + unlike($explain, qr/Index Scan using idx/, "$name: no index scan"); + + my $expected = $node->safe_psql("postgres", "SET enable_indexscan = off; $sql;"); + my $actual = $node->safe_psql("postgres", "$settings $sql;"); + is(sorted($actual), sorted($expected), "$name: all rows"); +} + +# Check the index is used +sub test_index +{ + my ($name, $sql, $extra_settings) = @_; + $extra_settings //= ""; + + my $explain = $node->safe_psql("postgres", "$settings $extra_settings EXPLAIN $sql;"); + like($explain, qr/Index Scan using idx/, "$name: index scan"); +} + +# Test without limit +test_no_index("no limit", "SELECT i FROM tst ORDER BY $dist"); + +# Test subqueries without limit, which get tuple_fraction = 0 when the outer +# query has an aggregate, GROUP BY, HAVING, DISTINCT, ORDER BY, or join +test_no_index("aggregate", "SELECT COUNT(*) FROM (SELECT i FROM tst ORDER BY $dist) s"); +test_no_index("group by", "SELECT c, COUNT(*) FROM (SELECT c FROM tst ORDER BY $dist) s GROUP BY c"); +test_no_index("grouping sets", + "SELECT c, COUNT(*) FROM (SELECT c FROM tst ORDER BY $dist) s GROUP BY ROLLUP (c)"); +test_no_index("having", "SELECT COUNT(*) FROM (SELECT i FROM tst ORDER BY $dist) s HAVING COUNT(*) > 0"); +test_no_index("distinct", "SELECT DISTINCT c FROM (SELECT c FROM tst ORDER BY $dist) s"); +test_no_index("order by", "SELECT i FROM (SELECT i FROM tst ORDER BY $dist) s ORDER BY i LIMIT $limit"); +test_no_index("join", + "SELECT s.i, cat.t FROM (SELECT i, c FROM tst ORDER BY $dist) s INNER JOIN cat ON cat.i = s.c"); + +# Test subqueries without limit when the outer query only reads the first rows +test_no_index("order by distance", + "SELECT i FROM (SELECT i, $dist AS d FROM tst ORDER BY d) s ORDER BY d LIMIT $limit"); +test_no_index("join order by distance", + "SELECT s.i, cat.t FROM (SELECT i, c, $dist AS d FROM tst ORDER BY d) s INNER JOIN cat ON cat.i = s.c ORDER BY s.d LIMIT $limit" +); + +# Test queries that still use the index +test_index("limit", "SELECT i FROM tst ORDER BY $dist LIMIT $limit"); +test_index("outer limit", "SELECT i FROM (SELECT i FROM tst ORDER BY $dist) s LIMIT $limit"); +test_index("aggregate with limit", "SELECT COUNT(*) FROM (SELECT i FROM tst ORDER BY $dist LIMIT $limit) s"); +test_index("order by distance with limit", + "SELECT i FROM (SELECT i, $dist AS d FROM tst ORDER BY d LIMIT $limit) s ORDER BY d"); +test_index("join with limit", + "SELECT s.i, cat.t FROM (SELECT i, c, $dist AS d FROM tst ORDER BY d LIMIT $limit) s INNER JOIN cat ON cat.i = s.c ORDER BY s.d" +); +test_index("no limit with enable_seqscan off", "SELECT i FROM tst ORDER BY $dist", "SET enable_seqscan = off;"); +test_index("subquery with enable_seqscan off", + "SELECT i FROM (SELECT i, $dist AS d FROM tst ORDER BY d) s ORDER BY d LIMIT $limit", + "SET enable_seqscan = off;"); + +done_testing();
^ permalink raw [nested|flat] 3+ messages in thread

* Re: [pgvector/pgvector] PR #1031: Remove approximate indexes for ORDER BY queries without a LIMIT
@ 2026-09-23 18:28 ` "ankane (@ankane)" <noreply+ankane@github.com>
  1 sibling, 0 replies; 3+ messages in thread

From: ankane (@ankane) @ 2026-09-23 18:28 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Hi @oliness, thanks for the PR.

This seems to work well for some queries I've tested (better than `limit_tuples` in #424), but I'm worried it's more risky / brittle / could break other queries. For instance, `tuple_fraction` is set to zero in a [number of situations](https://github.com/postgres/postgres/blob/REL_18_6/src/backend/optimizer/path/allpaths.c#L2666-L2671).

@jkatz @hlinnaka any thoughts?

^ permalink  raw  [nested|flat] 3+ messages in thread

* Re: [pgvector/pgvector] PR #1031: Remove approximate indexes for ORDER BY queries without a LIMIT
@ 2026-09-23 19:42 ` "oliness (@oliness)" <noreply+oliness@github.com>
  1 sibling, 0 replies; 3+ messages in thread

From: oliness (@oliness) @ 2026-09-23 19:42 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I've added TAP tests for the `tuple_fraction = 0` case: `test/t/049_hnsw_no_limit.pl` and `test/t/050_ivfflat_no_limit.pl`, one per index type. They run with `enable_sort = off`, so the index is chosen whenever it's allowed.

For queries planned with `tuple_fraction = 0`, they check that the index isn't used and that the results match a scan with `enable_indexscan = off`:

- no `LIMIT`
- a subquery without its own `LIMIT`, under an outer aggregate, `GROUP BY`, `ROLLUP`, `HAVING`, `DISTINCT`, `ORDER BY` on another column, or join
- the same kind of subquery when the outer query only reads the first rows: an outer `ORDER BY` on the same distance with a `LIMIT`, or a join ordered by distance with a `LIMIT`

They also check that these queries still use the index:

- a `LIMIT`
- an outer `LIMIT` with nothing else in the outer query
- a subquery with its own `LIMIT`, under an aggregate, `ORDER BY`, or join
- no `LIMIT` with `enable_seqscan = off`, at the top level and in a subquery

On master, 17 of the 27 checks in each file fail, including every "no index scan" check. The checks for queries that should still use the index pass on master too.


^ permalink  raw  [nested|flat] 3+ messages in thread


end of thread, other threads:[~2026-09-23 19:42 UTC | newest]

Thread overview: 3+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-09-21 11:35 [pgvector/pgvector] PR #1031: Remove approximate indexes for ORDER BY queries without a LIMIT "oliness (@oliness)" <noreply+oliness@github.com>
2026-09-23 18:28 ` "ankane (@ankane)" <noreply+ankane@github.com>
2026-09-23 19:42 ` "oliness (@oliness)" <noreply+oliness@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