pg.ddx.io  pgvector/pgvector GitHub issues and pull requests  
help / color / mirror / Atom feed
From: fede-bello (@fede-bello) <noreply+fede-bello@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] issue #648: Custom scoring with HNSW index
Date: Mon, 19 Aug 2024 16:11:00 +0000
Message-ID: <gh-pgvector-pgvector-648@github.com> (raw)

I am trying to achieve a search where some tuples have more weight than others. Let's say I have my table:

```
Document:
- id 
- embedding
- is_important : boolean
```
If the document is important, I would like to give more weight to it at the moment of searching.
I am working with HNSW indexes and I have ~4 M tuples in the database, so needs to use the index or else it takes too long. My parameters are: `ef_construction= 256`, `m=32` and `ef_search = 256`.
 So, first I tried something like:
```
SELECT "t1"."id", 
    (CASE WHEN ("t1"."is_important") THEN 1.2 ELSE 1 END * ("t1"."embedding" <#> <vector_search_embedding>)) AS "weighted_score"
FROM "Document" AS "t1"
WHERE ((CASE WHEN ("t1"."is_important") THEN 1.2 ELSE 1 END * ("t1"."embedding" <#> <vector_search_embedding>)) < -0.5)
ORDER BY (CASE WHEN ("t1"."is_important") THEN 1.2 ELSE 1 END * ("t1"."embedding" <#> <vector_search_embedding>)) ASC 
LIMIT 50
```
So, ordering by my custom score.  That, of course, did not work (didn't use the index)

Then, I tried using a subquery to find the most similar documents and then ordering by my custom score:
```
SELECT "t1"."id", 
    (CASE WHEN ("t1"."isImportant") THEN 1.2 ELSE 1 END * ("t1"."summaryEmbedding" <#> '<vector_search_embedding')) AS "weighted_score"
FROM "Document" AS "t1"
WHERE ("t1"."id" IN (
    SELECT "t1"."id"
    FROM "Document" AS "t1"
    WHERE ((CASE WHEN ("t1"."isImportant") THEN 1.2 ELSE 1 END * ("t1"."summaryEmbedding" <#> '<vector_search_embedding')) < -0.5)) 
    ORDER BY ("t1"."summaryEmbedding" <#> '<vector_search_embedding') ASC
    LIMIT 128)
ORDER BY weighted_score ASC
LIMIT 50
```

But its not ideal since there are important documents that might have a higher weighted score but get filtered by the limit in the first subquery.

So, my question is: is there any workaround to make this custom scoring efficiently? I could do several queries - one for important documents, one for not important documents and then merging and ordering this but I am looking for something more efficient.



view thread (5+ messages)  latest in thread

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