pg.ddx.io  pgvector/pgvector GitHub issues and pull requests  
help / color / mirror / Atom feed
From: ankane (@ankane) <noreply+ankane@github.com>
To: pgvector/pgvector <noreply+pgvector-pgvector@github.com>
Subject: Re: [pgvector/pgvector] issue #687: Query returns indexed rows with noticeable "steps"; how to control?
Date: Tue, 01 Oct 2024 02:56:49 +0000
Message-ID: <gh-pgvector-pgvector-687-c2384680998@github.com> (raw)
In-Reply-To: <gh-pgvector-pgvector-687@github.com>
References: <gh-pgvector-pgvector-687@github.com>

It looks like this is due to how the query is written and the function being `STABLE` (as it doesn't happen with `IMMUTABLE` and `VOLATILE` won't use the index).

```sql
CREATE OR REPLACE FUNCTION embed(t text) RETURNS vector AS $$
    BEGIN
        RAISE NOTICE 'embed: %', t;
        RETURN '[3,1,2]';
    END;
$$ LANGUAGE plpgsql STABLE;

CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3));
CREATE INDEX ON items USING hnsw (embedding vector_cosine_ops);
INSERT INTO items (embedding) VALUES ('[1,2,3]'), ('[4,5,6]'), ('[7,8,9]');

SET enable_seqscan = off;
EXPLAIN ANALYZE SELECT * FROM items CROSS JOIN LATERAL (SELECT embedding <=> embed('text')::vector(3) dist) cs ORDER BY dist;
```

This will call the function (and print `embed: text`) 4 times - once for the initial query and then for each result.

If you change how the query is written, it'll only call the function once.

```sql
EXPLAIN ANALYZE SELECT * FROM items ORDER BY embedding <=> (SELECT embed('text')::vector(3)) LIMIT 5;
```

Also, I'd recommend adding `LIMIT` to the query (rather than relying on `ef_search` to limit results).

view thread (9+ messages)  latest in thread

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