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...
Rust - Build a CRUD API with SQLX and PostgreSQL

In this article, you'll learn how to build a CRUD API in Rust using SQLX, Actix-web, and PostgreSQL. Learning how to build a CRUD API as a developer will equip you with valuable skills for building robust, maintainable, and scalable applications.

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

📺 Netflix in Rust/ React-TS/ NextJS, Actix-Web, Async Apollo-GraphQl, Cassandra/ ScyllaDB, Async SQLx, Kafka, Redis, Tokio, Actix, Elasticsearch, Influxdb Iox, Tensorflow, AWS
📺 Netflix in Rust/ React-TS/ NextJS, Actix-Web, Async Apollo-GraphQl, Cassandra/ ScyllaDB, Async SQLx, Kafka, Redis, Tokio, Actix, Elasticsearch, Influxdb Iox, Tensorflow, AWS

Fullstack Movie Streaming Platform 📺 Netflix in RUST/ NextJS, Actix-Web, Async Apollo-GraphQl, Cassandra/ ScyllaDB, Async SQLx, Spark, Kafka, Redis,

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

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

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

Web Application with using Rust(Actix, Diesel and etc)
Web Application with using Rust(Actix, Diesel and etc)

Santa Service App Used technology stack Web Server with using Rust (Actix, Actix-web, Diesel) Data base (Postgres) Console Application (Tokio) Tasks o

Background task processing for Rust applications with Tokio, Diesel, and PostgreSQL.
Background task processing for Rust applications with Tokio, Diesel, and PostgreSQL.

Async persistent background task processing for Rust applications with Tokio. Queue asynchronous tasks to be processed by workers. It's designed to be

Todo REST API with Rust,Axum, and Diesel

Building a Todo API with Rust - A Step-by-Step Guide Using Axum and Diesel This is the project demonstrating how to build a Todo REST API by using Rus

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

Generate rust structs & query functions from diesel schema files

dsync A utility to generate database structs and querying code from diesel schema files. Primarily built for create-rust-app. Currently, it's more adv

The goal of this repository is to have a real world template of a Rust backend using Axum, Diesel, etc.

Axum Diesel Real-World Example A modular Rust backend template based on the Domain-Driven Design (DDD) architecture, utilizing the Axum and Diesel fra

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

reth-indexer reads directly from the reth db and indexes the data into a postgres database all decoded with a simple config file and no extra setup alongside exposing a API ready to query the data.
reth-indexer reads directly from the reth db and indexes the data into a postgres database all decoded with a simple config file and no extra setup alongside exposing a API ready to query the data.

reth-indexer reth-indexer reads directly from the reth db and indexes the data into a postgres database all decoded with a simple config file and no e

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 108 Jan 1, 2023
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 Jan 1, 2023
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
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 294 Dec 23, 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 Dec 10, 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
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 Jan 1, 2023
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 128 Dec 26, 2022