From: matan-airis (@matan-airis) <noreply+matan-airis@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: [pgvector/pgvector] issue #645: What is the best way to find nearest-neighbor for N vectors (batch query)?
Date: Sun, 18 Aug 2024 12:04:42 +0000
Message-ID: <gh-pgvector-pgvector-645@github.com> (raw)
I have a situation where I have a bunch of embeddings I want to lookup. So far, the fastest way I managed to do that is by making a database query per vector, which is reasonably fast (looking 100 vectors up in a table with 1M rows takes ~30 seconds if I run the queries serially and even faster if I parallelize the queries).
Trying to do this with one query takes several times longer, about 3 minutes. The query I have so far looks something like this, where `t_temp` is a temp table with 100 vectors and `t` is a table with 1M vectors. For this application I need exact nearest-neighbor, so I'm not using an index.
```sql
SELECT t_results.* FROM (
SELECT embedding
FROM t_temp
) t_v
JOIN LATERAL (
SELECT (t_v.embedding <#> embedding) * -1 AS similarity
FROM t
ORDER BY similarity DESC
LIMIT 1
) t_results ON true
```
Is there a better way to do this query, or should I keep using multiple queries?