Skip to content

Latest commit

 

History

History
83 lines (58 loc) · 1.96 KB

README.md

File metadata and controls

83 lines (58 loc) · 1.96 KB

pgvector-perl

pgvector examples for Perl

Supports DBD::Pg

Build Status

Getting Started

Follow the instructions for your database library:

DBD::Pg

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

Contributing

Everyone is encouraged to help improve this project. Here are a few ways you can help:

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