Skip to main content

RingDb

Struct RingDb 

Source
pub struct RingDb<T = ()> { /* private fields */ }
Expand description

Builder for a ring-query vector database.

Insert vectors (and their associated payloads) with add_vector(), then call build() to transfer ownership to the compute backend and obtain a SealedRingDb that can be queried.

T is the payload type stored alongside each vector. Use T = () when no payload is needed.

§Example — no payload

use ringdb::{RingDb, RingDbConfig, RingQuery};

let config = RingDbConfig::new(4);
let mut db = RingDb::new(config).unwrap();

db.add_vector(&[1.0, 0.0, 0.0, 0.0], ()).unwrap();
db.add_vector(&[0.0, 1.0, 0.0, 0.0], ()).unwrap();

let db = db.build().unwrap();
let result = db.query(&RingQuery { query: &[1.0f32, 0.0, 0.0, 0.0], d: 1.0, lambda: 0.1 }).unwrap();
println!("hits: {:?}", result.ids);

§Example — with payload

use ringdb::{RingDb, RingDbConfig, RingQuery};
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
struct Meta { label: String }

let mut db: RingDb<Meta> = RingDb::new(RingDbConfig::new(2)).unwrap();
db.add_vector(&[1.0, 0.0], Meta { label: "dog".into() }).unwrap();
db.add_vector(&[0.0, 1.0], Meta { label: "cat".into() }).unwrap();

let db = db.build().unwrap();
let result = db.query(&RingQuery { query: &[1.0f32, 0.0], d: 1.0, lambda: 0.1 }).unwrap();
let payloads = db.fetch_payloads(&result.ids).unwrap();

Implementations§

Source§

impl<T: Serialize + DeserializeOwned> RingDb<T>

Source

pub fn new(config: RingDbConfig) -> Result<Self, RingDbError>

Create a new empty RingDb with the given configuration.

Source

pub fn add_vector( &mut self, vector: &[f32], payload: T, ) -> Result<(), RingDbError>

Insert a single vector and its associated payload.

Vectors are assigned sequential IDs starting from 0. The slice length must equal dims.

Source

pub fn build(self) -> Result<SealedRingDb<T>, RingDbError>

Transfer ownership of the accumulated data to the compute backend and seal the database.

Vector data is moved into the backend (zero-cost for the CPU backend). Payloads are serialized and moved into a cold anonymous mmap — the staging Vec<T> is dropped immediately after.

If RingDbConfig::persist_dir is set the following files are written to that directory before sealing:

FileContent
meta.bindims + n_vectors as little-endian u64
vectors.binraw f32 vectors (row-major)
norms_sq.binraw f32 squared norms
payloads.binconcatenated bincode payload bytes
offsets.binbyte offsets (u64) into payloads.bin

The database can be reloaded later with RingDb::load().

Source

pub fn load( dir: &Path, backend_preference: BackendPreference, ) -> Result<SealedRingDb<T>, RingDbError>

Reconstruct a SealedRingDb from a directory previously written by RingDb::build() when RingDbConfig::persist_dir was set.

Reads meta.bin, vectors.bin, norms_sq.bin, payloads.bin, and offsets.bin from dir, re-uploads the vectors and norms to the requested backend, and memory-maps the payload file.

Pass [BackendPreference::Cpu] for the CPU backend (the only option today; CUDA and others will be added later).

§Errors

Returns RingDbError::Corrupt if any file is missing, has an unexpected size, or the dimension/count metadata is inconsistent.

§Example
use ringdb::{RingDb, RingDbConfig, BackendPreference};
use std::path::Path;

// --- save ---
let mut db = RingDb::<()>::new(RingDbConfig::new(4).with_persist_dir("/tmp/mydb")).unwrap();
db.add_vector(&[1.0, 0.0, 0.0, 0.0], ()).unwrap();
let _sealed = db.build().unwrap(); // writes files to /tmp/mydb

// --- load ---
let loaded = RingDb::<()>::load(Path::new("/tmp/mydb"), BackendPreference::Cpu).unwrap();
Source

pub fn len(&self) -> usize

Number of vectors currently staged.

Source

pub fn is_empty(&self) -> bool

Returns true if no vectors have been inserted.

Source

pub fn dims(&self) -> usize

Number of dimensions per vector.

Source

pub fn backend_name(&self) -> &str

Name of the backend currently in use.

Auto Trait Implementations§

§

impl<T> Freeze for RingDb<T>

§

impl<T = ()> !RefUnwindSafe for RingDb<T>

§

impl<T> Send for RingDb<T>
where T: Send,

§

impl<T> Sync for RingDb<T>
where T: Sync,

§

impl<T> Unpin for RingDb<T>
where T: Unpin,

§

impl<T> UnsafeUnpin for RingDb<T>

§

impl<T = ()> !UnwindSafe for RingDb<T>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.