From: jkatz (@jkatz) <noreply+jkatz@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: Re: [pgvector/pgvector] issue #641: Cant use DISTINCT ON
Date: Mon, 12 Aug 2024 13:44:41 +0000
Message-ID: <gh-pgvector-pgvector-641-c2284035995@github.com> (raw)
In-Reply-To: <gh-pgvector-pgvector-641@github.com>
References: <gh-pgvector-pgvector-641@github.com>
@mfandre What you described above is a different type of query. With your first query:
```sql
SELECT DISTINCT ON (embedding, path) path
FROM chunks
ORDER BY embedding <=> '[...]'
LIMIT 3
```
your `ORDER BY` clause is calculating the distance between `embedding` and a query vector, whereas your projection (`DISTINCT ON`) is using just the value of `embedding`.
If you want to use `DISTINCT ON` using the distance, you would write it with something like this (untested):
```sql
SELECT DISTINCT ON (distance, path)
embedding <=> '[...]' AS distance, path
FROM chunks
ORDER BY distance
LIMIT 3;
```
though (again untested in this case) I don't see the difference between that and using `DISTINCT`.
For the second query, the reason it worked is because you don't have to account for ordering. As it says in the docs that @ankane referenced:
> ...[DISTINCT ON] keeps only the first row of each set of rows where the given expressions evaluate to equal.
so because order matters, the values in `DISTINCT ON` must match the same values provided in order in the `ORDER BY` clause.