pg.ddx.io  pgvector/pgvector GitHub issues and pull requests  
help / color / mirror / Atom feed
[pgvector/pgvector] issue #259: Understanding HNSW + filtering
90+ messages / 22 participants
[nested] [flat]

* [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-11 08:45 "Palmik (@Palmik)" <noreply+Palmik@github.com>
  0 siblings, 0 replies; 90+ messages in thread

From: Palmik (@Palmik) @ 2023-09-11 08:45 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Hi, I would like to understand how the current implementation handles HNSW + filtering.

Imagine you have a table:

```sql
CREATE TABLE document (
  id UUID PRIMARY KEY,
  text TEXT NOT NULL,
  embedding REAL[] NOT NULL,
  category TEXT NOT NULL
)
```

And that you even have an index on `category`:

```sql
CREATE INDEX document_category ON document (category);
```

And then you want to do a query like:

```sql
SELECT id, text
FROM document
WHERE category = $1
ORDER BY embedding <-> $2
LIMIT 10;
```

To do this efficiently is not straightforward -- ideally we want to do the expensive HNSW ANN on the already pruned subset (https://qdrant.tech/articles/filtrable-hnsw/). Can pgvector do this, or is there plan to enable such optimization in the future?

(In this case the condition is simple enough that you might be able to use table partitioning, but that's not always the case)

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-11 08:45 ` "Palmik (@Palmik)" <noreply+Palmik@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: Palmik (@Palmik) @ 2023-09-11 08:45 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@Palmik renamed this.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-11 14:22 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: jkatz (@jkatz) @ 2023-09-11 14:22 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@Palmik PostgreSQL supports [conditional indexing][1] through [partial indexes][1] which lets you define an index like:

```sql
CREATE INDEX ON document USING hnsw(embedding) WHERE category = ?
```

However, you would have to do this for every single category in the database. To look up from both indexes at the same time, pgvector would have to add support for bitmap scans in `hnsw`.

That said, picking an indexing strategy may depend on the actual contents of your data. For example, if your `category` filter eliminates most rows (e.g. you have a handful of vectors to compare remaining), using the index `embedding` may not make sense. Or based upon your use case, you may want to perform the ANN search first and then filter out the results by category.

[1]: https://www.postgresql.org/docs/current/indexes-partial.html

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-11 14:52 ` "Palmik (@Palmik)" <noreply+Palmik@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: Palmik (@Palmik) @ 2023-09-11 14:52 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Thanks Jonathan. Partial index on all possible categories is also unfortunately not feasible (for similar reasons partitioning is not). While in our case category filter will eliminate most documents, the remaining document set is still too large for nearest-neighbor scan without index (millions of documents).

Is there any plan to support these kind of use cases, where combining traditional and hnsw indices would lead to much better performance?

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-11 14:53 ` "Palmik (@Palmik)" <noreply+Palmik@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: Palmik (@Palmik) @ 2023-09-11 14:53 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I stumbled on https://github.com/tensorchord/pgvecto.rs -- which claims to support such use case, but I did not delve into implementation details.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-11 15:25 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: jkatz (@jkatz) @ 2023-09-11 15:25 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> Is there any plan to support these kind of use cases, where combining traditional and hnsw indices would lead to much better performance?

I have a POC that does this, but it requires some more investigation on how to best support it. One challenge is that the values in the `ORDER BY` clause are not available to the index access method ([`amgetbitmap`][1]) that you need to perform this type of scan. There are other ways we could attempt it today, but we'd have to decide if it makes sense to add a new operator to the `WHERE` clause to specifically allow for this type of scan, or if we need to propose changes upstream.

It's likely possible to do "post-filtering" as part of the index scan if we add support for [covering indexes][2], though the tradeoff is that it requires storing more data in the index itself.

I took a quick look at the implementation you shared above -- it looks like it uses an alternative storage system, not PostgreSQL, so it would not be an apples-to-apples comparison on how to do dynaminc prefiltering as part of the index scan.

> While in our case category filter will eliminate most documents, the remaining document set is still too large for nearest-neighbor scan without index (millions of documents).

How many categories do you have? Do they all require partitions, or just a few? I'm curious, mainly because based on that, it may be reasonable to partition some set of the data and keep the rest in the default partition.

[1]: https://www.postgresql.org/docs/current/index-scanning.html
[2]: https://www.postgresql.org/docs/current/indexes-index-only-scans.html

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-12 11:43 ` "pashkinelfe (@pashkinelfe)" <noreply+pashkinelfe@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: pashkinelfe (@pashkinelfe) @ 2023-09-12 11:43 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

TL;DR The feasible way is to have filtering data in the same index with vectors.

@jkatz I may be wrong but I suppose that the main problem of using bitmap scan would be that the result of bitmap AND query is proper only if ordering is done after BitmapAnd node (that's likely the reason that Bitmap scan node doesn't get ORDER BY clause). But after BitmapAnd we don't have index data anymore to do efficient ANN. 

Otherwise, if we have ANN before BitmapAnd we'll get only a small number of nearest-neighbors into bitmap (while it's supposed to have all tuples). We are likely to wrongly get no tuples after BitmapAnd at all. To avoid this we need to have a sufficient (how many is sufficient?) amount of tuples after ANN. I think that's not how filtering by another attribute should work.

So, IMO we can't use bitmap scan to do this kind of filtering.

The closest way to do this kind of filtering could be by implementing a covering index with filtering by the included column during index scan


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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-12 18:29 ` "ankane (@ankane)" <noreply+ankane@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: ankane (@ankane) @ 2023-09-12 18:29 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@pashkinelfe That's my understanding as well.

It'd be great if someone wanted to explore this. I think the decision to support it would come down to the complexity it adds. I've added to ideas (#27).

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-12 18:34 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

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

One thought around this specific to HNSW: perhaps there's a way towards a "multi-column" style index that would require more links, but allow for this type of query.

Let's say I have two columns: `embedding` and `category_id` and I choose to index both of them with a `hnsw` index. During the index creation, I would build out two different kinds of neighborhoods:

1. Neighborhoods around `embedding`
2. Neighborhoods around a `category_id` and `embedding` pair

When I have a `category_id` in my query, I then know to traverse the links that are around `category_id`/`embedding` pairs that have the same `embedding`. Otherwise, if I just have `embedding`, I would traverse any link.

This would increase index size + construction time, which is no different than multi-column indexes, and would may require an expansion of the on-disk format, this would allow you to trim down the pages you need to search on a particular filter.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-12 18:47 ` "pashkinelfe (@pashkinelfe)" <noreply+pashkinelfe@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: pashkinelfe (@pashkinelfe) @ 2023-09-12 18:47 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@jkatz It's an interesting idea! Though there is one thing that I don't quite catch: how to combine "nearness" in two different spaces. Furthermore, nearness in embedding HNSW component is inexact, but a  link lost (or unfollowed at scan)between `category_id` makes everything inexact. I'm not sure it's completely unacceptable but can introduce some behavior that is not expected under "filtering by other column" term.

It needs further thought I suppose, it seems hard to implement combined btree+hnsw in one index. Filtering by included column seems much clearer.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-12 18:57 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

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

I'm not suggesting a B-tree (though perhaps we need some semantics like that at the top layer?), but rather, when we compute the distances between vectors, we compute two sets:

1. Just by `embedding` (and we maintain M links)
2. By `embedding` and `category_id` where we find all vectors that have the same `category_id` and maintain `M` links between these items

The thought process is that we want to reduce the number of embeddings we have to scan, but we want to ensure that our search is efficient. If we just keep the value in an `INCLUDE` column, we may not see the best available embeddings for a particularly `category_id` (or whatever the column is), or we may have to perform a more exhaustive search.

What I'm attempting to propose is a method to ensure our search is efficient and finds the best embeddings for a particular `category_id`, though at the cost of keeping additional info in the index and build time.


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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-14 07:49 ` "fanfuxiaoran (@fanfuxiaoran)" <noreply+fanfuxiaoran@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: fanfuxiaoran (@fanfuxiaoran) @ 2023-09-14 07:49 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@jkatz I found a page that proposed some methods to deal with `attribute filter ` https://www.cs.purdue.edu/homes/csjgwang/pubs/SIGMOD21_Milvus.pdf
I just have a rough idea: If there is any index on the attribute,  we can first search the attribute and get a TID bitmap,
then use the bitmap to do a vector search. The bitmap can be used to filter vector items in the index, and the vector search doesn't stop until it finds enough neighbors. But it is tough, the vector index needs to sort the result and doesn't know how many dead tuples and how many target rows need to return,  so it actually doesn't know when to stop searching neighbors.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-14 14:58 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: jkatz (@jkatz) @ 2023-09-14 14:58 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Forgot to post this the other day, but this is what I was thinking around HNSW -- effectively keeping two pairs of links in a "multi-column" style index. The first set of links connect every vector in the index. The second set of links are specific to a particular filter (e.g. `cat_id`). That way, if you're searching on a "filter", you're searching on those links directly related to the filter.

![hnsw-cat](https://github.com/pgvector/pgvector/assets/1694/b22aa3e6-e9c5-4356-8086-e4a1eac6d48a)


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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-14 14:59 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: jkatz (@jkatz) @ 2023-09-14 14:59 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@fanfuxiaoran Thanks for sharing. I haven't read through the doc yet, but on the surface, I'm not sure how that's different from the bitmap index scan and the same issues as described earlier in the thread.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-15 14:33 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: jkatz (@jkatz) @ 2023-09-15 14:33 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I thought about an approach for `ivfflat` using a multicolumn index strategy. This will example will use two columns: (`embedding`, `category_id`):

## Build

We would keep two structure:
* The ivfflat structure, with extra space to store the additional columns (in this case `category_id`).
* A B-tree structure that only stores **unique** values for `category_id` (e.g. a `category_id` only appears once). At the leaf, each `category_id` would point to the TIDs of any of the `lists` metapages that contain the `category_id` value. The max number of TIDs for any `category_id` would be `lists`.
* When insert a new `embedding`, we first determine the list we want to insert it into, and get the list TID. Then we check if `category_id` exists in the B-tree. If it does, and the list TID does not exist, we add it. If it does not, we insert into the `category_id` B-tree with the list `TID`. We insert `embedding` into the list as usual, with the added `category_id` in the tuple.

## Scan

If we see that we have an index scan with the filter column (e.g. `category_id`), we first go into the B-tree and determine if it's present
* if it's not present, we can return no rows!
* If it is present, we get the the TIDs that contain embeddings of `category_id`. (If there are no list TIDs, we return)
* We then do the distance ordering of lists against the query vector, and keep `probes` total.
* We then scan the lists -- if we encounter an entry where `category_id` does not match the query `category_id`, we skip that entry. otherwise we add the heap TID + distance to the sort (same as now)
* Finally, we return the TIDs to the executor to do its work.

## Delete
* Find the list that the target tuple is in
* Scan the list to see if there are any other tuples with the same `category_id`
  *  If there are none (other than this one), update the B-tree to remove the list TID from the `category_id` entry

## Open Questions

* In the B-tree, do we maintain a (list TID, count) for each `category_id`? This would involve more locking on insert/delete, but on a delete, once we find the target embedding in the list, we can eliminate it and not scan all the tuples in the list
* Additionally, we'd want to make sure there's enough info available to show a reduced cost when we have a `category_id` (or equivalent) column
* Finally, in the case we have a `category_id` present, I wonder if we can store the values in the `lists` themselves in a B-tree structure, so that way we can go directly to those values.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-16 15:02 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: knizhnik (@knizhnik) @ 2023-09-16 15:02 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I wonder if we can use much simpler approach - just repeat search with larger `ef_search` valuer to return more candidates.  I tried to implement such approach for HNSW index: https://github.com/pgvector/pgvector/pull/266
So if filter needs more candidates, HNSWindex will provide them.
What do you think about this approach?


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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-17 19:13 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

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

@knizhnik It may expand the search radius, but we may not be seeing the best available vectors for a filter. For example, let's say that vectors with a specific filter (`category_id=5`) are clustered around a particularly neighborhood that's not actually close to the query vector -- if we expand the search, we may end up exhaustively searching the index until we find the best candidate vectors.

I don't know how much of an issue it would be in practice, but I still think it makes sense to try to tailor the search path towards vectors that are known to match a particular filter. Maybe after that it could make sense to expand the search radius if we're not finding enough vectors, but I'd need to think on it some more.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-17 19:41 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: knizhnik (@knizhnik) @ 2023-09-17 19:41 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Sorry, I do not completely understand your concern.
Assume that you have query mentions above: 
```
SELECT id, text FROM document WHERE category = $1 ORDER BY embedding <-> $2 LIMIT 10;
```
Plan is the following:
```
 Limit  (cost=4.48..51.74 rows=3 width=56)
   ->  Index Scan using document_embedding_idx on document  (cost=4.48..51.74 rows=3 width=56)
         Order By: (embedding <-> '[1,2,3]'::vector)
         Filter: (category = 'first'::text)
```
We ask hens index to return tuples in order of increasing distance and then apply filter until 10 results are found.
So we can 't "end up exhaustively searching the index until we find the best candidate vectors". We will repeat HNSW search once and once again with increased `ef_search` until 10 documents with specified category are found.
There're two main drawbacks:
1. Repeating index search will definitely increase query execution time.
2. Returned results are not always in distance ascending order.
But we can not return i.e. 5 results if there are 10 or more records of the specified category doesn't;t matter how far them are from specified vector.






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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-18 08:53 ` "fanfuxiaoran (@fanfuxiaoran)" <noreply+fanfuxiaoran@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: fanfuxiaoran (@fanfuxiaoran) @ 2023-09-18 08:53 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@jkatz  Your approach of creating multiple columns index to support attribute filtering looks good to me. 
>Finally, in the case we have a category_id present, I wonder if we can store the values in the lists themselves in a B-tree structure, so that way we can go directly to those values.

I think storing the values in the lists themselves in a B-tree structure would have a bad performance as the size of the vector struct is big and we need to read the pages randomly to compute the distances for a specific list as the `category_id` that in the same list may be distributed in different pages.

>HNSW -- effectively keeping two pairs of links in a "multi-column" style index

It could work when the predicate is '=',  but how about '>' or '<'?
 I have another idea about HNSW index, which is similar to ivfflat index.  We need to maintain such info in HNSW index: given a TID we can directly get its entry point in different layers. When fetching the index, first get the 'TID's ( the base heap table TID)   that matches the attribute filter. Then fetch the entry points for those 'TID's. Finally, choose the entry point in each layer based on the vector distance to the query vector and those 'TIDs to do search.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-20 00:37 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: jkatz (@jkatz) @ 2023-09-20 00:37 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> I think storing the values in the lists themselves in a B-tree structure would have a bad performance as the size of the vector struct is big and we need to read the pages randomly to compute the distances for a specific list as the category_id that in the same list may be distributed in different pages.

In this case, the size of an `int4` is nothing compared to the size of a vector, so I don't see this being a practical concern. Additionally, I don't see the random pages being a concern either -- the pages themselves are already clustered together in the index (at least at creation), whereas the random reads occur once we read values from the heap.

The bulk of the work is handled when pruning the lists: we know that `N` lists contain `category_id`, so we only have to review those lists. Given we'd have to scan all the pages in a given list, we can at least skip vector comparisons on index entries that do not match `category_id`. While it does not filter everything, it allows us to visit fewer lists and perform vector calculations on fewer candidates.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-20 05:42 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: knizhnik (@knizhnik) @ 2023-09-20 05:42 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

The problem we are trying to solve is not specific for HNSW/IVFFLAT indexes. It is universal problem of multidimensional search with heterogeneous  dimensions. Imagine that you find the nearest restaurant with the highest rating and preferable Italian cuisine. How to compare distance with rating? Is it better to go 100m more to reach restaurant with score 4.5 instead of 3.7? Or French restaurant 0.5km closer is better? Looks like CS is not able to provide something better for such multicriteria search rather than K-D Tree. But it is not self balanced and not working for large number of dimensions...

Postgres provides GIN (Generalised Inverted Index) which can be used for full text search. It idea is very similar with IVFFLAT. Here we also have the problem with multidimensional search (assume that we want to find document containing some keywords published before some date). My former colleagues proposed VODKA index: https://www.pgcon.org/2014/schedule/events/696.en.html which is actually two dimensional index, using B-Tree for posting lists. But it is still not able to solve all problems with multidimensional search...

Right now if you need to combine several search  criteria, Postgres can propose only two approaches:
1. Filtered index scan (you perform index search using one criteria and filter records matching another criteria).
2. Bitmap scan (index scans construct bitmap which you can then intersect or union and use for heap scan)

First approach is not working well for HNSW because it returns limited (K) number of results.
Second approach is not possible because we need to return records undesired order. It will be nice if we can test bitmap inside index AM, but right now it is not possible. 

So how can we address this problem with HNSW/IVFFLAT?
1. Provide iterator which returns all recordist distance descending order (as it is done in Postgres GIST KNN implementation). Now sure if it is possible for HNSW...
2. Somehow push down search predicate to HNSW index so it can filter records while search. Postgres index AM doesn't support it. Certainly we can define some executors hook and analyze query plan, trying to locate our indexscsan node pin this tree and extra top level predicates. But it is very non trivial and hacky. 
3. Propose some combined index structure (like K-D tree) which will be able to perform such multidimensional search. It seems to be most efficient solution. But at the same time - most difficult to implement. 
4. Somehow managed to add extra attributes (like `category_id`) to the embedding vector.
5. Repeat search with increased K value to provide more candidates. This is most compromise approach implemented in my PR. 

And last note: most likely it will be necessary to perform search with and without extra criteria. For example, we can look for documents of particular category or perform search through all documents. Maintaining two different indexes seems be be quite expensive solution.


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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-09-20 19:51 ` "pashkinelfe (@pashkinelfe)" <noreply+pashkinelfe@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: pashkinelfe (@pashkinelfe) @ 2023-09-20 19:51 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@jkatz 

> It may expand the search radius, but we may not be seeing the best available vectors for a filter. For example, let's say that vectors with a specific filter (category_id=5) are clustered around a particularly neighborhood that's not actually close to the query vector -- if we expand the search, we may end up exhaustively searching the index until we find the best candidate vectors.

I agree that filtering without this would always be a compromise that will fail to output proper results if a filtering attribute will reject the number of nodes passing the filter significantly. So we need to build `M*Ncat` links where `Ncat` is the number of possible filtering categories (instead of existing HNSW parameter of number of links per node `M`). The number of links is not expected to bloat the index much as multidimensional vector size is big enough compared to `M` (or `M*Ncat`) links. But strictly implementing this we can get adding new values of `category_id` to be resource resource-intensive.

Automatically repeating search with increased ef_search if we get less vector, as @knizhnik proposed in https://github.com/pgvector/pgvector/pull/266, I think is a different and easier optimization that can help with getting less results from HNSW due to dead tuples in the heap. I think it's safe enough to be included. 

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-10-25 12:39 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: mgoldenbe (@mgoldenbe) @ 2023-10-25 12:39 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@Palmik

> Partial index on all possible categories is also unfortunately not feasible

I have similar requirements, whereby search needs to be conducted only on documents belonging to a particular user. Why might it not be feasible to automatically create an index whenever a new user joins (or a new category is created in your case)?

In my own case, the difficulty is that users can share documents, so I have a separate table for storing documents and a separate table for storing ownership information, i.e. `(<user id>,<document id>)` pairs.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-10-25 12:44 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: mgoldenbe (@mgoldenbe) @ 2023-10-25 12:44 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@jkatz 

> To look up from both indexes at the same time, pgvector would have to add support for bitmap scans in `hnsw`.

Why not simply force the desired behavior in the query itself by using a subquery in `FROM`? For example, the subquery might compute the table filtered using the regular index, while the outer query would operate on the filtered table. 

If this approach works, does it still require a separate partial index for each category or would it work even with a single full index?

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-10-25 13:18 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: mgoldenbe (@mgoldenbe) @ 2023-10-25 13:18 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@jkatz 

I did not understand from your original reply what the current behavior is for the query in the question. Would it do filtering during the KNN search, i.e. similarly to [how it is implemented in Elastic Search](https://discuss.elastic.co/t/pre-filter-knn-vector-search/341585)? And if so, then, when there are thousands of categories, is this approximate KNN search any faster than brute-force exact KNN search within the category of interest? 

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-10-25 14:00 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: knizhnik (@knizhnik) @ 2023-10-25 14:00 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> @jkatz
> 
> I did not understand from your original reply what the current behavior is for the query in the question. Would it do filtering during the KNN search, i.e. similarly to [how it is implemented in Elastic Search](https://discuss.elastic.co/t/pre-filter-knn-vector-search/341585)? And if so, then, when there are thousands of categories, is this approximate KNN search any faster than brute-force exact KNN search within the category of interest?

It was not question to me, but I can answer: no filtering is not done inside KNN search.
So first you perform ANN search and return efSearch closest result and then apply filter to it.
Obviously it may return less results than expected. Ornate return any results at all.

Postgres index access method API doesn't allow to push filter in this case.

This is why I proposed PR where index search returns as much results as requested (iterator).


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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-10-25 14:07 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: mgoldenbe (@mgoldenbe) @ 2023-10-25 14:07 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@knizhnik 

What will happen if I use a subquery as proposed in my other question to @jkatz?

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-10-25 14:15 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: knizhnik (@knizhnik) @ 2023-10-25 14:15 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Subquery can not somehow help. There are two different indexes: HNSW index by embedding and B-Tree by category.
You can not use both indexes in your query if you want to satisfy both conditions (except using bitmap scan).
So you have either perform search by category and then sort all selected records by embedding distance.
Either get records in distance increasing order and filter out once belonging to the particular category.

If number of categories is small and fixed, then creating partial index for each category may help. By in general case it doesn't work.

So there are three working solutions:
1. Brute-force search
2. Dynamically increase`efSearch` to get required number of results
3. Return iterator which can provide arbitrary number of results.

3) seems to be the best choice. And I have implemented in my PR.


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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-10-25 15:10 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: mgoldenbe (@mgoldenbe) @ 2023-10-25 15:10 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@knizhnik 

Why can't the partial index approach work when the number of categories is both large and non-fixed? In particular:

1. **Large**. There is no limit on the number of indices one can have on one table.
2. **Non-fixed**. One can automatically create a new index as soon as a new category is added. This should be very fast, since the there no documents in the new category as of yet.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-10-25 19:15 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: knizhnik (@knizhnik) @ 2023-10-25 19:15 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Because partial index should be created manually for each category value. It is very inconvenient and not so efficient.


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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-10-26 08:32 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: mgoldenbe (@mgoldenbe) @ 2023-10-26 08:32 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@knizhnik 

Why manually? Can't you run `CREATE INDEX` from your backend code such as Django?
Why would partial indexes become inefficient when there are many of them?

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-10-26 08:48 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: knizhnik (@knizhnik) @ 2023-10-26 08:48 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Certainly you can automate creation of indexes. 
But what if new category is added? Once again - you can create trigger which creates index but ...

If there are ~100 categories, then it can be acceptable. But for larger number of categories - I expect that overhead (including planning time) will be quite large. Also if you create partial index for each category value, then you will note able to rung queries `where category > 100` or `where category in (1,2,3)`
 

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-10-26 09:39 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: mgoldenbe (@mgoldenbe) @ 2023-10-26 09:39 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@knizhnik 

> But what if new category is added? Once again - you can create trigger which creates index but ...

Either a trigger, or do `CREATE INDEX` just like you do `INSERT INTO` to insert the new category.


> But for larger number of categories - I expect that overhead (including planning time) will be quite large.

Why isn't the partial index creation time `O(1)`? Why should it depend on the number of partial indices that already exist?


> Also if you create partial index for each category value, then you will note able to rung queries `where category > 100` or `where category in (1,2,3)`

I run only `where category = some_category`. But regardless, why would `where category in (1,2,3)` not work? As for `where category > 100`, it would probably just not use the indices.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-10-28 17:08 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: mgoldenbe (@mgoldenbe) @ 2023-10-28 17:08 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@jkatz 

You did not mention [table partitioning](https://github.com/pgvector/pgvector#filtering) in your answer here. If I understand correctly, if the table uses *list partitioning* on the `category_id` column, then the condition `WHERE category_id = 3` will cause it to only consult the HNSW index for that partition. Doesn't this completely solve the problem? 

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-10-28 18:49 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: knizhnik (@knizhnik) @ 2023-10-28 18:49 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

It will solve the problem if
1. You can  create partition for each category (this number can be very large)
2. There are no queries involving multiple partitions, i.e. `select * from document where category = in (1.2.3) order by embedding <-> ...`

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-10-29 08:16 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: mgoldenbe (@mgoldenbe) @ 2023-10-29 08:16 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@knizhnik 

> You can create partition for each category (this number can be very large)

- Aren't partitions created automatically once the table is created with list partitioning?
- What's the problem with 1,000 partitions for a table with a billion rows?

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-10-29 18:59 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: knizhnik (@knizhnik) @ 2023-10-29 18:59 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> Aren't partitions created automatically once the table is created with list partitioning?
No, you have explicitly specify list of values for which partition is created.

> What's the problem with 1,000 partitions for a table with a billion rows?
Optimiser has to analyse 1000 tables which takes ~1000 more times than for select from single table.



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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-11-06 22:45 ` "jeff-davis (@jeff-davis)" <noreply+jeff-davis@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: jeff-davis (@jeff-davis) @ 2023-11-06 22:45 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

# Proposal

I'd like to organize a few of the ideas in this thread along with my
own thoughts into a proposal. This is still rough and I need to look
at a lot of code details, but I'd like some feedback.

# Problem Statement

Support queries of the form:

```                                                                                                                                
SELECT ... WHERE category_id = 1234 ORDER BY embedding <-> $1                                                                      
```                                                                                                                                

for an index defined as:

```
CREATE INDEX ON items USING hnsw (embedding vector_l2_ops, category_id)                                                            
```                                                                                                                                

No more than a few scalar attributes are expected along
with the vector.

# Summary

Maintain many HNSW graphs within one index object (i.e. a single
`pg_class` entry). Vector data is shared to avoid unnecessary
duplication. Each HNSW graph would be applicable to the subset of rows
that match a filter condition. (Similar, I believe, to what @jkatz
suggests[^1][^2]).

A scalar index (i.e. btree) would be first used to select the right
HNSW graph based on the filter conditions available from the query,
and then the search follows that graph's entry point.

For common data sets, many of the HNSW graphs would be a single
element or very few elements -- for example, the HNSW graph for the
subset of rows matching a highly selective filter condition. These
would be degenerate HNSW graphs consisting of a single neighborhood,
and we'd need to be sure these simple cases do not have unnecessary
storage overhead. But also, even within the same data set, some HNSW
graphs will be very large -- e.g. the HNSW graph for the subset of
rows matching an unselective filter condition; or the HNSW graph
representing no filter conditions at all.

# Notes

This proposed approach is briefly discussed in section 1.2 of
Filtered-DiskANN[^3] ("a trivial pre-processing method that builds a
separate index for each possible filterable
label..."). Filtered-DiskANN dismisses this approach because it's
"prohibitively expensive in scenarios with a large number of
filters...". But for our purposes we only need to filter on a few
attribtues (e.g. `category_id`) in addition to the vector. I consider
filtering on a large number of possible labels to be a different
problem.

To simplify planning, we introduce two limitations (though these can
be lifted with additional planning work):
1. The vector attribute is listed first among the attributes in the
   index definition, despite logically being secondary in the search
   process.
2. Only a prefix of the attributes defined in the index will be
   usable, similar to a btree (so, an index on `(V, A1, A2)` could be
   queried on `(V, A1, A2)`, `(V, A1)`, or just `V`; but not
   `(V, A2)`). NB: this limitation may negatively impact query recall.

To avoid engineering complexities from introducing a btree, we can
also consider using ideas from HQANN[^4], which allows mixing scalar
and vector types in the same index using a modified distance function.

# Algorithms

Assuming an index on attributes (V, A1, .., AN), where `V` is a vector
attribute and `A1`, ..., `AN` are scalar attributes with btree
opclasses.

`*` is a special token meaning that the attribute in the tuple is
unspecified; i.e. not part of a filter available from the query.

## Insert `tuple T (v, a1, .., aN)`

```                                                                                                                                
# with planner improvements, could generate all combinations of                                                                    
# scalar attributes, but for now just generate all prefixes                                                                        
For i in 0..N:                                                                                                                     
  # fill in attributes 1..i with values from the inserted tuple                                                                    
  # and fill in attributes i..N with '*'                                                                                           
  tuple partialT = (a1, .., ai, *, ...)                                                                                            
  G <- use partialT to search scalar index for HNSW graph                                                                          
  if G == NULL: initialize G and insert into scalar index                                                                          
  Insert T into G                                                                                                                  
```          
                                                                                                                      
## Delete `tuple T (v, a1, .., aN)`

```                                                                                                                                
# with planner improvements, could generate all combinations of                                                                    
# scalar attributes, but for now just generate all prefixes                                                                        
For i in 0..N:                                                                                                                     
  # fill in attributes 1..i with values from the inserted tuple                                                                    
  # and fill in attributes i..N with '*'                                                                                           
  tuple partialT = (a1, .., ai, *, ...)                                                                                            
  G <- use partialT to search scalar index for HNSW graph                                                                          
  Assert G != NULL                                                                                                                 
  Delete T from G                                                                                                                  
  if G is empty:                                                                                                                   
    Delete partialT from scalar index                                                                                              
```                                                         
## Query `WHERE A1 = C1 AND ... AJ = CJ ORDER BY V <-> $1`

```                                                                                                                                
  # ignore attributes that aren't a prefix of the index definition                                                                 
  # until the planner can support them                                                                                             
  M = MIN(J, N)                                                                                                                    
                                                                                                                                   
  # fill in attributes 1..M with filters from the query                                                                            
  # and fill in attributes M+1..N with '*'                                                                                         
  tuple partialT = (a1, .., aM, *, ...)                                                                                            
  G <- use partialT to search scalar index for HNSW graph                                                                          
  Use v to search G and return nearest neighbors                                                                                   
```

[^1]: https://github.com/pgvector/pgvector/issues/259#issuecomment-1719622821
[^2]: https://github.com/pgvector/pgvector/issues/259#issuecomment-1716258158
[^3]: https://harsha-simhadri.org/pubs/Filtered-DiskANN23.pdf
[^4]: https://arxiv.org/pdf/2207.07940.pdf


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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-11-07 02:06 ` "ankane (@ankane)" <noreply+ankane@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: ankane (@ankane) @ 2023-11-07 02:06 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Hi @jeff-davis, thanks for the proposal.

I agree with the problem statement and was thinking the same for the attribute order (vector column first), even though it's different from b-tree (where filtering columns come first).

For the approach, I'm hoping we can avoid the complexity of multiple graphs by using HQANN. I've started some prototyping on this and think it can be done with a single change to the on-disk format (reinterpreting `vec` as an `IndexTuple` when `IndexRelationGetNumberOfAttributes(index) > 1`).

I also think it may allow for searching any combination of the attributes (`(V, A1)` and `(V, A2)`), not just the leading ones.

Will spend some more time on it this week to try and have something to share.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-11-07 04:58 ` "jeff-davis (@jeff-davis)" <noreply+jeff-davis@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: jeff-davis (@jeff-davis) @ 2023-11-07 04:58 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> Hi @jeff-davis, thanks for the proposal.
> For the approach, I'm hoping we can avoid the complexity of multiple graphs by using HQANN. I've started some prototyping on this and think it can be done with a single change to the on-disk format (reinterpreting `vec` as an `IndexTuple` when `IndexRelationGetNumberOfAttributes(index) > 1`).

I was originally planning to propose something related to HQANN, so I look forward to reading your design. I looked at it as a way to simplify some engineering challenges (one type of index, one disk structure, etc.), but what I intended to propose was essentially the same (mathematically) as the btree approach that I did propose. The idea I had was to turn scalar attributes into a number by hashing, and ensure that the scalar hash always dominated the vector distance in the overall distance calculation, which is a simplification of the HQANN approach. That would make the top few levels look like a skip list, and lower levels look like a proper HNSW, but it would all be in one HNSW graph with one entry point.

The reason I ended up proposing the btree approach is that it seemed simpler to explain. Whether the end result is simpler using a btree or HQANN will probably revolve around the details, so I can't say for sure that one is simpler than the other. I am happy with either approach at a high level.

> I also think it may allow for searching any combination of the attributes (`(V, A1)` and `(V, A2)`), not just the leading ones.

That would be possible in either approach. The above proposal (with slight modification) allows for enumerating all subsets of scalar attributes, and using similar partial tuples with `*` markers in the btree keys.

The challenge is not so much in storage or execution, but in planning, I believe. We either need to make the planner aware that the index will work for any subset, or we need to inject such paths ourselves. To do this "right" also involves handling parameterized paths. I believe we can and should do all of this, but it's extra work and we can start simply (i.e. prefixes only, then combinations, then parameterized combinations).

> Will spend some more time on it this week to try and have something to share.

Great!


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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-11-07 06:42 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: knizhnik (@knizhnik) @ 2023-11-07 06:42 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I just want to notice that the proposed approach (with `(embedding vector_l2_ops, category_id)` index) will work only f when query contains exact match predicate for category, i.e.
```
SELECT ... WHERE category_id = 1234 ORDER BY embedding <-> $1;
```
It will not work (index can not be applied) in the following cases:
```
SELECT ... WHERE category_id in (1,2,3,4) ORDER BY embedding <-> $1;
SELECT ... WHERE category_id > 1234 ORDER BY embedding <-> $1;
SELECT ... ORDER BY embedding <-> $1;
```

Certainly we can merge results obtained  from multiple indexes. But it leads to a lot of redundant work and in case where there is not restriction on category becomes extremely ineffcieint.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-11-07 13:41 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: jkatz (@jkatz) @ 2023-11-07 13:41 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

From talking to pgvector users, the most common query pattern in this case is `=`. I've seen a handful of `IN (...)`, and I have not seen inequality. If we can build something that handles the most common case while leaving the door open for handling the others, I think that's a big step forward.

Also, the approach outlined above handles the currently supported case of `SELECT ... ORDER BY ...`, otherwise I don't even think we could consider it.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-11-10 04:05 ` "pomnb (@pomnb)" <noreply+pomnb@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: pomnb (@pomnb) @ 2023-11-10 04:05 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

hope support (id, embedding) index 

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-11-10 21:35 ` "ankane (@ankane)" <noreply+ankane@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: ankane (@ankane) @ 2023-11-10 21:35 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Pushed an initial version to the [hqann branch](https://github.com/pgvector/pgvector/compare/hqann). Still need to clean up the code and do more testing, but it should provide an overall idea of the design.

(also, if testing, use cosine distance for now)

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-11-14 07:29 ` "suppersam1 (@suppersam1)" <noreply+suppersam1@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: suppersam1 (@suppersam1) @ 2023-11-14 07:29 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

[7084_an_efficient_and_robust_framew.pdf](https://github.com/pgvector/pgvector/files/13345677/7084_an_efficient_and_robust_framew.pdf)
Perhaps we can take a look at this paper.This paper proposes a concept of mixed distance, which converts attribute columns into vectors and mixes the distance between the vector column.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-12-04 05:50 ` "29swastik (@29swastik)" <noreply+29swastik@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: 29swastik (@29swastik) @ 2023-12-04 05:50 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@jkatz 
We also have similar requirements where we have documents uploaded for different bots and when a query comes from end user SQL would look like below (in our case there will be only `=` not `IN` on **bot_number**)

> SELECT id, text FROM document WHERE bot_number = $1 ORDER BY embedding <-> $2 LIMIT 10;

For now we are solving this by having separate table for each bot

> SELECT id, text FROM document_bot_number ORDER BY embedding <-> $2 LIMIT 10;

But this might not be efficient in long run, so is creating hash partition on **bot_number** a good idea?



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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2023-12-04 23:03 ` "rajbakhru-aptr (@rajbakhru-aptr)" <noreply+rajbakhru-aptr@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: rajbakhru-aptr (@rajbakhru-aptr) @ 2023-12-04 23:03 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Any chance we can get this into 0.5.2?  Would be a major improvement!
@ankane - how can we help?

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-01-15 16:07 ` "ianwoodfill (@ianwoodfill)" <noreply+ianwoodfill@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: ianwoodfill (@ianwoodfill) @ 2024-01-15 16:07 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

We're very excited about this feature, would be really useful for our use case. Wondering if this is something that will likely be shipped and what the timeline might be?

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-01-15 20:12 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

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

@ianwoodfill Are you able to share more about your use case? Would you be able to test https://github.com/pgvector/pgvector/tree/hqann and see if it helps?

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-01-22 21:33 ` "williamhakim10 (@williamhakim10)" <noreply+williamhakim10@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: williamhakim10 (@williamhakim10) @ 2024-01-22 21:33 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@jkatz this is very awesome work. I dumped a portion of our production database and installed the branch locally, and it works like a charm. The query planner uses the index as expected, although sadly it uses a `Filter` rather than an `index_cond` when you chain multiple `=` predicates with `OR`. Presumably this is because the query planner thinks it'll be faster (which it probably is) but doesn't know that this actually gives you different results. (That would truly be a killer feature FWIW, because presumably if you have too many possible predicates to create a partial index on each one, then you may want to query against more than one at the same time.)

I did notice that it only supports integers at present; that worked mostly fine for our use case (and obviously it's unreasonable to expect documentation of unreleased features), but good to know.

Any idea how we can help with this, or do you have any idea when we're likely to see this get merged in?

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-02-07 06:26 ` "yekta (@yekta)" <noreply+yekta@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: yekta (@yekta) @ 2024-02-07 06:26 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

We tried pgvector a 5-6 months ago and decided to go with Qdrant and after some testing. Now we've been testing it again to see if it's enough for our use case. We really really want it to work given we are already using Postgres. However, filtering problems are a deal breaker for us as well. We would appreciate if there is a solution to this.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-02-27 13:31 ` "jcodella (@jcodella)" <noreply+jcodella@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: jcodella (@jcodella) @ 2024-02-27 13:31 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Friendly ping @ankane, is there any plan to release filtering support via HQANN soon? We'd like to do some development work using this at Microsoft, and our initial testing looks very promising. It would helpful to know if there's a timeline or plan to merge? Any way we can assist here?

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-02-28 05:02 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: jkatz (@jkatz) @ 2024-02-28 05:02 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> and our initial testing looks very promising.

Can you share your testing methodology and any results that you have?

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-03-05 13:12 ` "lambda-science (@lambda-science)" <noreply+lambda-science@github.com>
  88 siblings, 0 replies; 90+ messages in thread

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

Is there any news about this 👀 I wish to use PGVector as Vector database but filters are crucials for my use-case.
Maybe a good example of such filter could be taken from OpenSearch efficient filtering ?
https://opensearch.org/docs/latest/search-plugins/knn/filter-search-knn/#using-a-faiss-efficient-fil...
It's basically what has been proposed here
- Pre-filter, if after filter the number of doc (P) is under a set treshold (FT, for example 50 000 docs): do bruteforce search
- If not, do approximate search with HNSW index over all doc but only add doc matching filter to the results (R, post-filtering)
- If resulting docs (R) >K # Good, it worked !
- Elif resulting docs (R) <K # Perform brutefoce search on docs pre-filtered - last resort ; very expensive

It's a mix of pre-filter, post-filter and smart choice between approximate search and brute-force search.
![image](https://github.com/pgvector/pgvector/assets/20109584/38c9d646-d26b-4d32-bafc-7a30395fdd95)



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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-03-05 13:54 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: jkatz (@jkatz) @ 2024-03-05 13:54 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@lambda-science Can you provide more info about your use-case? There are already several ways to pre-filter with PostgreSQL + pgvector today, including [partitioning and using partial indexes](https://github.com/pgvector/pgvector?tab=readme-ov-file#filtering), as well as post-filtering. It'd help to understand the size of your data set / storage pattern to see if it'd benefit from additional pre-filtering support.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-03-05 16:18 ` "ianwoodfill (@ianwoodfill)" <noreply+ianwoodfill@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: ianwoodfill (@ianwoodfill) @ 2024-03-05 16:18 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I'll chime in with a potentially relevant use case.

We store vector representations of text files in a hierarchical file system represented in postgres. We have a `folder` table that can be infinitely nested, and a `file` table with the documents themselves and their vector representations.

We run a vector search on parts of these tables in unpredictable patterns, defined by end-users. For example, a user might do a vector search within a certain folder and its subdirectories/contents, or even multiple folders. We use a recursive CTE to determine the file search space, and do a vector similarity search on that.

This query pattern has made it very difficult to efficiently use indices/partinioning, since the best we can do is at the file-system level (each end-user gets their own file system).

We found that queries often incorrectly choose to use or not use the index, resulting in query timeouts or low recall. We've discussed manually implementing solutions like @lambda-science suggested, imagining that would work better for our use case.

We've currently resolved to relying on KNN, and instead using hardware with high disk throughput to avoid losing recall and improve query speeds. Obviously this is not super scalable.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-03-05 16:31 ` "williamhakim10 (@williamhakim10)" <noreply+williamhakim10@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: williamhakim10 (@williamhakim10) @ 2024-03-05 16:31 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

The flow-chart by @lambda-science is relatively easy to implement by simply writing your own logic; just slightly modify your query to force the planner to brute-force depending on the scenario. For example, you can do something like this to force brute-force:
```
select 1 - (embedding <=> {your embedding}) cosine_similarity
...
order by cosine_similarity desc
```
The real issue isn't forcing the query planner to use brute force in situations in which you already know ANN will return <K results, it's that brute force isn't realistic once you start getting to hundreds of millions of vectors within a reasonable time frame.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-03-06 08:24 ` "lambda-science (@lambda-science)" <noreply+lambda-science@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: lambda-science (@lambda-science) @ 2024-03-06 08:24 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> @lambda-science Can you provide more info about your use-case? There are already several ways to pre-filter with PostgreSQL + pgvector today, including [partitioning and using partial indexes](https://github.com/pgvector/pgvector?tab=readme-ov-file#filtering), as well as post-filtering. It'd help to understand the size of your data set / storage pattern to see if it'd benefit from additional pre-filtering support.

My use case is that we have two type of search:

- 90% of the vector database (1M vectors) is avaliable to all user, like "technical documentation". 
- 10% is private vector by users (100k, for example 10 user, each having 10 000 privates vectors), like "my own very private doc".

For the search on the first 90% public, I would do HSNW on ALL the database but there are two issues:
- What if among user private document one user uploaded something very similar to my query and now my 10 top_k are coming from with user results ? With full HNSW + post-filtering I have no results anymore.
- What if actually among these 90% documents I Want to add additionnal filter because it's hard for me to find the relevant document and we want to use more filter ? I would have to plan all filtering pattern and build partial HNSW for each categories.
- What if one day my DB grows a lot and now I have 45% (1M vector) technical documents, 45% (1M Vector) legal documents. I can't do full HNSW search anymore because there is too much risk my top_k is small with post-filtering. I have to *manually* build partial HNSW

For the search on the last 10% private doc, I could do pre-filtering + brute-force yes. Small caveat if someday one user has a loooot of vectors.

Basically our use-case is answering very precise technical documentation about products. So we want to apply as much filter as possible to limit the search space  (product name, product version, country...) and irrelevant informations. Maybe we can do bruteforce in this case.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-06 19:52 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: mauriciocirelli (@mauriciocirelli) @ 2024-05-06 19:52 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I have a similar use case.
We have documents splitted into categories and owners. A user may only query documents that they are allowed to (by owners filtering).
We have solved this issue by creating partitions on the categories list and an index on the owners.

It is working fine, as we have just about 20k documents. But multi-key indexing would be insanely appreciated.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-07 11:18 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: mauriciocirelli (@mauriciocirelli) @ 2024-05-07 11:18 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Another thing that I am seeing when having more filters on the query is the behavior of the LIMIT clause. This table is partitioned by category and we have an index on owner_id and another index on the embedding (HSNW).

```sql

WITH pre_filtered_docs AS (
	SELECT * FROM documents
	WHERE
	((category = ('cat-a')) AND (owner_id IN (1, 2, 3)))
	OR
	((category = ('cat-b')) AND (owner_id IN (4, 5, 6)))
)
SELECT category, owner_id, text, embedding <=> '[vector to query]' as distance
FROM pre_filtered_docs
ORDER BY distance
LIMIT 10;
```

```
QUERY PLAN
Limit  (cost=257.04..296.29 rows=10 width=48)
  ->  Merge Append  (cost=257.04..833.95 rows=147 width=48)
        Sort Key: ((documents.embedding <=> '[...]'::vector))"
        ->  Index Scan using documents_cat_a_embedding_idx on documents_cat_a documents_1  (cost=128.51..279.53 rows=14 width=48)
              Order By: (embedding <=> '[...]'::vector)
              Filter: ((((category)::text = 'cat-a'::text) AND (owner_id = ANY ('{1,2,3}'::integer[]))) OR (((category)::text = 'cat-b'::text) AND (owner_id = ANY ('{4,5,6}'::integer[]))))
        ->  Index Scan using documents_cat_b_embedding_idx on documents_cat_b documents_2  (cost=128.51..552.95 rows=133 width=48)
              Order By: (embedding <=> '[...]'::vector)
              Filter: ((((category)::text = 'cat-a'::text) AND (owner_id = ANY ('{1,2,3}'::integer[]))) OR (((category)::text = 'cat-b'::text) AND (owner_id = ANY ('{4,5,6}'::integer[]))))
```

Since I have an OR condition on the subquery, I would expect that this query would bring at least the same number of documents it brings without that OR. However, I see that if I remove one of those conditions, I get 10 docs. If I keep them both, I get less docs.

How is it possible? It should be an additive filter (OR) and return at least the same number of docs.

Interestingly, this is happening only on PG v15 (our production deployment). I have PG v16 on a docker container in my local machine for development and it works as expected.

The query planner is ver different:

```
QUERY PLAN
Limit  (cost=382.12..382.14 rows=10 width=48)
  ->  Sort  (cost=382.12..382.48 rows=146 width=48)
        Sort Key: ((documents.embedding <=> '[...]'::vector))
        ->  Append  (cost=36.32..378.96 rows=146 width=48)
              ->  Bitmap Heap Scan on documents_cat_a documents_1  (cost=36.32..56.99 rows=14 width=48)
                    Recheck Cond: ((owner_id = ANY ('{1,2,3}'::integer[])) OR ((category)::text = 'cat-b'::text))
                    Filter: ((((category)::text = 'cat-a'::text) AND (owner_id = ANY ('{1,2,3}'::integer[]))) OR (((category)::text = 'cat-b'::text) AND (owner_id = ANY ('{4,5,6}'::integer[]))))
                    ->  BitmapOr  (cost=36.28..36.28 rows=14 width=0)
                          ->  Bitmap Index Scan on documents_cat_a_owner_id_idx  (cost=0.00..31.99 rows=14 width=0)
                                Index Cond: (owner_id = ANY ('{1,2,3}'::integer[]))
                          ->  Bitmap Index Scan on documents_cat_a_pkey  (cost=0.00..4.29 rows=1 width=0)
                                Index Cond: ((category)::text = 'cat-b'::text)
              ->  Seq Scan on documents_cat_b documents_2  (cost=0.04..321.24 rows=132 width=48)
                    Filter: ((((category)::text = 'cat-a'::text) AND (owner_id = ANY ('{1,2,3}'::integer[]))) OR (((category)::text = 'cat-b'::text) AND (owner_id = ANY ('{4,5,6}'::integer[]))))

```

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-08 14:41 ` "williamhakim10 (@williamhakim10)" <noreply+williamhakim10@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: williamhakim10 (@williamhakim10) @ 2024-05-08 14:41 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> Another thing that I am seeing when having more filters on the query is the behavior of the LIMIT clause. This table is partitioned by category and we have an index on owner_id and another index on the embedding (HSNW).
> 
> ```sql
> WITH pre_filtered_docs AS (
> 	SELECT * FROM documents
> 	WHERE
> 	((category = ('cat-a')) AND (owner_id IN (1, 2, 3)))
> 	OR
> 	((category = ('cat-b')) AND (owner_id IN (4, 5, 6)))
> )
> SELECT category, owner_id, text, embedding <=> '[vector to query]' as distance
> FROM pre_filtered_docs
> ORDER BY distance
> LIMIT 10;
> ```
> 
> ```
> QUERY PLAN
> Limit  (cost=257.04..296.29 rows=10 width=48)
>   ->  Merge Append  (cost=257.04..833.95 rows=147 width=48)
>         Sort Key: ((documents.embedding <=> '[...]'::vector))"
>         ->  Index Scan using documents_cat_a_embedding_idx on documents_cat_a documents_1  (cost=128.51..279.53 rows=14 width=48)
>               Order By: (embedding <=> '[...]'::vector)
>               Filter: ((((category)::text = 'cat-a'::text) AND (owner_id = ANY ('{1,2,3}'::integer[]))) OR (((category)::text = 'cat-b'::text) AND (owner_id = ANY ('{4,5,6}'::integer[]))))
>         ->  Index Scan using documents_cat_b_embedding_idx on documents_cat_b documents_2  (cost=128.51..552.95 rows=133 width=48)
>               Order By: (embedding <=> '[...]'::vector)
>               Filter: ((((category)::text = 'cat-a'::text) AND (owner_id = ANY ('{1,2,3}'::integer[]))) OR (((category)::text = 'cat-b'::text) AND (owner_id = ANY ('{4,5,6}'::integer[]))))
> ```
> 
> Since I have an OR condition on the subquery, I would expect that this query would bring at least the same number of documents it brings without that OR. However, I see that if I remove one of those conditions, I get 10 docs. If I keep them both, I get less docs.
> 
> How is it possible? It should be an additive filter (OR) and return at least the same number of docs.
> 
> Interestingly, this is happening only on PG v15 (our production deployment). I have PG v16 on a docker container in my local machine for development and it works as expected.
> 
> The query planner is ver different:
> 
> ```
> QUERY PLAN
> Limit  (cost=382.12..382.14 rows=10 width=48)
>   ->  Sort  (cost=382.12..382.48 rows=146 width=48)
>         Sort Key: ((documents.embedding <=> '[...]'::vector))
>         ->  Append  (cost=36.32..378.96 rows=146 width=48)
>               ->  Bitmap Heap Scan on documents_cat_a documents_1  (cost=36.32..56.99 rows=14 width=48)
>                     Recheck Cond: ((owner_id = ANY ('{1,2,3}'::integer[])) OR ((category)::text = 'cat-b'::text))
>                     Filter: ((((category)::text = 'cat-a'::text) AND (owner_id = ANY ('{1,2,3}'::integer[]))) OR (((category)::text = 'cat-b'::text) AND (owner_id = ANY ('{4,5,6}'::integer[]))))
>                     ->  BitmapOr  (cost=36.28..36.28 rows=14 width=0)
>                           ->  Bitmap Index Scan on documents_cat_a_owner_id_idx  (cost=0.00..31.99 rows=14 width=0)
>                                 Index Cond: (owner_id = ANY ('{1,2,3}'::integer[]))
>                           ->  Bitmap Index Scan on documents_cat_a_pkey  (cost=0.00..4.29 rows=1 width=0)
>                                 Index Cond: ((category)::text = 'cat-b'::text)
>               ->  Seq Scan on documents_cat_b documents_2  (cost=0.04..321.24 rows=132 width=48)
>                     Filter: ((((category)::text = 'cat-a'::text) AND (owner_id = ANY ('{1,2,3}'::integer[]))) OR (((category)::text = 'cat-b'::text) AND (owner_id = ANY ('{4,5,6}'::integer[]))))
> ```

If you look at your two query plans you'll see that the second one is doing a brute force search rather than using the index; this could be a difference between pg v15 and pg v16, but it also could be related to the amount of data you've got locally vs production. Either way the difference lies in the use of the HNSW index (or not).

I'm not really sure I understand your issue with the first query - the planner output seems to suggest that it's finding 14 results for the first condition and 133 results for the second one, and then limiting to 10 results as you requested?

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-08 14:54 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: mauriciocirelli (@mauriciocirelli) @ 2024-05-08 14:54 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Hi @williamhakim10 

Thanks for replying.
In order to make sure that the amount of data would not compromise the tests, I had dumped the production database to my local machine for testing (the tables that were actually used for this development). So, by the time of those tests, the amount of data on the documents table was the very same between both databases. The only difference was the PG version.

Regarding the limits, the first planner suggests it has found 14 and limited to 10. However, PGAdmin shows only 3 records, while it shows 10 on the production database with the second query planner provided.

It seems to me that on PG15, it was first searching for the 10 nearest neighbors and applying the category/owner filter on them, returning just 3 results (because the other 7 did not match the category/owner filters); while on PG16, it was first searching the documents by category/owner and, then, finding the 10 nearest neighbors, returning 10 results.

In these KNN queries, the order of the WHERE conditions matters a lot, as we have been discussing on this thread.

Redis solves this issue by splitting the query in a two steps: a pre-filter query and a KNN query. This leads to the expected results. I am seeing this only on PG16: it is using the category/owner index first and filtering by distance later.
On PG15, it is using the embedding index first and applying the category/owner filter later. This leads to results that are not what we expect (usually less results).



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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-08 15:10 ` "williamhakim10 (@williamhakim10)" <noreply+williamhakim10@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: williamhakim10 (@williamhakim10) @ 2024-05-08 15:10 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@mauriciocirelli you're seeing this result in the second query because the query *isn't using the index*. Because pgvector's indices don't do filtering for you, you're left with two options: filter all results by your condition and then do a brute-force reordering, or use the index to find nearest neighbors and then filter afterwards. You have to choose which approach you want. Admittedly the planner is a little opaque, and certainly postgres version differences could cause the planner to choose differently (although there are ways you can nudge it). If you always want to do brute-force search (like Redis) drop the HNSW index and you'll always get brute force.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-08 15:15 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
  88 siblings, 0 replies; 90+ messages in thread

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

Hi @williamhakim10 

Yes, I understand that. In the second query planner it has chosen to use the category/owner index instead of the HNSW index. So it was "brute-forcing" the distance, but only on a subset of the data.

But I have cases which a super-user could search for any document, so the owner index would not be used. In such cases, the HSNW index would be very helpful. Dropping it may cause a performance impact for super-users searches.

So, basically, it is up to postgres to decide which is the best index to use. I am fine with that and PG16 is doing it properly.

The issue is that on PG15, it is not returning the correct data. When I have "pre-filters", it is chosing a query planner that returns less results than I would expect (3 instead of 10) because it is applying the "pre-filters" after finding the 10 nearest neighbors.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-08 15:23 ` "williamhakim10 (@williamhakim10)" <noreply+williamhakim10@github.com>
  88 siblings, 0 replies; 90+ messages in thread

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

I'm not enough of a postgres expert to know for sure, but in my practical experience it's a bit tricky to reason about when the planner will choose to use a pgvector index, and when it won't. I wouldn't bank on the pg16 query plan remaining constant as your data changes. If you *always* want brute-force on filtered searches, I'd recommend using a descending-order sort which will skip the index (see my reply earlier: https://github.com/pgvector/pgvector/issues/259#issuecomment-1979171781)

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-08 15:27 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
  88 siblings, 0 replies; 90+ messages in thread

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

I totally agree with you. I cannot rely on the same query plan for every query at any point in the future.

What I am trying to understand is the behavior of the LIMIT clause. Why do I get 10 results in one scenario and only 3 on another, using the very same query and very same data?

We cannot rely on the plan being the same all the time, but I would expect that least that the results would be the same. In my understanding, different plans leads to different performance, but not to different results.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-08 15:33 ` "williamhakim10 (@williamhakim10)" <noreply+williamhakim10@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: williamhakim10 (@williamhakim10) @ 2024-05-08 15:33 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

This happens because (many of) the vectors that match your filter condition may not be particularly close neighbors of the original embedding, so the space explored by the HNSW index may not contain many matches.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-08 15:41 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: mauriciocirelli (@mauriciocirelli) @ 2024-05-08 15:41 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I do not agree with that.

The issue is related to the LIMIT clause. If I remove it, I get all results, as expected.
When I add a LIMIT clause to the outer query, I expect that it would process all the steps of the plan and, in the end, limit the results.

However, on PG15, it is limiting the inner query (HNSW query) too, which brings me only 10 nearest neighbors. Then, it applies the owner/category filter, returning less than 10 results.

Is there anything that I can do on my query or on my database to fix it?

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-08 15:45 ` "williamhakim10 (@williamhakim10)" <noreply+williamhakim10@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: williamhakim10 (@williamhakim10) @ 2024-05-08 15:45 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

The query plan shows that that isn’t what’s happening; the LIMIT is being applied at the end as you’d expect. What does the query plan look like without the LIMIT on pg15?

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-08 15:47 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: mauriciocirelli (@mauriciocirelli) @ 2024-05-08 15:47 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Exactly like the second query planner (the one I ran on PG16), without the first line (the LIMIT clause).

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-08 16:55 ` "williamhakim10 (@williamhakim10)" <noreply+williamhakim10@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: williamhakim10 (@williamhakim10) @ 2024-05-08 16:55 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> Exactly like the second query planner (the one I ran on PG16), without the first line (the LIMIT clause).

I'm not really sure what the question is then; if you don't specify a LIMIT then the index won't be used per the README. So you'll get different results.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-08 17:00 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: mauriciocirelli (@mauriciocirelli) @ 2024-05-08 17:00 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@williamhakim10 

The question is very straightforward.
I have many documents in several different categories. On PG15, a query returns 3 results, when I LIMIT to 10. On PG16, the same query returns 10 results.
If I do not use the LIMIT clause, either PG version return all related documents.

As I see on the plan, on PG15, it is using the HNSW index. On PG16, it is using the owner id index. 

It seems to me that on PG15, it is using the HNSW index and limiting its search to the 10 NN (from the LIMIT clause), while it should not do it. The LIMIT clause should be applied only on the final step, after all other filterings.

Why HNSW index is limiting its search on the inner query on PG15? This is what I am trying to understand and, if possible, workaround, to provide the correct results to the end application. The same query on the same data, should return the same results. In this case, 10 documents, because there are 10 documents that satisfy all the conditions.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-08 17:35 ` "ankane (@ankane)" <noreply+ankane@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: ankane (@ankane) @ 2024-05-08 17:35 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Hi @mauriciocirelli, check out the [troubleshooting docs](https://github.com/pgvector/pgvector?tab=readme-ov-file#why-are-there-less-results-for-a-query-after...). Also, please create a new issue for any additional questions to avoid notifying everyone in this thread.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-08 19:00 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: mauriciocirelli (@mauriciocirelli) @ 2024-05-08 19:00 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Ok, I may open another thread for this.

Sorry for bothering you all. My intention was to add to the discussion that the LIMIT clause may not be working as expected when we combine conditions with the HNSW index.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-05-24 13:14 ` "nickcanz (@nickcanz)" <noreply+nickcanz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: nickcanz (@nickcanz) @ 2024-05-24 13:14 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

👋 This seems like a use-case we could make use of. It looks like https://github.com/pgvector/pgvector/tree/hqann is somewhat out of date at this point, would y'all still find it useful if we ran some testing against this branch or wait until a new build exists?

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-06-21 09:10 ` "marv1nnnnn (@marv1nnnnn)" <noreply+marv1nnnnn@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: marv1nnnnn (@marv1nnnnn) @ 2024-06-21 09:10 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Any updates on the hqann implementation? We are using GCP CloudSQL for PostgreSQL now, and the lack of pre-filtering has become a painpoint. Also there seems to be technique advances like ACORN to solve this problem: https://arxiv.org/html/2403.04871v1

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-07-26 13:35 ` "lucasgadams (@lucasgadams)" <noreply+lucasgadams@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: lucasgadams (@lucasgadams) @ 2024-07-26 13:35 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Definitely interested in this. Our use case is similar to others mentioned above. We have a combination of public and private (to a user) documents in our database. When we do embedding search, it is always with a combination of joins (foreign key from document to embedding) and potentially some additional filtering (embedding type). The join is usually coming from a complex query of a few tables, users to document metadata, filtering document metadata to specific collections, possibly some string matches on metadata, ect. So far we have been using brute force search because we can often get the search space down to 50-100k, and we have a big postgres instance. No problems there for private user docs. But this will increase in the future, where instead of user docs we have company docs that can be much larger. We will still be using joins to pre-filter (to company owned docs), but the search space will be 100x larger, so we will be adding indexes eventually. Pre-filtering is a must for this sort of thing, as individual companies might have very similar documents which means post-filtered searches are not going to be very accurate. Hoping we can do this sort of thing in pgvector! Otherwise we will need to use one of the managed products that support pre-filtering.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-08-01 14:33 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: jkatz (@jkatz) @ 2024-08-01 14:33 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@lucasgadams Thanks for sharing, this is very helpful! I wanted to call out one particular comment:

> Pre-filtering is a must for this sort of thing, as individual companies might have very similar documents which means post-filtered searches are not going to be very accurate. 

On a theoretical basis, I don't agree that "post-filtered" searches aren't going to be accurate. It comes down to implementation: the challenge with a post-filtered search is that you'll need to see enough vectors in the index that satisfy all of the filtered conditions. Currently (as of v0.7.3) in pgvector, you may not be able to return enough tuples at a value of `hnsw.ef_search` to be able to satisfy it - and possibly with your case, you may not be able to achieve that at max `hnsw.ef_search`.

The way for pgvector to handle that would be to expand the search to additional neighborhoods until we satisfy the `LIMIT`, but this comes at cost of increased query time. So it raises a good question - is it more important to (1) return enough tuples (rows) to satisfy the LIMIT at the tradeoff of query latency, or is (2) query latency more important even if recall suffers? I believe for your case it's (2), but would love to hear more from others.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-08-01 14:49 ` "nickcanz (@nickcanz)" <noreply+nickcanz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: nickcanz (@nickcanz) @ 2024-08-01 14:49 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

For the use case we're trying to build we don't want to "share" small worlds among different users at all, we're always going to query with a specific user in mind and just want similarity search within the scope of the user's items. 

Right now, to avoid both the limit and latency problems you've mentioned we're accomplishing that via partial indexes i.e. `CREATE INDEX ON items USING hnsw (embedding vector_l2_ops) WHERE (category_id = 123);` This is accomplishing the job while we have a small number of users, but as we scale this management overhead isn't ideal and even something like table partitioning has overhead when it's in the thousands. 

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-08-01 18:49 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: jkatz (@jkatz) @ 2024-08-01 18:49 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

> For the use case we're trying to build we don't want to "share" small worlds among different users at all, we're always going to query with a specific user in mind and just want similarity search within the scope of the user's items.

@nickcanz In your case, would you ever perform a query over the full index (`SELECT ... FROM ... ORDER BY`), or is the query only ever scoped to a particular user (`SELECT ... FROM ... WHERE user_id = ... ORDER BY`)? Do you ever use or plan to use any other filters on the scans?

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-08-01 19:22 ` "nickcanz (@nickcanz)" <noreply+nickcanz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: nickcanz (@nickcanz) @ 2024-08-01 19:22 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Good question! We'd *always* include the `WHERE user_id = ...` but other filters *might* also be applied, in which case we would still have to balance the ef_search and latency, but ideally over a much smaller subset than the entire table.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-08-16 02:33 ` "cho-thinkfree-com (@cho-thinkfree-com)" <noreply+cho-thinkfree-com@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: cho-thinkfree-com (@cho-thinkfree-com) @ 2024-08-16 02:33 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I am also facing the same issue.

As the rows became more than 1 million, the search was slowing down, so I added the hnsw index to vector.

And when I sent the query below, it returned 0 results.

```
SELECT        
	(sparse <=> :lexicalVectorObject) AS distance			
FROM 
    tablexxxx
WHERE
    user_id = 'xxxxx'
ORDER BY (sparse <=> :lexicalVectorObject)
LIMIT 30
```

However, removing the WHERE clause returns the desired 30 results.
I am having trouble searching large amounts of data due to this issue.

I saw that this and similar issues are being discussed on https://github.com/pgvector/pgvector/issues/263.
I don't know where to put this, so I'm leaving it here.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-08-16 03:18 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

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

@cho-thinkfree-com Did you have an index on `user_id`? Based on how many vectors you have per user, if you're always including user_id in the query, have an index on the user_id column could end up being faster while returning the expected results.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-08-16 09:12 ` "cho-thinkfree-com (@cho-thinkfree-com)" <noreply+cho-thinkfree-com@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: cho-thinkfree-com (@cho-thinkfree-com) @ 2024-08-16 09:12 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Thank you for your quick reply, but I apologize for the delay in responding.

What I said above is a simplification. My actual situation is as follows.

* Total number of rows: about 2,2000,000
* WHERE clause condition: attachment = FALSE
* Number of rows where attachment is FALSE: about 330,000
* The attachment column is indexed.

* WHERE clause, 0 rows are returned. 
* no WHERE clause, 30 rows are returned.



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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-08-16 15:37 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
  88 siblings, 0 replies; 90+ messages in thread

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

@cho-thinkfree-com Without understanding the full scope of how you're searching, perhaps for your case you may want to consider either

1. Having a partial index on the vector column (`CREATE INDEX ON ... USING hnsw(...) WHERE (attachment = false);` (I don't know what your other conditions may be or if you're ever searching over specifically `attachment=true`, or
2. Partitioning the table by your `attachment` column, and creating the vector index on partition where `attachment` is false. (If you're also searching where `attachment = true`, you can create a vector index on that partition as well.

A B-tree index on `attachment` is unlikely going to give you much here if you're just indexing on true/false, particularly given the selectivity of your data. You're likely better off just dropping that index.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-08-19 02:17 ` "cho-thinkfree-com (@cho-thinkfree-com)" <noreply+cho-thinkfree-com@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: cho-thinkfree-com (@cho-thinkfree-com) @ 2024-08-19 02:17 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

I have very little knowledge about databases. I'm just happy to be able to use such a great open-source project. :-)
I'm also very grateful that you take the time to respond to my posts and share your opinions.

When searching without an index in a table with millions of rows, the speed was too slow. 
So I thought, "If I use attachment = FALSE, which removes attachments, perhaps searching over fewer rows might improve the speed?" With my limited knowledge, I wrote the query in that way.
Thank you for the valuable information that it might actually be better to drop the index.

I’m trying to create a service that searches for documents within a table where embedding information is stored, across n groups (UUIDs) and m categories (UUIDs).
In my current situation, groups and categories can be dynamically added.
Additionally, depending on the situation, there are cases where queries are made at once without distinguishing between groups and categories

In this case, I’m wondering if it’s a good idea to create indexes for all n groups (UUIDs) and m categories (UUIDs).

For example, something like this:
(Each time a group or category is added...)

`CREATE INDEX ON ... USING hnsw(...) WHERE (group_id = UUID and category_id = UUID);`

I'm concerned that my questions might be disrupting the current issue thread. I apologize in advance if that's the case.



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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-09-20 00:53 ` "ankane (@ankane)" <noreply+ankane@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: ankane (@ankane) @ 2024-09-20 00:53 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

Hi all, just posted the initial plan for 0.8.0 (#677), which includes an option for iterative index scans.

```sql
SET hnsw.iterative_scan = on;
```

If too few results from the initial index scan match the filters, the scan will continue until enough matching results are found.

A drawback of this approach is results may not be returned in strict order (each iteration of results will be ordered, but it's possible for an iteration to find results with a lower distance than previous iterations). You can use a CTE if strict ordering is required.

```sql
WITH approx_order AS MATERIALIZED (
    SELECT id, embedding <-> $1 AS distance FROM items WHERE ... ORDER BY distance LIMIT 10
) SELECT * FROM approx_order ORDER BY distance;
```

Will share another update once it's merged for anyone who would like to help test.

There are also plans to continue exploring composite indexes (which incorporate filters into index construction) for better performance.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-09-22 21:33 ` "ankane (@ankane)" <noreply+ankane@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: ankane (@ankane) @ 2024-09-22 21:33 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

There are now branches for this in #678 for anyone who would like to give feedback / test (in a non-production environment).

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-10-30 22:55 ` "ankane (@ankane)" <noreply+ankane@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: ankane (@ankane) @ 2024-10-30 22:55 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

@ankane closed this.

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

* Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
@ 2024-10-30 22:55 ` "ankane (@ankane)" <noreply+ankane@github.com>
  88 siblings, 0 replies; 90+ messages in thread

From: ankane (@ankane) @ 2024-10-30 22:55 UTC (permalink / raw)
  To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>

0.8.0 is now released with support for [iterative index scans](https://github.com/pgvector/pgvector?tab=readme-ov-file#iterative-index-scans). It also improves cost estimation for better index selection.

For filtering on columns where some values match few rows and others match many, it can be good to add an exact index on the filter column as well as an approximate index on the vector column (which will allow the planner to choose the best index for the specific query).

Also, as I mentioned earlier, there are plans to continue exploring composite indexes for better performance.

Since this thread is getting pretty long, please create a new issue for any follow-up. Thanks all.

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


end of thread, other threads:[~2024-10-30 22:55 UTC | newest]

Thread overview: 90+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2023-09-11 08:45 [pgvector/pgvector] issue #259: Understanding HNSW + filtering "Palmik (@Palmik)" <noreply+Palmik@github.com>
2023-09-11 08:45 ` "Palmik (@Palmik)" <noreply+Palmik@github.com>
2023-09-11 14:22 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2023-09-11 14:52 ` "Palmik (@Palmik)" <noreply+Palmik@github.com>
2023-09-11 14:53 ` "Palmik (@Palmik)" <noreply+Palmik@github.com>
2023-09-11 15:25 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2023-09-12 11:43 ` "pashkinelfe (@pashkinelfe)" <noreply+pashkinelfe@github.com>
2023-09-12 18:29 ` "ankane (@ankane)" <noreply+ankane@github.com>
2023-09-12 18:34 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2023-09-12 18:47 ` "pashkinelfe (@pashkinelfe)" <noreply+pashkinelfe@github.com>
2023-09-12 18:57 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2023-09-14 07:49 ` "fanfuxiaoran (@fanfuxiaoran)" <noreply+fanfuxiaoran@github.com>
2023-09-14 14:58 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2023-09-14 14:59 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2023-09-15 14:33 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2023-09-16 15:02 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
2023-09-17 19:13 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2023-09-17 19:41 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
2023-09-18 08:53 ` "fanfuxiaoran (@fanfuxiaoran)" <noreply+fanfuxiaoran@github.com>
2023-09-20 00:37 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2023-09-20 05:42 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
2023-09-20 19:51 ` "pashkinelfe (@pashkinelfe)" <noreply+pashkinelfe@github.com>
2023-10-25 12:39 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
2023-10-25 12:44 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
2023-10-25 13:18 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
2023-10-25 14:00 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
2023-10-25 14:07 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
2023-10-25 14:15 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
2023-10-25 15:10 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
2023-10-25 19:15 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
2023-10-26 08:32 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
2023-10-26 08:48 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
2023-10-26 09:39 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
2023-10-28 17:08 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
2023-10-28 18:49 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
2023-10-29 08:16 ` "mgoldenbe (@mgoldenbe)" <noreply+mgoldenbe@github.com>
2023-10-29 18:59 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
2023-11-06 22:45 ` "jeff-davis (@jeff-davis)" <noreply+jeff-davis@github.com>
2023-11-07 02:06 ` "ankane (@ankane)" <noreply+ankane@github.com>
2023-11-07 04:58 ` "jeff-davis (@jeff-davis)" <noreply+jeff-davis@github.com>
2023-11-07 06:42 ` "knizhnik (@knizhnik)" <noreply+knizhnik@github.com>
2023-11-07 13:41 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2023-11-10 04:05 ` "pomnb (@pomnb)" <noreply+pomnb@github.com>
2023-11-10 21:35 ` "ankane (@ankane)" <noreply+ankane@github.com>
2023-11-14 07:29 ` "suppersam1 (@suppersam1)" <noreply+suppersam1@github.com>
2023-12-04 05:50 ` "29swastik (@29swastik)" <noreply+29swastik@github.com>
2023-12-04 23:03 ` "rajbakhru-aptr (@rajbakhru-aptr)" <noreply+rajbakhru-aptr@github.com>
2024-01-15 16:07 ` "ianwoodfill (@ianwoodfill)" <noreply+ianwoodfill@github.com>
2024-01-15 20:12 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-01-22 21:33 ` "williamhakim10 (@williamhakim10)" <noreply+williamhakim10@github.com>
2024-02-07 06:26 ` "yekta (@yekta)" <noreply+yekta@github.com>
2024-02-27 13:31 ` "jcodella (@jcodella)" <noreply+jcodella@github.com>
2024-02-28 05:02 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-03-05 13:12 ` "lambda-science (@lambda-science)" <noreply+lambda-science@github.com>
2024-03-05 13:54 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-03-05 16:18 ` "ianwoodfill (@ianwoodfill)" <noreply+ianwoodfill@github.com>
2024-03-05 16:31 ` "williamhakim10 (@williamhakim10)" <noreply+williamhakim10@github.com>
2024-03-06 08:24 ` "lambda-science (@lambda-science)" <noreply+lambda-science@github.com>
2024-05-06 19:52 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
2024-05-07 11:18 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
2024-05-08 14:41 ` "williamhakim10 (@williamhakim10)" <noreply+williamhakim10@github.com>
2024-05-08 14:54 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
2024-05-08 15:10 ` "williamhakim10 (@williamhakim10)" <noreply+williamhakim10@github.com>
2024-05-08 15:15 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
2024-05-08 15:23 ` "williamhakim10 (@williamhakim10)" <noreply+williamhakim10@github.com>
2024-05-08 15:27 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
2024-05-08 15:33 ` "williamhakim10 (@williamhakim10)" <noreply+williamhakim10@github.com>
2024-05-08 15:41 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
2024-05-08 15:45 ` "williamhakim10 (@williamhakim10)" <noreply+williamhakim10@github.com>
2024-05-08 15:47 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
2024-05-08 16:55 ` "williamhakim10 (@williamhakim10)" <noreply+williamhakim10@github.com>
2024-05-08 17:00 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
2024-05-08 17:35 ` "ankane (@ankane)" <noreply+ankane@github.com>
2024-05-08 19:00 ` "mauriciocirelli (@mauriciocirelli)" <noreply+mauriciocirelli@github.com>
2024-05-24 13:14 ` "nickcanz (@nickcanz)" <noreply+nickcanz@github.com>
2024-06-21 09:10 ` "marv1nnnnn (@marv1nnnnn)" <noreply+marv1nnnnn@github.com>
2024-07-26 13:35 ` "lucasgadams (@lucasgadams)" <noreply+lucasgadams@github.com>
2024-08-01 14:33 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-08-01 14:49 ` "nickcanz (@nickcanz)" <noreply+nickcanz@github.com>
2024-08-01 18:49 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-08-01 19:22 ` "nickcanz (@nickcanz)" <noreply+nickcanz@github.com>
2024-08-16 02:33 ` "cho-thinkfree-com (@cho-thinkfree-com)" <noreply+cho-thinkfree-com@github.com>
2024-08-16 03:18 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-08-16 09:12 ` "cho-thinkfree-com (@cho-thinkfree-com)" <noreply+cho-thinkfree-com@github.com>
2024-08-16 15:37 ` "jkatz (@jkatz)" <noreply+jkatz@github.com>
2024-08-19 02:17 ` "cho-thinkfree-com (@cho-thinkfree-com)" <noreply+cho-thinkfree-com@github.com>
2024-09-20 00:53 ` "ankane (@ankane)" <noreply+ankane@github.com>
2024-09-22 21:33 ` "ankane (@ankane)" <noreply+ankane@github.com>
2024-10-30 22:55 ` "ankane (@ankane)" <noreply+ankane@github.com>
2024-10-30 22:55 ` "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