pgvector support for Rust Supports Rust-Postgres, SQLx, and Diesel

Overview

pgvector-rust

pgvector support for Rust

Supports Rust-Postgres, SQLx, and Diesel

Build Status

Getting Started

Follow the instructions for your database library:

Rust-Postgres

Add this line to your application’s Cargo.toml under [dependencies]:

pgvector = { version = "0.1", features = ["postgres"] }

Create a vector from a Vec

let vec = pgvector::Vector::from(vec![1.0, 2.0, 3.0]);

Insert a vector

client.execute("INSERT INTO table (column) VALUES ($1)", &[&vec])?;

Get the nearest neighbor

$1 LIMIT 1", &[&vec])?; ">
let row = client.query_one("SELECT * FROM table ORDER BY column <-> $1 LIMIT 1", &[&vec])?;

Retrieve a vector

let row = client.query_one("SELECT column FROM table LIMIT 1", &[])?;
let vec: pgvector::Vector = row.get(0);

Use Option if the value could be NULL

let res: Option<pgvector::Vector> = row.get(0);

SQLx

Add this line to your application’s Cargo.toml under [dependencies]:

pgvector = { version = "0.1", features = ["sqlx"] }

Create a vector from a Vec

let vec = pgvector::Vector::from(vec![1.0, 2.0, 3.0]);

Insert a vector

sqlx::query("INSERT INTO table (column) VALUES ($1)").bind(vec).execute(&pool).await?;

Get the nearest neighbors

$1 LIMIT 1") .bind(vec).fetch_all(&pool).await?; ">
let rows = sqlx::query("SELECT * FROM table ORDER BY column <-> $1 LIMIT 1")
    .bind(vec).fetch_all(&pool).await?;

Retrieve a vector

let row = sqlx::query("SELECT column FROM table LIMIT 1").fetch_one(&pool).await?;
let vec: pgvector::Vector = row.try_get("column")?;

Diesel

Add this line to your application’s Cargo.toml under [dependencies]:

pgvector = { version = "0.1", features = ["diesel"] }

And add this line to your application’s diesel.toml under [print_schema]:

import_types = ["diesel::sql_types::*", "pgvector::sql_types::*"]

Create a migration

diesel migration generate create_vector_extension

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

CREATE TABLE items (
  factors VECTOR(3)
)

For models, use:

pub struct Item {
    pub factors: Option<pgvector::Vector>
}

Create a vector from a Vec

let factors = pgvector::Vector::from(vec![1.0, 2.0, 3.0]);

Insert a vector

let new_item = Item {
    factors: Some(factors)
};

diesel::insert_into(items::table)
    .values(&new_item)
    .get_result::(&conn)?;

Get the nearest neighbors

use pgvector::VectorExpressionMethods;

let neighbors = items::table
    .order(items::factors.l2_distance(factors))
    .limit(5)
    .load::(&conn)?;

Also supports max_inner_product and cosine_distance

Add an approximate index in a migration

CREATE INDEX my_index ON items USING ivfflat (factors vector_l2_ops)

Use vector_ip_ops for inner product and vector_cosine_ops for cosine distance

Reference

Convert a vector to a Vec

let f32_vec = vec.to_vec();

History

View the changelog

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/ankane/pgvector-rust.git
cd pgvector-rust
cargo test --all-features
You might also like...
A job queue built on sqlx and PostgreSQL.

sqlxmq A job queue built on sqlx and PostgreSQL. This library allows a CRUD application to run background jobs without complicating its deployment. Th

Simple example of axum, sqlx with sqlite and utoipa (swagger) - without auth

axum_crud_api Simple example to learn creating CRUD rest apis in Rust with axum, sqlx with sqlite and utoipa (swagger) - without auth Also shows how t

Rust Axum+SQLx Sample

rust-axum-sqlx-sample Install git clone https://github.com/web3ten0/rust-axum-sqlx-1.git cd rust-axum-sqlx-1/local docker-compose up -d sh scripts/exe

Request-bound SQLx transactions for axum

axum-sqlx-rx Request-bound SQLx transactions for axum. Summary axum-sqlx-rx provides an axum extractor for obtaining a request-bound transaction. The

Diesel - A safe, extensible ORM and Query Builder for Rust

A safe, extensible ORM and Query Builder for Rust API Documentation: latest release – master branch Homepage Diesel gets rid of the boilerplate for da

A Rust Boilerplate server with GraphQL API, Diesel, PostgreSQL, session authentication and JWT
A Rust Boilerplate server with GraphQL API, Diesel, PostgreSQL, session authentication and JWT

Canduma rust Graphql A Rust authentication server with GraphQL API, Diesel, PostgreSQL session authentication and JWT This repository contains a Graph

Diesel - ORM and Query Builder for Rust

A safe, extensible ORM and Query Builder for Rust API Documentation: latest release – master branch Homepage Diesel gets rid of the boilerplate for da

Detects whether a terminal supports color, and gives details about that support

Detects whether a terminal supports color, and gives details about that support. It takes into account the NO_COLOR environment variable. This crate i

Server with Rust, Rocket, Diesel, Docker to create your own to-do-list

Installation Install Docker & Docker-Compose Then download the repository go to the root where the Dockerfile is and do: sudo docker-compose up sudo i

Diesel async connection implementation

A async interface for diesel Diesel gets rid of the boilerplate for database interaction and eliminates runtime errors without sacrificing performance

