pg.ddx.io  pgvector/pgvector GitHub issues and pull requests  
help / color / mirror / Atom feed
From: Wulfsta (@Wulfsta) <noreply+Wulfsta@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: Re: [pgvector/pgvector] issue #901: How do I extend pgvector with a custom distance metric?
Date: Fri, 26 Sep 2025 05:32:20 +0000
Message-ID: <gh-pgvector-pgvector-901-c3336836827@github.com> (raw)
In-Reply-To: <gh-pgvector-pgvector-901@github.com>
References: <gh-pgvector-pgvector-901@github.com>

@ankane it's probably worth asking as well - must these functions be unary? What I want to experiment with is a sort of filtering directly in the vectors (I have read the past filtering discussions here). I don't know if this is a common approach, so perhaps this is a naive proposal, but I want to sum two distance metrics, where the first applies to the first 16 bytes and the second applies to the rest of the vector. To demonstrate in SQL, what I am visualizing is as follows
```
CREATE INDEX idx_compound_hnsw ON uuid_embedding_table USING hnsw (uuid, embedding vector_cosine_ops)
```
to accelerate
```
SELECT * FROM uuid_embedding_table WHERE uuid = $1 ORDER BY embedding <=> $2
```
where the compound index is defined as:
- a HNSW index using a single distance metric that is the sum of
  - the Hamming distance of `uuid` and `$1`
  - half the cosine distance of the `embedding` column and `$2`.

Note that given distance metrics `d_1(a, b)` where `a`, `b` are in `M` and `d_2(c, d)` where `c`, `d` are in `N`, then `d((a, c), (b, d)) = d_1(a, b) + d_2(c, d)` still satisfies the constraints of a metric. That is, the sum of the Hamming distance of two UUIDs converted into bits and the cosine distance of two embeddings can be used as a distance metric. In particular, note that the Hamming distance is larger than half the cosine distance unless the UUIDs are equal (this idea should work for other distance metrics, as long as the Hamming distance of the UUIDs dominates the sum, or is scaled to ensure it does). This should make it such that a single HNSW index can support this style of filtering directly?

Anyhow, I could probably hack this into place by storing the UUIDs as part of the vectors and doing some byte array slicing and type conversion? This thought experiment is starting to look like it would require [a lot](https://github.com/pgvector/pgvector/blob/4cef9213ec81b8609bd06cb8ca02fee7c3c3f05d/src/hnsw.c#L277) of modification to pgvector, and I'm curious what your thoughts are about this? 

view thread (13+ messages)  latest in thread

Message-ID: <gh-pgvector-pgvector-901-c3336836827@github.com>
Permalink:  ../gh-pgvector-pgvector-901-c3336836827@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