pgvector support for Ruby
For Rails, check out Neighbor
Add this line to your application’s Gemfile:
gem "pgvector"
And follow the instructions for your database library:
Or check out some examples:
- Embeddings with OpenAI
- User-based recommendations with Disco
- Item-based recommendations with Disco
Register the vector type with your connection
registry = PG::BasicTypeRegistry.new.define_default_types
Pgvector::PG.register_vector(registry)
conn.type_map_for_results = PG::BasicTypeMapForResults.new(conn, registry: registry)
Insert a vector
embedding = [1, 2, 3]
conn.exec_params("INSERT INTO items (embedding) VALUES ($1)", [embedding])
Get the nearest neighbors to a vector
conn.exec_params("SELECT * FROM items ORDER BY embedding <-> $1 LIMIT 5", [embedding]).to_a
Create a table
DB.create_table :items do
primary_key :id
column :embedding, "vector(3)"
end
Add the plugin to your model
class Item < Sequel::Model
plugin :pgvector, :embedding
end
Insert a vector
Item.create(embedding: [1, 1, 1])
Get the nearest neighbors to a record
item.nearest_neighbors(:embedding, distance: "euclidean").limit(5)
Also supports inner_product
and cosine
distance
Get the nearest neighbors to a vector
Item.nearest_neighbors(:embedding, [1, 1, 1], distance: "euclidean").limit(5)
View the changelog
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-ruby.git
cd pgvector-ruby
createdb pgvector_ruby_test
bundle install
bundle exec rake test