From: jkatz (@jkatz) <noreply+jkatz@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: Re: [pgvector/pgvector] issue #259: Understanding HNSW + filtering
Date: Fri, 15 Sep 2023 14:33:29 +0000
Message-ID: <gh-pgvector-pgvector-259-c1721382806@github.com> (raw)
In-Reply-To: <gh-pgvector-pgvector-259@github.com>
References: <gh-pgvector-pgvector-259@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.