pg.ddx.io  pgvector/pgvector GitHub issues and pull requests  
help / color / mirror / Atom feed
[pgvector/pgvector] issue #721: HNSW index bypassed when LIMIT or filter selectivity exceeds threshold
6+ messages / 2 participants
[nested] [flat]

* [pgvector/pgvector] issue #721: HNSW index bypassed when LIMIT or filter selectivity exceeds threshold
@ 2024-11-28 09:31 "rsomani95 (@rsomani95)" <noreply+rsomani95@github.com>
  0 siblings, 0 replies; 6+ messages in thread

From: rsomani95 (@rsomani95) @ 2024-11-28 09:31 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I've got a query that only uses the HNSW index sometimes, and the query planner chooses not to use the index in two conditions per my observations:
1. Size of the `LIMIT` is too high
2. Values of the filters in the `WHERE` clause return a larger number of values 

Here's some context of my setup:
- I've got 3 tables -- _tag_, _taggeditem_ and _segment_
- I'm trying to filter on two columns on the _tag_ tabled named `category` and `name`. I have btree indexes on both these columns
- My HNSW index is built like so:
```sql
CREATE INDEX s_embedding_idx_shot ON segment USING hnsw (embedding halfvec_cosine_ops) WITH (m='32', ef_construction='128') WHERE ((category)::text = 'Shot'::text)
```

---

Here's how I'm doing my tag + vector search
```sql
BEGIN;

SET LOCAL hnsw.ef_search = 200;
SET LOCAL hnsw.iterative_scan = 'strict_order';
SET LOCAL hnsw.max_scan_tuples = 20000;
SET LOCAL hnsw.scan_mem_multiplier = 2;

-- EXPLAIN (ANALYZE, COSTS, VERBOSE, BUFFERS)
SELECT "segment"."id"
  FROM "segment"
 INNER JOIN "taggeditem"
    ON ("segment"."id" = "taggeditem"."object_id")
 INNER JOIN "tag"
    ON ("taggeditem"."tag_id" = "tag"."id")
 WHERE (
   -- Tag filters
   "tag"."category" = 'Cinematography'
   AND "tag"."name" = 'Wide Framing'
   -- Vector filter
   AND "segment"."category" IN ('Shot')
   AND ("segment"."embedding" <=> '[vector]') < 0.9)
 ORDER BY ("segment"."embedding" <=> '[vector]')
 LIMIT 100;
COMMIT;
```

### With `LIMIT 100`, the vector index is **not** used.

<details>
<summary>
Click to expand query plan
</summary>

```sql
Limit  (cost=498348.89..498360.39 rows=100 width=24) (actual time=3419.236..3419.356 rows=100 loops=1)
   Output: segment.id, ((segment.embedding <=> '[vector]'::halfvec))
   Buffers: shared hit=2237943
   ->  Gather Merge  (cost=498348.89..498435.60 rows=754 width=24) (actual time=3419.234..3419.344 rows=100 loops=1)
         Output: segment.id, ((segment.embedding <=> '[vector]'::halfvec))
         Workers Planned: 1
         Workers Launched: 1
         Buffers: shared hit=2237943
         ->  Sort  (cost=497348.88..497350.76 rows=754 width=24) (actual time=1795.739..1795.749 rows=94 loops=2)
               Output: segment.id, ((segment.embedding <=> '[vector]'::halfvec))
               Sort Key: ((segment.embedding <=> '[vector]'::halfvec))
               Sort Method: top-N heapsort  Memory: 36kB
               Buffers: shared hit=2237943
               Worker 0:  actual time=172.889..172.902 rows=100 loops=1
                 Sort Method: top-N heapsort  Memory: 37kB
                 Buffers: shared hit=193058
               ->  Nested Loop  (cost=358.73..497320.06 rows=754 width=24) (actual time=1.777..1790.919 rows=23430 loops=2)
                     Output: segment.id, (segment.embedding <=> '[vector]'::halfvec)
                     Inner Unique: true
                     Buffers: shared hit=2237934
                     Worker 0:  actual time=3.068..172.053 rows=3588 loops=1
                       Buffers: shared hit=193049
                     ->  Nested Loop  (cost=358.30..437800.76 rows=12886 width=16) (actual time=1.659..1048.770 rows=206741 loops=2)
                           Output: taggeditem.object_id
                           Buffers: shared hit=248641
                           Worker 0:  actual time=3.010..47.407 rows=34006 loops=1
                             Buffers: shared hit=31444
                           ->  Parallel Index Scan using tag_pkey on public.tag  (cost=0.29..10892.86 rows=4 width=16) (actual time=0.039..3.625 rows=3 loops=2)
                                 Output: tag.id
                                 Filter: (((tag.category)::text = 'Cinematography'::text) AND ((tag.name)::text = 'Wide Framing'::text))
                                 Rows Removed by Filter: 11114
                                 Buffers: shared hit=11064
                                 Worker 0:  actual time=0.057..7.125 rows=4 loops=1
                                   Buffers: shared hit=11025
                           ->  Bitmap Heap Scan on public.taggeditem  (cost=358.02..106405.11 rows=32187 width=32) (actual time=9.023..339.374 rows=68914 loops=6)
                                 Output: taggeditem.created, taggeditem.modified, taggeditem.id, taggeditem.object_id, taggeditem.confidence, taggeditem.tag_type, taggeditem.content_type_id, taggeditem.owner_id, taggeditem.tag_id
                                 Recheck Cond: (taggeditem.tag_id = tag.id)
                                 Rows Removed by Index Recheck: 1764739
                                 Heap Blocks: exact=49462 lossy=167390
                                 Buffers: shared hit=237577
                                 Worker 0:  actual time=1.419..8.711 rows=8502 loops=4
                                   Buffers: shared hit=20419
                                 ->  Bitmap Index Scan on taggeditem_tag_id_9037c8bd  (cost=0.00..349.97 rows=32187 width=0) (actual time=6.939..6.939 rows=68914 loops=6)
                                       Index Cond: (taggeditem.tag_id = tag.id)
                                       Buffers: shared hit=348
                                       Worker 0:  actual time=0.742..0.742 rows=8502 loops=4
                                         Buffers: shared hit=42
                     ->  Index Scan using segment_pkey on public.segment  (cost=0.43..4.62 rows=1 width=835) (actual time=0.003..0.003 rows=0 loops=413482)
                           Output: segment.id, segment.embedding
                           Index Cond: (segment.id = taggeditem.object_id)
                           Filter: (((segment.category)::text = 'Shot'::text) AND ((segment.embedding <=> '[vector]'::halfvec) < '0.9'::double precision))
                           Rows Removed by Filter: 1
                           Buffers: shared hit=1873169
                           Worker 0:  actual time=0.003..0.003 rows=0 loops=34006
                             Buffers: shared hit=153353
 Query Identifier: -3296060046874035074
 Planning:
   Buffers: shared hit=35
 Planning Time: 3.294 ms
 Execution Time: 3420.343 ms
```

