From: redphosphorus7562 (@redphosphorus7562) <noreply+redphosphorus7562@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: Re: [pgvector/pgvector] issue #862: Inconsistent behavior with relaxed_order: planner assumes strict ordering from HNSW index
Date: Mon, 23 Jun 2025 05:55:08 +0000
Message-ID: <gh-pgvector-pgvector-862-c2995026185@github.com> (raw)
In-Reply-To: <gh-pgvector-pgvector-862@github.com>
References: <gh-pgvector-pgvector-862@github.com>
Also, I have another question about relaxed_order. @ankane
<img width="848" alt="Image" src="https://github.com/user-attachments/assets/10296032-5c12-4640-9e9a-c5500bf46bfb"; />
As shown in the image above,the documentation states that using a CTE will ensure strict ordering, but I’m curious how that’s actually achieved — because from the plan, it doesn’t appear to do any explicit sorting (in PG17). In some older versions of PostgreSQL (e.g., 13), there _is_ an explicit sort.
```sql
EXPLAIN WITH a AS MATERIALIZED (
SELECT embedding <=> '[3,1,2]' AS distance
FROM items
ORDER BY embedding <=> '[3,1,2]'
LIMIT 40
)
SELECT * FROM a ORDER BY distance;
```
**In PG17 ,I get the following plan:**
```
QUERY PLAN
-------------------------------------------------------------------------------------------
CTE Scan on a (cost=103.57..104.37 rows=40 width=8)
CTE a
-> Limit (cost=95.53..103.57 rows=40 width=8)
-> Index Scan using items_embedding_idx on items (cost=95.53..4112.00 rows=20000 width=8)
Order By: (embedding <=> '[3,1,2]'::vector)
(5 rows)
```
**In PG13:**
```
QUERY PLAN
-------------------------------------------------------------------------------------------------------
Sort (cost=105.31..105.41 rows=40 width=8)
Sort Key: a.distance
CTE a
-> Limit (cost=95.42..103.44 rows=40 width=8)
-> Index Scan using items_embedding_idx on items (cost=95.42..4108.00 rows=20000 width=8)
Order By: (embedding <=> '[3,1,2]'::vector)
-> CTE Scan on a (cost=0.00..0.80 rows=40 width=8)
(7 rows)
```