pgvector examples for Perl
Supports DBD::Pg
Getting Started
Follow the instructions for your database library:
Or check out some examples:
- Embeddings with OpenAI
- Binary embeddings with Cohere
- Hybrid search with Ollama (Reciprocal Rank Fusion)
- Sparse search with Text Embeddings Inference
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:
- 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.plTo run an example:
cd examples/openai
createdb pgvector_example
perl example.pl