From: WalidMustapha (@WalidMustapha) <noreply+WalidMustapha@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: Re: [pgvector/pgvector] issue #760: HNSW Index Not Used When Combining ORDER BY Distance with Deduplication
Date: Sat, 18 Jan 2025 10:21:07 +0000
Message-ID: <gh-pgvector-pgvector-760-c2599659641@github.com> (raw)
In-Reply-To: <gh-pgvector-pgvector-760@github.com>
References: <gh-pgvector-pgvector-760@github.com>
Just to fully understand the limitations with HNSW indexing and deduplication, am I correct in understanding that this query pattern would require a full scan:
```
WITH deduplicated AS (
SELECT DISTINCT ON (id) *
FROM table
)
SELECT *
FROM deduplicated
ORDER BY vector_column <-> query_vector;
```
And instead we must use this workaround (my current implementation):
```
WITH vector_search AS (
SELECT *
FROM table
ORDER BY vector_column <-> query_vector
LIMIT {increased_limit} -- fetch more results to accomodate for duplicates
)
SELECT DISTINCT ON (id) *
FROM vector_search
ORDER BY vector_distance;
```
The first query can't use the HNSW index because it needs to scan all rows after the DISTINCT operation, while the second query pattern can at least use the HNSW index for the initial vector search before deduplication. Is this correct?