pg.ddx.io  pgvector/pgvector GitHub issues and pull requests  
help / color / mirror / Atom feed
[pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
31+ messages / 9 participants
[nested] [flat]

* [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-11-26 14:39  "prathier (@prathier)" <noreply+prathier@github.com>
  0 siblings, 0 replies; 31+ messages in thread

From: prathier (@prathier) @ 2024-11-26 14:39 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Hello,

This kind of queries no longer works on my database which has more rows than before:

```
SELECT
  	(v.embedding <#> '[-0.033441752, ...0.012570631]') as distance
FROM vector_table v
LEFT JOIN files f ON f.id = v.file_id
WHERE f.type = 'MYTYPE' AND f.status = 'PROCESSED'
ORDER BY distance
LIMIT 10;
```

If I increase hnsw.ef_search from 100 to 1000 it works but it's slower. And I suppose that 1000 will not be enough when my table will be bigger.

For now I have 7 millions rows but I will reach billion rows soon.
 
Here is my index:
```
CREATE INDEX IF NOT EXISTS vector_table_embedding_idx 
ON vector_table USING hnsw ((embedding::halfvec(512)) halfvec_ip_ops)
WITH (m = 32, ef_construction = 200);
```

7 millions rows looks very small to me, is there a way to have a query correctly working without partioning or sharding my database ?



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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-11-26 16:55  "jkatz (@jkatz)" <noreply+jkatz@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: jkatz (@jkatz) @ 2024-11-26 16:55 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@prathier What version of pgvector are you using?

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-11-26 20:46  "prathier (@prathier)" <noreply+prathier@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: prathier (@prathier) @ 2024-11-26 20:46 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I'm using 0.7.0. I've tried using subquery or other alternative but I can't force postgresql to process filters before processing the vector index scan. 

Limit  (cost=257.88..334.67 rows=10 width=2216) (actual time=115.136..115.139 rows=0 loops=1)
[...]
        ->  Index Scan using public_vector_table_embedding_idx on public_vector_table v  (cost=257.44..11133279.04 rows=7090160 width=1286) (actual time=108.785..110.447 rows=41 loops=1)
              Order By: (embedding <#> '[-0.033447266,...,0.012573242]'::halfvec)
            [...]
              ->  Index Scan using public_files_pkey on public_files f  (cost=0.43..0.62 rows=1 width=1865) (actual time=0.136..0.136 rows=0 loops=33)
                    Index Cond: (id = v.file_id)
                    Filter: (((type)::text = ANY ('{LAW,JP}'::text[])) AND ((status)::text = 'PROCESSED'::text))
  


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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-11-26 21:20  "jkatz (@jkatz)" <noreply+jkatz@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: jkatz (@jkatz) @ 2024-11-26 21:20 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@prathier Can you try upgrading to pgvector 0.8.0? There's been a lot of work on improving queries with filters, including addressing the "overfiltering" problem (more details in [Filters](https://github.com/pgvector/pgvector?tab=readme-ov-file#filtering).

If your filters are highly selective, it may also make more sense to use a B-tree to process them. v0.8.0 makes it easier to have both an vector index and a B-tree index simultaneously.

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-11-27 08:11  "prathier (@prathier)" <noreply+prathier@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: prathier (@prathier) @ 2024-11-27 08:11 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Ok, i will upgraded to 0.8. 
All columns used on my WHERE are indexed. I've read about [iterative index](https://github.com/pgvector/pgvector?tab=readme-ov-file#iterative-index-scans), should I give it a try ?

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-11-27 10:42  "prathier (@prathier)" <noreply+prathier@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: prathier (@prathier) @ 2024-11-27 10:42 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I'm now using v 0.8.0 on PG17 but the error still persist. It looks like WHERE filters are not applied before processing vector index **if they target a small subset of my table**. I'm using B-tree on all my filters.

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-11-27 13:04  "jkatz (@jkatz)" <noreply+jkatz@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: jkatz (@jkatz) @ 2024-11-27 13:04 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@prathier Did you run `ANALYZE` on the table after building the index? After running that, can you provide an example of the `EXPLAIN ANALYZE` plan with any sensitive info redacted?

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-11-27 16:11  "prathier (@prathier)" <noreply+prathier@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: prathier (@prathier) @ 2024-11-27 16:11 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Yes, I've run `ANALYZE`.

Here a working query with plan:

```
SELECT
     v.id,             
    (v.embedding <#> '[-0.033441752, ... 0.012570631]') as distance
FROM 
    public_vector_table v
LEFT JOIN public_files f ON f.id = v.file_id
WHERE f.status = 'INDEXATION_ERROR'
ORDER BY distance
limit 10;
```

Correct plan:

```
Limit  (cost=913.17..913.18 rows=5 width=16) (actual time=0.139..0.141 rows=10 loops=1)
  Buffers: shared hit=59
  ->  Sort  (cost=913.17..913.18 rows=5 width=16) (actual time=0.138..0.139 rows=10 loops=1)
        Sort Key: ((v.embedding <#> '[-0.033447266,...,0.012573242]'::halfvec))
        Sort Method: top-N heapsort  Memory: 25kB
        Buffers: shared hit=59
        ->  Nested Loop  (cost=0.86..913.11 rows=5 width=16) (actual time=0.036..0.124 rows=25 loops=1)
              Buffers: shared hit=59
              ->  Index Scan using public_files_status_idx on public_files f  (cost=0.43..4.45 rows=1 width=8) (actual time=0.019..0.037 rows=10 loops=1)
                    Index Cond: ((status)::text = 'INDEXATION_ERROR'::text)
                    Buffers: shared hit=13
              ->  Index Scan using public_vector_table_file_id_idx on public_vector_table v  (cost=0.43..906.15 rows=251 width=959) (actual time=0.004..0.007 rows=2 loops=10)
                    Index Cond: (file_id = f.id)
                    Buffers: shared hit=46
Planning:
  Buffers: shared hit=19
Planning Time: 0.405 ms
Execution Time: 0.174 ms
```


Here a non-working query (only the `WHERE` changes):

```
SELECT
     v.id,             
    (v.embedding <#> '[-0.033441752, ... 0.012570631]') as distance
FROM 
    public_vector_table v
LEFT JOIN public_files f ON f.id = v.file_id
WHERE f.type = 'COLLECTIVE'
ORDER BY distance
limit 10;
```
 plan:
```

Limit  (cost=257.88..13212.86 rows=10 width=16) (actual time=5.227..5.229 rows=0 loops=1)
  Buffers: shared hit=2485
  ->  Nested Loop  (cost=257.88..11328096.92 rows=8744 width=16) (actual time=5.225..5.227 rows=0 loops=1)
        Buffers: shared hit=2485
        ->  Index Scan using public_vector_table_embedding_idx on public_vector_table v  (cost=257.44..11133279.04 rows=7090160 width=959) (actual time=4.869..4.941 rows=41 loops=1)
              Order By: (embedding <#> '[-0.033447266,...,0.012573242]'::halfvec)
              Buffers: shared hit=2353
        ->  Memoize  (cost=0.44..0.63 rows=1 width=8) (actual time=0.007..0.007 rows=0 loops=41)
              Cache Key: v.file_id
              Cache Mode: logical
              Hits: 8  Misses: 33  Evictions: 0  Overflows: 0  Memory Usage: 3kB
              Buffers: shared hit=132
              ->  Index Scan using public_files_pkey on public_files f  (cost=0.43..0.62 rows=1 width=8) (actual time=0.007..0.007 rows=0 loops=33)
                    Index Cond: (id = v.file_id)
                    Filter: ((type)::text = 'COLLECTIVE'::text)
                    Rows Removed by Filter: 1
                    Buffers: shared hit=132
Planning:
  Buffers: shared hit=19
Planning Time: 0.417 ms
Execution Time: 6.060 ms
```

Both `status` and `type` column are indexed with btree, and both WHERE represents a very small subset of the data.

I really don't get why we don't have the same plan.




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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-11-28 09:34  "rsomani95 (@rsomani95)" <noreply+rsomani95@github.com>
  29 siblings, 0 replies; 31+ messages in thread

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

@prathier I wonder if you're running into similar issues that I did in https://github.com/pgvector/pgvector/issues/721. In my setup I was querying both columns separately, but see the same pattern when querying them together too. More importantly, _the query planner's choice to use the index / not was directly correlated with the size of the data filtered by the `WHERE` clause_. 

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-11-29 16:14  "jkatz (@jkatz)" <noreply+jkatz@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: jkatz (@jkatz) @ 2024-11-29 16:14 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I think #721 is similar but different; I'm thinking on both of these cases at the moment, and hope to have a response soon (have a few other distractions I'm dealing with!).

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-12-03 13:26  "Tibiritabara (@Tibiritabara)" <noreply+Tibiritabara@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: Tibiritabara (@Tibiritabara) @ 2024-12-03 13:26 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Dear team, I am facing the same issues. We are currently having PG14 on AWS with PGVector 0.7.3. Our table has grown quite a lot recently, and lately, we see queries with no results when using an `ORDER BY`clause.

This is a sample query:

```sql
SELECT "vector_store"."id",
  (EMBEDDING <-> '[...]') AS DISTANCE
  FROM
    "vector_store"
  WHERE
    1 = 1
    AND (
      METADATA ->> 'field' = 'value'
      )
  ORDER BY DISTANCE
  LIMIT 20
```

As soon as I remove the `ORDER BY` I see results. Is there a way I can address this?. This column is using an HNSW index. Whenever I try a non-indexed distance operator, it works.

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-12-03 15:08  "jkatz (@jkatz)" <noreply+jkatz@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: jkatz (@jkatz) @ 2024-12-03 15:08 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@Tibiritabara The short answers is that I would recommend upgrading to pgvector 0.8.0 which has features to addressed overfiltering. You can read more about those here: 

https://github.com/pgvector/pgvector/?tab=readme-ov-file#filtering

(I also just gave a presentation of those features, but the slides/video are not available yet).

In the case that you have highly selective filters in your `METADATA` (high selectivity means only a limited number rows are returned), you can also use a GIN index on your `jsonb` column to search over that data, which could not only end up being faster, but would return the results with better recall. More information on that is here: https://www.postgresql.org/docs/current/datatype-json.html#JSON-INDEXING

(Also, the `1=1` in the query doesn't actually do anything; you can remove it).

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-12-04 10:59  "Tibiritabara (@Tibiritabara)" <noreply+Tibiritabara@github.com>
  29 siblings, 0 replies; 31+ messages in thread

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

Dear @jkatz thank you so much for your prompt answer and support. I will try to upgrade to 0.8.0 soon, and test once again. The current number of records on our DB is close to 50k, a much smaller number that the ones reported by @prathier, the original poster of this issue, but I am afraid I will face the same challenges as him.

I will add the suggested indexes as well on our `jsonb` columns. One last thing, regarding the `1=1`, it is a trick I learned on my data warehousing days. You can then append dynamically as many conditions with `AND ...`, and it will always be syntacticallly correct. It is like leaving a trailing comma at the end of every item on a list in TypeScript or Python. 

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-12-04 15:09  "Tibiritabara (@Tibiritabara)" <noreply+Tibiritabara@github.com>
  29 siblings, 0 replies; 31+ messages in thread

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

Hey @jkatz , I added the suggested `GIN` Indexes, as well as migrated to v0.8.0, and unfortunately the issue is still there. There are no results when querying in the sample query I sent. To overcome this, I just forced postgres to ignore the index, by adding a `+ 0` to the `DISTANCE` column. I can do more tests if required.

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-12-04 15:51  "rsomani95 (@rsomani95)" <noreply+rsomani95@github.com>
  29 siblings, 0 replies; 31+ messages in thread

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

@Tibiritabara did you modify these variables?

```sql
hnsw.ef_search = 200;
hnsw.iterative_scan = 'strict_order';
hnsw.max_scan_tuples = 20000;
hnsw.scan_mem_multiplier = 2;
```

I **_had_** to set these and do some very basic tuning to get results

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-12-04 16:04  "Tibiritabara (@Tibiritabara)" <noreply+Tibiritabara@github.com>
  29 siblings, 0 replies; 31+ messages in thread

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

I will try that out. Thanks for the suggestion.

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-12-12 08:23  "prathier (@prathier)" <noreply+prathier@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: prathier (@prathier) @ 2024-12-12 08:23 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Hi @jkatz,

Do you believe this bug will be difficult to fix? Would it be worth exploring the use of the [pg_hint_plan](https://github.com/ossc-db/pg_hint_plan) extension to manually influence PostgreSQL execution plans as a potential workaround?

Switching to an entirely new vector store would be quite challenging for us, but we’re open to considering it if there’s no feasible solution within a reasonable timeframe. Could you provide an estimate on whether this issue might be resolved in weeks, months, or longer? This information would help us make an informed decision moving forward.

Thank you for your insights!

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-12-12 19:09  "jkatz (@jkatz)" <noreply+jkatz@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: jkatz (@jkatz) @ 2024-12-12 19:09 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@prathier I'm not convinced it's a bug yet and I haven't dug into this issue specifically yet. :smile: But is there a reason why you're using `m=32` instead of `m=16`? Are you able to get the recall target you want with `m=16`?

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-12-19 20:17  "juliag2 (@juliag2)" <noreply+juliag2@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: juliag2 (@juliag2) @ 2024-12-19 20:17 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> @Tibiritabara did you modify these variables?
> 
> ```sql
> hnsw.ef_search = 200;
> hnsw.iterative_scan = 'strict_order';
> hnsw.max_scan_tuples = 20000;
> hnsw.scan_mem_multiplier = 2;
> ```
> 
> I **_had_** to set these and do some very basic tuning to get results

I faced the same issue and this workaround has worked for me.

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2024-12-20 14:41  "jkatz (@jkatz)" <noreply+jkatz@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: jkatz (@jkatz) @ 2024-12-20 14:41 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> > @Tibiritabara did you modify these variables?
> > ```sql
> > hnsw.ef_search = 200;
> > hnsw.iterative_scan = 'strict_order';
> > hnsw.max_scan_tuples = 20000;
> > hnsw.scan_mem_multiplier = 2;
> > ```
> > 
> > 
> >     
> >       
> >     
> > 
> >       
> >     
> > 
> >     
> >   
> > I **_had_** to set these and do some very basic tuning to get results
> 
> I faced the same issue and this workaround has worked for me.

This isn't a workaround - [it's a feature](https://github.com/pgvector/pgvector?tab=readme-ov-file#filtering). Setting `hnsw.iterative_scan` lets PostgreSQL know to continue scanning the index until enough results are returned. We explicitly don't set `hnsw.iterative_scan` by default in v0.8.0, in part because it may not be the best method for all queries involving filters, which I'll discuss more below.

I still need to finish a blog post on this topic, but I [recently spoke on strategies around handling `WHERE` clauses](https://www.youtube.com/watch?v=L8fQqVwTT3Y&ab_channel=AWSEvents) and how the selectivity of your query (how many results you expect to return - high selectivity means you return only a few results) impacts your indexing strategy. Based on your query pattern, it may make more sense to use a B-tree or other index type than a vector index. This can give you both faster queries and better quality results, but it depends on the overall composition of your data.

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2025-02-04 14:12  "Tibiritabara (@Tibiritabara)" <noreply+Tibiritabara@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: Tibiritabara (@Tibiritabara) @ 2025-02-04 14:12 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

So, I have been able to test these settings locally. I currently have a table with vector and sparse embeddings of more than 40k records. As pointed out earlier, I was doing JSONB filtering and currently using v0.8.0. 

After extensive testing, I was able to single out the `iterative_scan` as the most meaningful setting. When is on `strict_order`, the query still takes more than 10 secs for its execution. When using `relaxed_order` I see huge reduction in execution time, down to 600ms. 

This is inline with the contents of your presentation @jkatz , but I need to point out, despite using BTREE and GIN indexes on my metadata, and other filtering attributes, the performance remains poor, unless the `iterative_scan` changes ,and I use the HNSW indexes 

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2025-02-06 08:27  "gili-vega (@gili-vega)" <noreply+gili-vega@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: gili-vega (@gili-vega) @ 2025-02-06 08:27 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I am encountering the same problem.
When combining order by and limit, on a column indexed with HNSW, no results are retrieved at all.
When using order by only (no limit) - results are retrieved correctly.

Trying to setup the local variables did not solve the issue for me. The DB holds around 800K~ vectors and supposed to be even larger in the future.

We are using v0.8.0.

@jkatz What do you suggest? It seems like there is a bug in this very useful feature, makes pgvector almost unusable for our needs

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2025-02-08 20:59  "jkatz (@jkatz)" <noreply+jkatz@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: jkatz (@jkatz) @ 2025-02-08 20:59 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> So, I have been able to test these settings locally. I currently have a table with vector and sparse embeddings of more than 40k records. As pointed out earlier, I was doing JSONB filtering and currently using v0.8.0.
> 
> After extensive testing, I was able to single out the `iterative_scan` as the most meaningful setting. When is on `strict_order`, the query still takes more than 10 secs for its execution. When using `relaxed_order` I see huge reduction in execution time, down to 600ms.
> 
> This is inline with the contents of your presentation [@jkatz](https://github.com/jkatz) , but I need to point out, despite using BTREE and GIN indexes on my metadata, and other filtering attributes, the performance remains poor, unless the `iterative_scan` changes ,and I use the HNSW indexes

@Tibiritabara Thanks for testing, however, I'm not fully following the explanation. Do you only have 40K records total that you're searching over in the dataset? Additionally, it'd be helpful to see the query / indexes you've created / EXPLAIN plans. FWIW, in a lot of my tests, I didn't see a performance difference between strict/relaxed ordering, so I wonder if something else is happening.

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2025-02-08 21:01  "jkatz (@jkatz)" <noreply+jkatz@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: jkatz (@jkatz) @ 2025-02-08 21:01 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> I am encountering the same problem. When combining order by and limit, on a column indexed with HNSW, no results are retrieved at all. When using order by only (no limit) - results are retrieved correctly.
> 
> Trying to setup the local variables did not solve the issue for me. The DB holds around 800K~ vectors and supposed to be even larger in the future.
> 
> We are using v0.8.0.

@gili-vega I'm sorry you're having issues, but unfortunately this is nearly impossible to provide additional guidance on without providing more information.

* Do you have the query and the  `EXPLAIN` plans (redacted if there's sensitive information)  of what you're running?
* Do you have information about the schema and the indexes you put on it (and how you created the indexes)?
* Did you run `ANALYZE` on the table?

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2025-02-10 14:08  "Tibiritabara (@Tibiritabara)" <noreply+Tibiritabara@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: Tibiritabara (@Tibiritabara) @ 2025-02-10 14:08 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> > So, I have been able to test these settings locally. I currently have a table with vector and sparse embeddings of more than 40k records. As pointed out earlier, I was doing JSONB filtering and currently using v0.8.0.
> > After extensive testing, I was able to single out the `iterative_scan` as the most meaningful setting. When is on `strict_order`, the query still takes more than 10 secs for its execution. When using `relaxed_order` I see huge reduction in execution time, down to 600ms.
> > This is inline with the contents of your presentation [@jkatz](https://github.com/jkatz) , but I need to point out, despite using BTREE and GIN indexes on my metadata, and other filtering attributes, the performance remains poor, unless the `iterative_scan` changes ,and I use the HNSW indexes
> 
> [@Tibiritabara](https://github.com/Tibiritabara) Thanks for testing, however, I'm not fully following the explanation. Do you only have 40K records total that you're searching over in the dataset? Additionally, it'd be helpful to see the query / indexes you've created / EXPLAIN plans. FWIW, in a lot of my tests, I didn't see a performance difference between strict/relaxed ordering, so I wonder if something else is happening.

Hey @jkatz thanks for coming back to me and for the support. I am still seeing performance issues when making queries. This is the current set of configurations I am doing:

```sql
  SET hnsw.ef_search TO 200;
  SET hnsw.iterative_scan TO 'relaxed_order';
  SET hnsw.max_scan_tuples TO 20000;
  SET hnsw.scan_mem_multiplier TO 2;
```

The query looks like this:

```SQL
WITH semantic_search AS ( 
    SELECT ai.vector_store.id, ( embedding <=> ? ) AS cosine_distance 
    FROM ai.vector_store 
    WHERE ? = ? AND ( metadata ->> ? = ? or metadata ->> ? = ? ) 
    ORDER BY cosine_distance 
    LIMIT ? 
), sparse_search AS ( 
    SELECT ai.vector_store.id, ( sparse <=> ? ) AS cosine_distance 
    FROM ai.vector_store 
    WHERE ? = ? AND ( metadata ->> ? = ? or metadata ->> ? = ? ) 
    ORDER BY cosine_distance 
    LIMIT ? 
), hybrid_search AS ( 
    SELECT COALESCE ( semantic_search.id, sparse_search.id ) AS id, COALESCE ( ( ( ( ( ? - semantic_search.cosine_distance ) + ? ) / ? ) * ? ), ? ) + COALESCE ( ( ( ( ( ? - sparse_search.cosine_distance ) + ? ) / ? ) * ? ), ? ) AS score 
    FROM semantic_search 
        FULL OUTER JOIN sparse_search ON semantic_search.id = sparse_search.id 
    ORDER BY score DESC 
    LIMIT ? 
) 
SELECT * 
FROM ai.vector_store 
    INNER JOIN hybrid_search ON ai.vector_store.id = hybrid_search.id 
ORDER BY similarity DESC 
LIMIT ? OFFSET ?
```

And the table looks like this:

```SQL
CREATE TABLE IF NOT EXISTS ai.vector_store
(
    id uuid NOT NULL DEFAULT gen_random_uuid(),
    text character varying COLLATE pg_catalog."default" NOT NULL,
    node_id character varying COLLATE pg_catalog."default",
    metadata jsonb,
    embedding vector(1536),
    entity_id uuid NOT NULL,
    similarity double precision,
    created_at timestamp with time zone DEFAULT now(),
    sparse sparsevec(30522),
    CONSTRAINT vector_store_pkey PRIMARY KEY (id),
    CONSTRAINT vector_store_id_fkey FOREIGN KEY (entity_id)
        REFERENCES storage.files (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
)

CREATE INDEX IF NOT EXISTS vector_store_idx
    ON ai.vector_store USING hnsw
    (embedding vector_cosine_ops)
    TABLESPACE pg_default;


CREATE INDEX IF NOT EXISTS vector_store_metadata_idx
    ON ai.vector_store USING gin
    (metadata)
    TABLESPACE pg_default;

CREATE INDEX IF NOT EXISTS vector_store_sparse_idx
    ON ai.vector_store USING hnsw
    (sparse sparsevec_cosine_ops)
    TABLESPACE pg_default;

CREATE INDEX IF NOT EXISTS vector_store_foreign_idx
    ON ai.vector_store USING btree
    (entity_id ASC NULLS LAST)
    TABLESPACE pg_default;
```

And this is the output of the Explain analyze:

```sql
Limit (cost=13869.93..13922.56 rows=20 width=1293) (actual time=1411.403..1411.525 rows=20 loops=1)
  -> Nested Loop (cost=13869.93..13948.87 rows=30 width=1293) (actual time=1411.402..1411.521 rows=20 loops=1)
    -> Limit (cost=13869.52..13869.59 rows=30 width=24) (actual time=1411.386..1411.393 rows=20 loops=1)
      -> Sort (cost=13869.52..13869.59 rows=30 width=24) (actual time=1411.385..1411.390 rows=20 loops=1)
      Sort Key: ((COALESCE((((('1'::double precision - ((vector_store_2.embedding <=> '[...]'::vector))) + '1'::double precision) / '2'::double precision) * '0.5'::double precision), '0'::double precision) + COALESCE((((('1'::double precision - ((vector_store_1.sparse <=> '{...}/30522'::sparsevec))) + '1'::double precision) / '2'::double precision) * '0.5'::double precision), '0'::double precision))) DESC
      Sort Method: quicksort Memory: 27kB
        -> Hash Full Join (cost=10083.92..13868.78 rows=30 width=24) (actual time=1411.153..1411.169 rows=30 loops=1)
        Hash Cond: (vector_store_1.id = vector_store_2.id)
          -> Limit (cost=662.64..4446.11 rows=30 width=24) (actual time=1.760..1.761 rows=0 loops=1)
            -> Index Scan using vector_store_sparse_idx on vector_store vector_store_1 (cost=662.64..59054.25 rows=463 width=24) (actual time=1.759..1.759 rows=0 loops=1)
            Order By: (sparse <=> '{...}/30522'::sparsevec)
            Filter: (((metadata ->> 'key'::text) = 'xxx'::text) OR ((metadata ->> 'entity_id'::text) = 'xxx'::text))
            Rows Removed by Filter: 40
          -> Hash (cost=9420.91..9420.91 rows=30 width=24) (actual time=1409.380..1409.382 rows=30 loops=1)
          Buckets: 1024 Batches: 1 Memory Usage: 10kB
            -> Limit (cost=9420.53..9420.61 rows=30 width=24) (actual time=1409.366..1409.373 rows=30 loops=1)
              -> Sort (cost=9420.53..9421.69 rows=463 width=24) (actual time=1409.364..1409.368 rows=30 loops=1)
              Sort Key: ((vector_store_2.embedding <=> '[...]'::vector))
              Sort Method: top-N heapsort Memory: 28kB
                -> Seq Scan on vector_store vector_store_2 (cost=0.00..9406.86 rows=463 width=24) (actual time=0.109..1408.807 rows=1561 loops=1)
                Filter: (((metadata ->> 'key'::text) = 'xxx'::text) OR ((metadata ->> 'entity_id'::text) = 'xxx'::text))
                Rows Removed by Filter: 44542
    -> Index Scan using vector_store_pkey on vector_store (cost=0.41..2.63 rows=1 width=1285) (actual time=0.005..0.005 rows=1 loops=20)
    Index Cond: (id = (COALESCE(vector_store_2.id, vector_store_1.id)))
Planning Time: 0.838 ms
Execution Time: 1411.618 ms
```

As seen, I built a hybrid search solution, running on the SQL server. For this hybrid search to work, we use both, dense and sparse search, and we merge the results to get a meaningful/ranked output.

I hope this helps



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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2025-02-12 12:45  "Tibiritabara (@Tibiritabara)" <noreply+Tibiritabara@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: Tibiritabara (@Tibiritabara) @ 2025-02-12 12:45 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> > > So, I have been able to test these settings locally. I currently have a table with vector and sparse embeddings of more than 40k records. As pointed out earlier, I was doing JSONB filtering and currently using v0.8.0.
> > > After extensive testing, I was able to single out the `iterative_scan` as the most meaningful setting. When is on `strict_order`, the query still takes more than 10 secs for its execution. When using `relaxed_order` I see huge reduction in execution time, down to 600ms.
> > > This is inline with the contents of your presentation [@jkatz](https://github.com/jkatz) , but I need to point out, despite using BTREE and GIN indexes on my metadata, and other filtering attributes, the performance remains poor, unless the `iterative_scan` changes ,and I use the HNSW indexes
> > 
> > 
> > [@Tibiritabara](https://github.com/Tibiritabara) Thanks for testing, however, I'm not fully following the explanation. Do you only have 40K records total that you're searching over in the dataset? Additionally, it'd be helpful to see the query / indexes you've created / EXPLAIN plans. FWIW, in a lot of my tests, I didn't see a performance difference between strict/relaxed ordering, so I wonder if something else is happening.
> 
> Hey [@jkatz](https://github.com/jkatz) thanks for coming back to me and for the support. I am still seeing performance issues when making queries. This is the current set of configurations I am doing:
> 
>   SET hnsw.ef_search TO 200;
>   SET hnsw.iterative_scan TO 'relaxed_order';
>   SET hnsw.max_scan_tuples TO 20000;
>   SET hnsw.scan_mem_multiplier TO 2;
> 
> The query looks like this:
> 
> WITH semantic_search AS ( 
>     SELECT ai.vector_store.id, ( embedding <=> ? ) AS cosine_distance 
>     FROM ai.vector_store 
>     WHERE ? = ? AND ( metadata ->> ? = ? or metadata ->> ? = ? ) 
>     ORDER BY cosine_distance 
>     LIMIT ? 
> ), sparse_search AS ( 
>     SELECT ai.vector_store.id, ( sparse <=> ? ) AS cosine_distance 
>     FROM ai.vector_store 
>     WHERE ? = ? AND ( metadata ->> ? = ? or metadata ->> ? = ? ) 
>     ORDER BY cosine_distance 
>     LIMIT ? 
> ), hybrid_search AS ( 
>     SELECT COALESCE ( semantic_search.id, sparse_search.id ) AS id, COALESCE ( ( ( ( ( ? - semantic_search.cosine_distance ) + ? ) / ? ) * ? ), ? ) + COALESCE ( ( ( ( ( ? - sparse_search.cosine_distance ) + ? ) / ? ) * ? ), ? ) AS score 
>     FROM semantic_search 
>         FULL OUTER JOIN sparse_search ON semantic_search.id = sparse_search.id 
>     ORDER BY score DESC 
>     LIMIT ? 
> ) 
> SELECT * 
> FROM ai.vector_store 
>     INNER JOIN hybrid_search ON ai.vector_store.id = hybrid_search.id 
> ORDER BY similarity DESC 
> LIMIT ? OFFSET ?
> 
> And the table looks like this:
> 
> CREATE TABLE IF NOT EXISTS ai.vector_store
> (
>     id uuid NOT NULL DEFAULT gen_random_uuid(),
>     text character varying COLLATE pg_catalog."default" NOT NULL,
>     node_id character varying COLLATE pg_catalog."default",
>     metadata jsonb,
>     embedding vector(1536),
>     entity_id uuid NOT NULL,
>     similarity double precision,
>     created_at timestamp with time zone DEFAULT now(),
>     sparse sparsevec(30522),
>     CONSTRAINT vector_store_pkey PRIMARY KEY (id),
>     CONSTRAINT vector_store_id_fkey FOREIGN KEY (entity_id)
>         REFERENCES storage.files (id) MATCH SIMPLE
>         ON UPDATE CASCADE
>         ON DELETE CASCADE
> )
> 
> CREATE INDEX IF NOT EXISTS vector_store_idx
>     ON ai.vector_store USING hnsw
>     (embedding vector_cosine_ops)
>     TABLESPACE pg_default;
> 
> 
> CREATE INDEX IF NOT EXISTS vector_store_metadata_idx
>     ON ai.vector_store USING gin
>     (metadata)
>     TABLESPACE pg_default;
> 
> CREATE INDEX IF NOT EXISTS vector_store_sparse_idx
>     ON ai.vector_store USING hnsw
>     (sparse sparsevec_cosine_ops)
>     TABLESPACE pg_default;
> 
> CREATE INDEX IF NOT EXISTS vector_store_foreign_idx
>     ON ai.vector_store USING btree
>     (entity_id ASC NULLS LAST)
>     TABLESPACE pg_default;
> 
> And this is the output of the Explain analyze:
> 
> Limit (cost=13869.93..13922.56 rows=20 width=1293) (actual time=1411.403..1411.525 rows=20 loops=1)
>   -> Nested Loop (cost=13869.93..13948.87 rows=30 width=1293) (actual time=1411.402..1411.521 rows=20 loops=1)
>     -> Limit (cost=13869.52..13869.59 rows=30 width=24) (actual time=1411.386..1411.393 rows=20 loops=1)
>       -> Sort (cost=13869.52..13869.59 rows=30 width=24) (actual time=1411.385..1411.390 rows=20 loops=1)
>       Sort Key: ((COALESCE((((('1'::double precision - ((vector_store_2.embedding <=> '[...]'::vector))) + '1'::double precision) / '2'::double precision) * '0.5'::double precision), '0'::double precision) + COALESCE((((('1'::double precision - ((vector_store_1.sparse <=> '{...}/30522'::sparsevec))) + '1'::double precision) / '2'::double precision) * '0.5'::double precision), '0'::double precision))) DESC
>       Sort Method: quicksort Memory: 27kB
>         -> Hash Full Join (cost=10083.92..13868.78 rows=30 width=24) (actual time=1411.153..1411.169 rows=30 loops=1)
>         Hash Cond: (vector_store_1.id = vector_store_2.id)
>           -> Limit (cost=662.64..4446.11 rows=30 width=24) (actual time=1.760..1.761 rows=0 loops=1)
>             -> Index Scan using vector_store_sparse_idx on vector_store vector_store_1 (cost=662.64..59054.25 rows=463 width=24) (actual time=1.759..1.759 rows=0 loops=1)
>             Order By: (sparse <=> '{...}/30522'::sparsevec)
>             Filter: (((metadata ->> 'key'::text) = 'xxx'::text) OR ((metadata ->> 'entity_id'::text) = 'xxx'::text))
>             Rows Removed by Filter: 40
>           -> Hash (cost=9420.91..9420.91 rows=30 width=24) (actual time=1409.380..1409.382 rows=30 loops=1)
>           Buckets: 1024 Batches: 1 Memory Usage: 10kB
>             -> Limit (cost=9420.53..9420.61 rows=30 width=24) (actual time=1409.366..1409.373 rows=30 loops=1)
>               -> Sort (cost=9420.53..9421.69 rows=463 width=24) (actual time=1409.364..1409.368 rows=30 loops=1)
>               Sort Key: ((vector_store_2.embedding <=> '[...]'::vector))
>               Sort Method: top-N heapsort Memory: 28kB
>                 -> Seq Scan on vector_store vector_store_2 (cost=0.00..9406.86 rows=463 width=24) (actual time=0.109..1408.807 rows=1561 loops=1)
>                 Filter: (((metadata ->> 'key'::text) = 'xxx'::text) OR ((metadata ->> 'entity_id'::text) = 'xxx'::text))
>                 Rows Removed by Filter: 44542
>     -> Index Scan using vector_store_pkey on vector_store (cost=0.41..2.63 rows=1 width=1285) (actual time=0.005..0.005 rows=1 loops=20)
>     Index Cond: (id = (COALESCE(vector_store_2.id, vector_store_1.id)))
> Planning Time: 0.838 ms
> Execution Time: 1411.618 ms
> 
> As seen, I built a hybrid search solution, running on the SQL server. For this hybrid search to work, we use both, dense and sparse search, and we merge the results to get a meaningful/ranked output.
> 
> I hope this helps

So after further analysis of the issues, in my scenario I noticed that the metadata filters were expensive, as they were doing a full scan. For some reason, and despite the GIN index existing on my metadata field, postgres was still doing the full scan nonetheless. 

I just added b-tree indexes on the two most common filters, and saw a performance increase. Thanks for the support

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2025-02-20 18:17  "JoshInnis (@JoshInnis)" <noreply+JoshInnis@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: JoshInnis (@JoshInnis) @ 2025-02-20 18:17 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> > > > So, I have been able to test these settings locally. I currently have a table with vector and sparse embeddings of more than 40k records. As pointed out earlier, I was doing JSONB filtering and currently using v0.8.0.
> > > > After extensive testing, I was able to single out the `iterative_scan` as the most meaningful setting. When is on `strict_order`, the query still takes more than 10 secs for its execution. When using `relaxed_order` I see huge reduction in execution time, down to 600ms.
> > > > This is inline with the contents of your presentation [@jkatz](https://github.com/jkatz) , but I need to point out, despite using BTREE and GIN indexes on my metadata, and other filtering attributes, the performance remains poor, unless the `iterative_scan` changes ,and I use the HNSW indexes
> > > 
> > > 
> > > [@Tibiritabara](https://github.com/Tibiritabara) Thanks for testing, however, I'm not fully following the explanation. Do you only have 40K records total that you're searching over in the dataset? Additionally, it'd be helpful to see the query / indexes you've created / EXPLAIN plans. FWIW, in a lot of my tests, I didn't see a performance difference between strict/relaxed ordering, so I wonder if something else is happening.
> > 
> > 
> > Hey [@jkatz](https://github.com/jkatz) thanks for coming back to me and for the support. I am still seeing performance issues when making queries. This is the current set of configurations I am doing:
> > SET hnsw.ef_search TO 200;
> > SET hnsw.iterative_scan TO 'relaxed_order';
> > SET hnsw.max_scan_tuples TO 20000;
> > SET hnsw.scan_mem_multiplier TO 2;
> > The query looks like this:
> > WITH semantic_search AS (
> > SELECT ai.vector_store.id, ( embedding <=> ? ) AS cosine_distance
> > FROM ai.vector_store
> > WHERE ? = ? AND ( metadata ->> ? = ? or metadata ->> ? = ? )
> > ORDER BY cosine_distance
> > LIMIT ?
> > ), sparse_search AS (
> > SELECT ai.vector_store.id, ( sparse <=> ? ) AS cosine_distance
> > FROM ai.vector_store
> > WHERE ? = ? AND ( metadata ->> ? = ? or metadata ->> ? = ? )
> > ORDER BY cosine_distance
> > LIMIT ?
> > ), hybrid_search AS (
> > SELECT COALESCE ( semantic_search.id, sparse_search.id ) AS id, COALESCE ( ( ( ( ( ? - semantic_search.cosine_distance ) + ? ) / ? ) * ? ), ? ) + COALESCE ( ( ( ( ( ? - sparse_search.cosine_distance ) + ? ) / ? ) * ? ), ? ) AS score
> > FROM semantic_search
> > FULL OUTER JOIN sparse_search ON semantic_search.id = sparse_search.id
> > ORDER BY score DESC
> > LIMIT ?
> > )
> > SELECT *
> > FROM ai.vector_store
> > INNER JOIN hybrid_search ON ai.vector_store.id = hybrid_search.id
> > ORDER BY similarity DESC
> > LIMIT ? OFFSET ?
> > And the table looks like this:
> > CREATE TABLE IF NOT EXISTS ai.vector_store
> > (
> > id uuid NOT NULL DEFAULT gen_random_uuid(),
> > text character varying COLLATE pg_catalog."default" NOT NULL,
> > node_id character varying COLLATE pg_catalog."default",
> > metadata jsonb,
> > embedding vector(1536),
> > entity_id uuid NOT NULL,
> > similarity double precision,
> > created_at timestamp with time zone DEFAULT now(),
> > sparse sparsevec(30522),
> > CONSTRAINT vector_store_pkey PRIMARY KEY (id),
> > CONSTRAINT vector_store_id_fkey FOREIGN KEY (entity_id)
> > REFERENCES storage.files (id) MATCH SIMPLE
> > ON UPDATE CASCADE
> > ON DELETE CASCADE
> > )
> > CREATE INDEX IF NOT EXISTS vector_store_idx
> > ON ai.vector_store USING hnsw
> > (embedding vector_cosine_ops)
> > TABLESPACE pg_default;
> > CREATE INDEX IF NOT EXISTS vector_store_metadata_idx
> > ON ai.vector_store USING gin
> > (metadata)
> > TABLESPACE pg_default;
> > CREATE INDEX IF NOT EXISTS vector_store_sparse_idx
> > ON ai.vector_store USING hnsw
> > (sparse sparsevec_cosine_ops)
> > TABLESPACE pg_default;
> > CREATE INDEX IF NOT EXISTS vector_store_foreign_idx
> > ON ai.vector_store USING btree
> > (entity_id ASC NULLS LAST)
> > TABLESPACE pg_default;
> > And this is the output of the Explain analyze:
> > Limit (cost=13869.93..13922.56 rows=20 width=1293) (actual time=1411.403..1411.525 rows=20 loops=1)
> > -> Nested Loop (cost=13869.93..13948.87 rows=30 width=1293) (actual time=1411.402..1411.521 rows=20 loops=1)
> > -> Limit (cost=13869.52..13869.59 rows=30 width=24) (actual time=1411.386..1411.393 rows=20 loops=1)
> > -> Sort (cost=13869.52..13869.59 rows=30 width=24) (actual time=1411.385..1411.390 rows=20 loops=1)
> > Sort Key: ((COALESCE((((('1'::double precision - ((vector_store_2.embedding <=> '[...]'::vector))) + '1'::double precision) / '2'::double precision) * '0.5'::double precision), '0'::double precision) + COALESCE((((('1'::double precision - ((vector_store_1.sparse <=> '{...}/30522'::sparsevec))) + '1'::double precision) / '2'::double precision) * '0.5'::double precision), '0'::double precision))) DESC
> > Sort Method: quicksort Memory: 27kB
> > -> Hash Full Join (cost=10083.92..13868.78 rows=30 width=24) (actual time=1411.153..1411.169 rows=30 loops=1)
> > Hash Cond: (vector_store_1.id = vector_store_2.id)
> > -> Limit (cost=662.64..4446.11 rows=30 width=24) (actual time=1.760..1.761 rows=0 loops=1)
> > -> Index Scan using vector_store_sparse_idx on vector_store vector_store_1 (cost=662.64..59054.25 rows=463 width=24) (actual time=1.759..1.759 rows=0 loops=1)
> > Order By: (sparse <=> '{...}/30522'::sparsevec)
> > Filter: (((metadata ->> 'key'::text) = 'xxx'::text) OR ((metadata ->> 'entity_id'::text) = 'xxx'::text))
> > Rows Removed by Filter: 40
> > -> Hash (cost=9420.91..9420.91 rows=30 width=24) (actual time=1409.380..1409.382 rows=30 loops=1)
> > Buckets: 1024 Batches: 1 Memory Usage: 10kB
> > -> Limit (cost=9420.53..9420.61 rows=30 width=24) (actual time=1409.366..1409.373 rows=30 loops=1)
> > -> Sort (cost=9420.53..9421.69 rows=463 width=24) (actual time=1409.364..1409.368 rows=30 loops=1)
> > Sort Key: ((vector_store_2.embedding <=> '[...]'::vector))
> > Sort Method: top-N heapsort Memory: 28kB
> > -> Seq Scan on vector_store vector_store_2 (cost=0.00..9406.86 rows=463 width=24) (actual time=0.109..1408.807 rows=1561 loops=1)
> > Filter: (((metadata ->> 'key'::text) = 'xxx'::text) OR ((metadata ->> 'entity_id'::text) = 'xxx'::text))
> > Rows Removed by Filter: 44542
> > -> Index Scan using vector_store_pkey on vector_store (cost=0.41..2.63 rows=1 width=1285) (actual time=0.005..0.005 rows=1 loops=20)
> > Index Cond: (id = (COALESCE(vector_store_2.id, vector_store_1.id)))
> > Planning Time: 0.838 ms
> > Execution Time: 1411.618 ms
> > As seen, I built a hybrid search solution, running on the SQL server. For this hybrid search to work, we use both, dense and sparse search, and we merge the results to get a meaningful/ranked output.
> > I hope this helps
> 
> So after further analysis of the issues, in my scenario I noticed that the metadata filters were expensive, as they were doing a full scan. For some reason, and despite the GIN index existing on my metadata field, postgres was still doing the full scan nonetheless.
> 
> I just added b-tree indexes on the two most common filters, and saw a performance increase. Thanks for the support

JsonB's GIN index works on keys existence operators (?, ?|, ?&, etc] not equality operators (<, <=, =, >, >=, etc) since you aren't using those operators the GIN index isn't considered better than doing a SeqScan. https://www.postgresql.org/docs/current/gin.html

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2025-02-20 22:27  "ankane (@ankane)" <noreply+ankane@github.com>
  29 siblings, 0 replies; 31+ messages in thread

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

I don't think there's anything for pgvector to do here, so closing this out (this behavior is documented in the [filtering](https://github.com/pgvector/pgvector?tab=readme-ov-file#filtering), [iterative index scans](https://github.com/pgvector/pgvector?tab=readme-ov-file#iterative-index-scans), and [troubleshooting](https://github.com/pgvector/pgvector?tab=readme-ov-file#why-are-there-less-results-for-a-query-after...) docs). In most cases, you should only need to set `hnsw.iterative_scan` (not any of the other values).

Iterative index scans may be enabled by default for HNSW in the future, but this can currently slow down queries that filter by distance without a CTE (see the iterative scan docs for more details).

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2025-02-20 22:27  "ankane (@ankane)" <noreply+ankane@github.com>
  29 siblings, 0 replies; 31+ messages in thread

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

@ankane closed this.

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2025-02-24 15:42  "shikaiwei1 (@shikaiwei1)" <noreply+shikaiwei1@github.com>
  29 siblings, 0 replies; 31+ messages in thread

From: shikaiwei1 (@shikaiwei1) @ 2025-02-24 15:42 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I tried to add "SET hnsw.iterative_scan = on;" into my sql, but it doesn`t work. I used 0.8.0.

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

* Re: [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results
@ 2025-02-24 18:00  "ankane (@ankane)" <noreply+ankane@github.com>
  29 siblings, 0 replies; 31+ messages in thread

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

Hi @shikaiwei1, see the docs for the correct statement to run. If that doesn't solve it, please create a new issue with the details about your setup and the output of `EXPLAIN ANALYZE`.

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


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

Thread overview: 31+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2024-11-26 14:39 [pgvector/pgvector] issue #719: SELECT WHERE ORDER BY LIMIT no results "prathier (@prathier)" <noreply+prathier@github.com>
2024-11-26 16:55 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-11-26 20:46 ` "prathier (@prathier)" <noreply+prathier@github.com>
2024-11-26 21:20 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-11-27 08:11 ` "prathier (@prathier)" <noreply+prathier@github.com>
2024-11-27 10:42 ` "prathier (@prathier)" <noreply+prathier@github.com>
2024-11-27 13:04 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-11-27 16:11 ` "prathier (@prathier)" <noreply+prathier@github.com>
2024-11-28 09:34 ` "rsomani95 (@rsomani95)" <noreply+rsomani95@github.com>
2024-11-29 16:14 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-12-03 13:26 ` "Tibiritabara (@Tibiritabara)" <noreply+Tibiritabara@github.com>
2024-12-03 15:08 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-12-04 10:59 ` "Tibiritabara (@Tibiritabara)" <noreply+Tibiritabara@github.com>
2024-12-04 15:09 ` "Tibiritabara (@Tibiritabara)" <noreply+Tibiritabara@github.com>
2024-12-04 15:51 ` "rsomani95 (@rsomani95)" <noreply+rsomani95@github.com>
2024-12-04 16:04 ` "Tibiritabara (@Tibiritabara)" <noreply+Tibiritabara@github.com>
2024-12-12 08:23 ` "prathier (@prathier)" <noreply+prathier@github.com>
2024-12-12 19:09 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-12-19 20:17 ` "juliag2 (@juliag2)" <noreply+juliag2@github.com>
2024-12-20 14:41 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2025-02-04 14:12 ` "Tibiritabara (@Tibiritabara)" <noreply+Tibiritabara@github.com>
2025-02-06 08:27 ` "gili-vega (@gili-vega)" <noreply+gili-vega@github.com>
2025-02-08 20:59 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2025-02-08 21:01 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2025-02-10 14:08 ` "Tibiritabara (@Tibiritabara)" <noreply+Tibiritabara@github.com>
2025-02-12 12:45 ` "Tibiritabara (@Tibiritabara)" <noreply+Tibiritabara@github.com>
2025-02-20 18:17 ` "JoshInnis (@JoshInnis)" <noreply+JoshInnis@github.com>
2025-02-20 22:27 ` "ankane (@ankane)" <noreply+ankane@github.com>
2025-02-20 22:27 ` "ankane (@ankane)" <noreply+ankane@github.com>
2025-02-24 15:42 ` "shikaiwei1 (@shikaiwei1)" <noreply+shikaiwei1@github.com>
2025-02-24 18:00 ` "ankane (@ankane)" <noreply+ankane@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