From: KilianU (@KilianU) <noreply+KilianU@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] issue #702: Index not used when using a WITH expression
Date: Mon, 28 Oct 2024 11:32:55 +0000
Message-ID: <gh-pgvector-pgvector-702@github.com> (raw)
Hi,
I want to report an issue that created a lot of confusion for me.
The following query works as expected: (just to demonstrate, that setup the DB, tables and index correctly)
`EXPLAIN SELECT * FROM incident_embedding ORDER BY embedding <=> '[...]' LIMIT 5;`
Outputs:
```
Limit (cost=388.72..388.95 rows=5 width=42)
-> Index Scan using incident_embedding_embedding_idx on incident_embedding (cost=388.72..8044.22 rows=167000 width=42)
" Order By: (embedding <=> '[...]'::vector)"
```
However, doing something like this, wont use the index:
```SQL
EXPLAIN WITH v AS (SELECT embedding as vec FROM incident_embedding WHERE incident_id = 2491825880941960244)
SELECT *, embedding <=> v.vec as distance FROM incident_embedding, v ORDER BY embedding <=> v.vec LIMIT 5;
```
Outputs:
```
Limit (cost=10229.19..10229.76 rows=5 width=60)
-> Gather Merge (cost=10229.19..21526.21 rows=98235 width=60)
Workers Planned: 1
-> Sort (cost=9229.18..9474.76 rows=98235 width=60)
Sort Key: ((incident_embedding.embedding <=> incident_embedding_1.embedding))
-> Nested Loop (cost=0.00..7597.53 rows=98235 width=60)
-> Parallel Seq Scan on incident_embedding incident_embedding_1 (cost=0.00..2619.94 rows=1 width=18)
Filter: (incident_id = '2491825880941960244'::bigint)
-> Seq Scan on incident_embedding (cost=0.00..3062.00 rows=167000 width=34)
```
**Expected outcome**: query engine should use the index.
### Background on how I stumbled over this issue
I wanted to do some benchmarking and wrote this query, to get some numbers on how long querying takes.
```plpgsql
EXPLAIN WITH v AS (SELECT CAST (random_float_array(1536) AS vector(1536)) as vec)
SELECT *, embedding <=> v.vec as distance FROM incident_embedding, v ORDER BY embedding::vector(1536) <=> v.vec LIMIT 5;
```
**Outcome**: index is not used in this case as well.
Here is the definition of `random_float_array`:
```plpgsql
CREATE OR REPLACE FUNCTION random_float_array(dim integer) RETURNS float[] AS $BODY$
begin
return (select array_agg(random()) from generate_series (0, dim -1));
end
$BODY$ LANGUAGE plpgsql;
```
This issue doesn't create any real world impact for me, since I did that for benchmarking only. However, I would be still curious on why the engine doesn't use the index in these cases.