From: lll-lll-lll-lll (@lll-lll-lll-lll) <noreply+lll-lll-lll-lll@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] issue #771: HNSW Index Not Utilized in pgvector 0.7.4
Date: Mon, 03 Feb 2025 09:51:49 +0000
Message-ID: <gh-pgvector-pgvector-771@github.com> (raw)
## Version
- pgvector 0.7.4
- HNSW index
- `hnsw.ef_search = 200`
- `hnsw.iterative_scan = 'strict_order'`
- `m = 16`
- `ef_construction = 64`
- Dimension: 2000 embeddings vector(2000) NOT NULL,
- Create index query:
- executed analyze items;
```sql
CREATE INDEX items_hnsw_idx ON items USING hnsw (embedding vector_cosine_ops);
```
## Issues Being Faced
I executed the following sample queries, but confirmed that the HNSW index is not being utilized.
```sql
-- Experiment query to check if the index is executed
EXPLAIN (ANALYZE, COSTS, VERBOSE, BUFFERS)
WITH random_vector AS (
SELECT ('[' || array_to_string(array_agg(random()), ',') || ']')::vector(2000) AS vec
FROM generate_series(1, 2000)
)
SELECT *
FROM items
ORDER BY embedding <=> (SELECT vec FROM random_vector)
LIMIT 10;
```
explain result
```sql
Limit (cost=100.49..100.61 rows=50 width=42) (actual time=19.322..19.335 rows=50 loops=1)
Output: itemsitems.embedding, items ((items.embedding <=> $1))
Buffers: shared hit=5211
CTE random_vector
-> Aggregate (cost=30.01..30.03 rows=1 width=32) (actual time=2.511..2.512 rows=1 loops=1)
Output: ((('['::text || array_to_string(array_agg(random()), ','::text)) || ']'::text))::vector(2000)
-> Function Scan on pg_catalog.generate_series (cost=0.00..20.00 rows=2000 width=0) (actual time=0.146..0.277 rows=2000 loops=1)
Output: generate_series.generate_series
Function Call: generate_series(1, 2000)
InitPlan 2 (returns $1)
-> CTE Scan on random_vector (cost=0.00..0.02 rows=1 width=32) (actual time=2.517..2.518 rows=1 loops=1)
Output: random_vector.vec
-> Sort (cost=70.44..73.69 rows=1300 width=42) (actual time=19.320..19.326 rows=50 loops=1)
Output: itemsitems.embedding, items ((items.embedding <=> $1))
Sort Key: ((items.embedding <=> $1))
Sort Method: top-N heapsort Memory: 31kB
Buffers: shared hit=5211
-> Seq Scan on public.items (cost=0.00..27.25 rows=1300 width=42) (actual time=2.599..18.854 rows=1300 loops=1)
Output: itemsitems.embedding, items (items.embedding <=> $1)
Buffers: shared hit=5211
Query Identifier: 2862890634848388890
Planning:
Buffers: shared hit=1
Planning Time: 0.134 ms
Execution Time: 19.437 ms
```
## Question
- When dealing with high-dimensional vectors, what methods can be used to test whether the index is being effectively utilized?
I have verified that the index is being used by monitoring the server and checking `pg_stat_user_indexes`, but I have already confirmed that the number of results is not increasing. why
below executed query
```sql
SELECT
embedding <=> '[vector]' AS cosine_distance
FROM
items
WHERE
(id != 'id')c
ORDER BY cosine_distance ASC
LIMIT 10;
```