pgvector-rust
pgvector support for Rust
Supports Rust-Postgres, SQLx, and Diesel
Getting Started
Follow the instructions for your database library:
Or check out some examples:
- Embeddings with OpenAI
- Binary embeddings with Cohere
- Sentence embeddings with Candle
- Hybrid search with Candle (Reciprocal Rank Fusion)
- Recommendations with Disco
- Bulk loading with
COPY
Rust-Postgres
Add this line to your application’s Cargo.toml
under [dependencies]
:
= { = "0.4", = ["postgres"] }
Enable the extension
client.execute?;
Create a table
client.execute?;
Create a vector from a Vec<f32>
use Vector;
let embedding = from;
Insert a vector
client.execute?;
Get the nearest neighbor
let row = client.query_one?;
Retrieve a vector
let row = client.query_one?;
let embedding: Vector = row.get;
Use Option
if the value could be NULL
let embedding: = row.get;
SQLx
Add this line to your application’s Cargo.toml
under [dependencies]
:
= { = "0.4", = ["sqlx"] }
For SQLx < 0.8, use version = "0.3"
and this readme.
Enable the extension
.execute
.await?;
query
Create a table
.execute
.await?;
query
Create a vector from a Vec<f32>
use Vector;
let embedding = from;
Insert a vector
.bind
.execute
.await?;
query
Get the nearest neighbors
let rows = query
.bind
.fetch_all
.await?;
Retrieve a vector
let row = query.fetch_one.await?;
let embedding: Vector = row.try_get?;
Diesel
Add this line to your application’s Cargo.toml
under [dependencies]
:
= { = "0.4", = ["diesel"] }
And update your application’s diesel.toml
under [print_schema]
:
= ["diesel::sql_types::*", "pgvector::sql_types::*"]
= false
Create a migration
with up.sql
:
CREATE EXTENSION vector
and down.sql
:
DROP EXTENSION vector
Run the migration
diesel migration run
You can now use the vector
type in future migrations
SERIAL PRIMARY KEY,
embedding VECTOR(3)
)
(
id
For models, use:
use Vector;
Create a vector from a Vec<f32>
let embedding = from;
Insert a vector
let new_item = NewItem ;
insert_into
.values
.?;
Get the nearest neighbors
use VectorExpressionMethods;
let neighbors = table
.order
.limit
.?;
Also supports max_inner_product
, cosine_distance
, l1_distance
, hamming_distance
, and jaccard_distance
Get the distances
let distances = table
.select
.?;
Add an approximate index in a migration
-- or
(embedding vector_l2_ops) WITH (lists = 100)
(embedding vector_l2_ops)
Use vector_ip_ops
for inner product and vector_cosine_ops
for cosine distance
Serialization
Use the serde
feature to enable serialization
Half Vectors
Use the halfvec
feature to enable half vectors
Reference
Convert a vector to a Vec<f32>
let f32_vec: = vec.into;
Get a slice
let slice = vec.as_slice;
History
View the changelog
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: