pgvector examples for Perl
Supports DBD::Pg
Follow the instructions for your database library:
Enable the extension
$dbh->do('CREATE EXTENSION IF NOT EXISTS vector');
Create a table
$dbh->do('CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3))');
Insert vectors
sub vector {
return '[' . join(',', @{$_[0]}) . ']';
}
my $sth = $dbh->prepare('INSERT INTO items (embedding) VALUES ($1), ($2), ($3)');
my @embedding1 = (1, 1, 1);
my @embedding2 = (2, 2, 2);
my @embedding3 = (1, 1, 2);
$sth->execute(vector(\@embedding1), vector(\@embedding2), vector(\@embedding3));
Get the nearest neighbors
my $sth = $dbh->prepare('SELECT * FROM items ORDER BY embedding <-> $1 LIMIT 5');
my @embedding = (1, 1, 1);
$sth->execute(vector(\@embedding));
while (my @row = $sth->fetchrow_array()) {
print($row[1] . "\n");
}
Add an approximate index
$dbh->do('CREATE INDEX ON items USING hnsw (embedding vector_l2_ops)');
# or
$dbh->do('CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100)');
Use vector_ip_ops
for inner product and vector_cosine_ops
for cosine distance
See a full example
Everyone is encouraged to help improve this project. Here are a few ways you can help:
- Report bugs
- Fix bugs and submit pull requests
- Write, clarify, or fix documentation
- Suggest or add new features
To get started with development:
git clone https://github.com/pgvector/pgvector-perl.git
cd pgvector-perl
createdb pgvector_perl_test
cpan DBD::Pg
perl example.pl