How to Use Embedded Databases (sled, redb) in Rust

Add sled or redb to Cargo.toml and initialize a database instance with Db::open or Database::create to start storing data locally.

Embedded databases like sled and redb are added as dependencies in Cargo.toml and initialized with a Db::open call in your main function. Add the crate to your manifest, then open a database instance and insert data using the insert method.

[dependencies]
sled = "0.34"
use sled::Db;

fn main() -> Result<(), sled::Error> {
    let db = Db::open("my_database")?;
    db.insert(b"hello", b"world")?;
    Ok(())
}

For redb, the setup is similar but uses the Database struct:

[dependencies]
redb = "2.0"
use redb::{Database, TableDefinition};

const TABLE: TableDefinition<&[u8], &[u8]> = TableDefinition::new("my_table");

fn main() -> Result<(), redb::Error> {
    let db = Database::create("my_database.redb")?;
    let write_txn = db.begin_write()?;
    {
        let mut table = write_txn.open_table(TABLE)?;
        table.insert(b"hello", b"world")?;
    }
    write_txn.commit()?;
    Ok(())
}