</details>

[Query Plan Visualisation](https://explain.dalibo.com/plan/0e569633acb4e5h5)

<br>

### With `LIMIT 50`, the vector index **is** used.

<details>
<summary>
Click to expand query plan
</summary>

```
Limit  (cost=2898.19..479096.12 rows=50 width=24) (actual time=3.194..64.412 rows=50 loops=1)
Output: segment.id, ((segment.embedding <=> '[vector]'::halfvec))
Buffers: shared hit=34479
->  Nested Loop  (cost=2898.19..12212613.14 rows=1282 width=24) (actual time=3.193..64.399 rows=50 loops=1)
      Output: segment.id, (segment.embedding <=> '[vector]'::halfvec)
      Inner Unique: true
      Buffers: shared hit=34479
      ->  Nested Loop  (cost=2897.89..12082779.67 rows=4749735 width=851) (actual time=0.947..45.374 rows=30087 loops=1)
            Output: segment.id, segment.embedding, taggeditem.tag_id
            Buffers: shared hit=24850
            ->  Index Scan using s_embedding_idx_shot on public.segment  (cost=2897.32..2187653.01 rows=198711 width=835) (actual time=0.927..19.427 rows=2649 loops=1)
                  Output: segment.id, segment.embedding
                  Order By: (segment.embedding <=> '[vector]'::halfvec)
                  Filter: ((segment.embedding <=> '[vector]'::halfvec) < '0.9'::double precision)
                  Buffers: shared hit=11165
            ->  Index Scan using taggeditem_object_id_c44701f4 on public.taggeditem  (cost=0.57..42.69 rows=711 width=32) (actual time=0.005..0.007 rows=11 loops=2649)
                  Output: taggeditem.created, taggeditem.modified, taggeditem.id, taggeditem.object_id, taggeditem.confidence, taggeditem.tag_type, taggeditem.content_type_id, taggeditem.owner_id, taggeditem.tag_id
                  Index Cond: (taggeditem.object_id = segment.id)
                  Buffers: shared hit=13685
      ->  Memoize  (cost=0.30..4.41 rows=1 width=16) (actual time=0.000..0.000 rows=0 loops=30087)
            Output: tag.id
            Cache Key: taggeditem.tag_id
            Cache Mode: logical
            Hits: 26920  Misses: 3167  Evictions: 0  Overflows: 0  Memory Usage: 248kB
            Buffers: shared hit=9501
            ->  Index Scan using tag_pkey on public.tag  (cost=0.29..4.40 rows=1 width=16) (actual time=0.002..0.002 rows=0 loops=3167)
                  Output: tag.id
                  Index Cond: (tag.id = taggeditem.tag_id)
                  Filter: (((tag.category)::text = 'Cinematography'::text) AND ((tag.name)::text = 'Wide Framing'::text))
                  Rows Removed by Filter: 1
                  Buffers: shared hit=9501
Query Identifier: -3296060046874035074
Planning:
Buffers: shared hit=35
Planning Time: 3.325 ms
Execution Time: 64.475 ms
```

</details>

[Query Plan Visualisation](https://explain.dalibo.com/plan/62dc4cc4623f35a5)

---

Similar to above, I've also noticed a similar pattern with different numbers when I change the values that I'm filtering by. Specifically, I changed `category='AssetType'` and `name='TV Ad'` (stats on these below).
When I change it to these values that are more frequently occuring in the _tag_ table than the ones shown above, I see the exact same pattern, but with `LIMIT 20` and `LIMIT 10`, where limiting to 10 results uses the vector index whereas 20 does not. 

This pattern makes me think if perhaps it's a memory issue?
My `shared_buffers` is currently set to '4GB', which is 25% of the memory on the machine. 

My tables are not extremely large. Here are some stats that might be relevant:
- _tag_ table size: 22,233
- _taggeditem_ table size: 81,176,748
- _segment_ table size: 3,969,216
- no. of _taggeditem_s for (`category`='Cinematography' + `name`='Wide Framing') = 413,482
- no. of _taggeditem_s for (`category`='AssetType' + `name`='TV Ad') = 3,124,493

Is this kind of behavior expected? I expect the tables to grow to billions of rows, and would appreciate any insight into how to mitigate this and make the same query consistently use the index regardless of the values one's filtering by.



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

* Re: [pgvector/pgvector] issue #721: HNSW index bypassed when LIMIT or filter selectivity exceeds threshold
@ 2024-12-04 18:05 ` "ankane (@ankane)" <noreply+ankane@github.com>
  4 siblings, 0 replies; 6+ messages in thread

From: ankane (@ankane) @ 2024-12-04 18:05 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Hi @rsomani95, scanning more a vector index will be more expensive (which can happen with a higher limit or filters with a lower selectivity), and it looks like that's pushing it over the cost of other index scans. If you haven't already, try setting `random_page_cost` to 1.1. You can also use the [pg_hint_plan extension](https://github.com/ossc-db/pg_hint_plan) to better control if an index is used.

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

* Re: [pgvector/pgvector] issue #721: HNSW index bypassed when LIMIT or filter selectivity exceeds threshold
@ 2024-12-04 18:12 ` "rsomani95 (@rsomani95)" <noreply+rsomani95@github.com>
  4 siblings, 0 replies; 6+ messages in thread

From: rsomani95 (@rsomani95) @ 2024-12-04 18:12 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@ankane thanks. I had tried `random_page_cost=1.1` but that didn't help either. 
I forgot to mention but I'd also set `enable_seqscan=off` globally when trying this.

the hint plan looks worth a shot - I'll try it out and report back if it helps.

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

* Re: [pgvector/pgvector] issue #721: HNSW index bypassed when LIMIT or filter selectivity exceeds threshold
@ 2025-02-14 00:46 ` "ankane (@ankane)" <noreply+ankane@github.com>
  4 siblings, 0 replies; 6+ messages in thread

From: ankane (@ankane) @ 2025-02-14 00:46 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I'm not sure there's anything for pgvector to do here, so closing this out.

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

* Re: [pgvector/pgvector] issue #721: HNSW index bypassed when LIMIT or filter selectivity exceeds threshold
@ 2025-02-14 00:46 ` "ankane (@ankane)" <noreply+ankane@github.com>
  4 siblings, 0 replies; 6+ messages in thread

From: ankane (@ankane) @ 2025-02-14 00:46 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@ankane closed this.

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

* Re: [pgvector/pgvector] issue #721: HNSW index bypassed when LIMIT or filter selectivity exceeds threshold
@ 2025-02-27 20:24 ` "rsomani95 (@rsomani95)" <noreply+rsomani95@github.com>
  4 siblings, 0 replies; 6+ messages in thread

From: rsomani95 (@rsomani95) @ 2025-02-27 20:24 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

The `pg_hint_plan` suggestion sent me down a bit of a rabbit hole. While it did force postgres to use the index, the quality of the results was quite inferior to brute force search (which was almost never the case when postgres decided to use the index by itself). I figured that part of the problem was that my filtering params were shaving off like 90% of the graph (not an exact number, but you get the point), so there really wasn't much space left to traverse within the HNSW graph. I ended up building a more tightly scoped index with some of the filtering params built in. 

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


end of thread, other threads:[~2025-02-27 20:24 UTC | newest]

Thread overview: 6+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2024-11-28 09:31 [pgvector/pgvector] issue #721: HNSW index bypassed when LIMIT or filter selectivity exceeds threshold "rsomani95 (@rsomani95)" <noreply+rsomani95@github.com>
2024-12-04 18:05 ` "ankane (@ankane)" <noreply+ankane@github.com>
2024-12-04 18:12 ` "rsomani95 (@rsomani95)" <noreply+rsomani95@github.com>
2025-02-14 00:46 ` "ankane (@ankane)" <noreply+ankane@github.com>
2025-02-14 00:46 ` "ankane (@ankane)" <noreply+ankane@github.com>
2025-02-27 20:24 ` "rsomani95 (@rsomani95)" <noreply+rsomani95@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