Tide middleware for Diesel pooled connections & transactions

tide-diesel Tide middleware for Diesel pooled connections & transactions. A Tide middleware which holds a pool of Diesel database connections, and aut

Cornucopia is a small CLI utility resting on tokio-postgres and designed to facilitate PostgreSQL workflows in Rust

Cornucopia Generate type checked Rust from your SQL Install | Example Cornucopia is a small CLI utility resting on tokio-postgres and designed to faci

Making Postgres and Elasticsearch work together like it's 2021

Making Postgres and Elasticsearch work together like it's 2021 Readme ZomboDB brings powerful text-search and analytics features to Postgres by using

Distributed, version controlled, SQL database with cryptographically verifiable storage, queries and results. Think git for postgres.

SDB - SignatureDB Distributed, version controlled, SQL database with cryptographically verifiable storage, queries and results. Think git for postgres

Manage Redshift/Postgres privileges in GitOps style written in Rust

grant-rs An open-source project that aims to manage Postgres/Redshift database roles and privileges in GitOps style, written in Rust. Home | Documenta

cogo rust coroutine database driver (Mysql,Postgres,Sqlite)

cdbc Coroutine Database driver Connectivity.based on cogo High concurrency,based on coroutine No Future'q,Output=*,No async fn, No .await , no Poll*

A Rust application that inserts Discogs data dumps into Postgres

Discogs-load A Rust application that inserts Discogs data dumps into Postgres. Discogs-load uses a simple state machine with the quick-xml Rust librar

A backend API starter with Rust & postgres

Rust backend starter Rust backend starter with OpenAPI spec & swagger with rocket_okapi

Command-line tool to make Rust source code entities from Postgres tables.

pg2rs Command-line tool to make Rust source code entities from Postgres tables. Generates: enums structs which can be then used like mod structs; use

Comments
  • Update Cargo.toml

    Update Cargo.toml

    Mentioning "0" would mean cargo would pick the latest dependency which is versioned "0.*" which would include versions incompatible with the one that this crate was written with and may break your create.

    opened by Dylan-DPC 1
Owner
Andrew Kane
Andrew Kane
A high level async Redis client for Rust built on Tokio and Futures.

A high level async Redis client for Rust built on Tokio and Futures.

Alec Embke 103 Nov 30, 2022
gobang - A cross-platform TUI database management tool written in Rust

gobang - A cross-platform TUI database management tool written in Rust

Takayuki Maeda 2.1k Dec 2, 2022
A MongoDB ODM for Rust based on Mongoose

Nongoose MongoDB ODM for Rust based on Mongoose Basic usage use mongodb::{bson::oid::ObjectId, sync::Client}; use nongoose::Schema; use serde::{Deseri

NextChat 9 Nov 8, 2022
A newsletter with actix-web and sqlx-postgres

Newsletter backend Health check: production Pre-requisites You'll need to install: Rust Docker There are also some OS-specific requirements. Windows c

Nadeem Bhati 4 Aug 24, 2022
A simple tool to test sqlx with postgres. It will automatically create a database and drop it after the test.

sqlx-db-tester This a tool to test sqlx with postgres. It only supports tokio runtime at this moment. How to use it You should first create a TestDb d

Tyr Chen 4 Nov 29, 2022
Easy c̵̰͠r̵̛̠ö̴̪s̶̩̒s̵̭̀-t̶̲͝h̶̯̚r̵̺͐e̷̖̽ḁ̴̍d̶̖̔ ȓ̵͙ė̶͎ḟ̴͙e̸̖͛r̶̖͗ë̶̱́ṉ̵̒ĉ̷̥e̷͚̍ s̷̹͌h̷̲̉a̵̭͋r̷̫̊ḭ̵̊n̷̬͂g̵̦̃ f̶̻̊ơ̵̜ṟ̸̈́ R̵̞̋ù̵̺s̷̖̅ţ̸͗!̸̼͋

Rust S̵̓i̸̓n̵̉ I̴n̴f̶e̸r̵n̷a̴l mutability! Howdy, friendly Rust developer! Ever had a value get m̵̯̅ð̶͊v̴̮̾ê̴̼͘d away right under your nose just when

null 293 Sep 22, 2022
Basic Actix + Diesel + Postgres REST API

Actix-Crud Basic Actix + Diesel + Postgres REST API Setup Install and setup PostgreSQL Set DATABASE_URL environment variable or specify in .env file g

Aathif Naseer 4 Sep 23, 2022
Docker images for compiling static Rust binaries using musl-libc and musl-gcc, with static versions of useful C libraries. Supports openssl and diesel crates.

rust-musl-builder: Docker container for easily building static Rust binaries Source on GitHub Changelog UPDATED: Major updates in this release which m

Eric Kidd 1.3k Dec 2, 2022
Postgres proxy which allows tools that don't natively supports IAM auth to connect to AWS RDS instances.

rds-iamauth-proxy rds-proxy lets you make use of IAM-based authentication to AWS RDS instances from tools that don't natively support that method of a

Gold Fig Labs Inc. 10 Nov 7, 2022
rust-postgres support library for the r2d2 connection pool

r2d2-postgres Documentation rust-postgres support library for the r2d2 connection pool. Example use std::thread; use r2d2_postgres::{postgres::NoTls,

Steven Fackler 125 Nov 21, 2022