Skip to main content

Crate couchbase

Crate couchbase 

Source
Expand description

§Couchbase Rust SDK

The official Couchbase SDK for Rust, providing asynchronous access to Couchbase Server from Rust applications.

This crate enables you to interact with a Couchbase cluster for key-value (KV) operations, SQL++ (N1QL) queries, Full-Text Search (FTS), sub-document operations, and cluster management.

§Getting Started

Add the dependency to your Cargo.toml:

[dependencies]
couchbase = "1.0.0-beta.1"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"

§Connecting to a Cluster

The entry point is the Cluster, which is created by calling Cluster::connect with a connection string and ClusterOptions.

use couchbase::cluster::Cluster;
use couchbase::authenticator::PasswordAuthenticator;
use couchbase::options::cluster_options::ClusterOptions;

let authenticator = PasswordAuthenticator::new("username", "password");
let options = ClusterOptions::new(authenticator.into());

let cluster = Cluster::connect("couchbase://localhost", options).await?;

§Basic Key-Value Operations

Once connected, open a Bucket, navigate to a Scope and Collection, and perform CRUD operations:

use couchbase::cluster::Cluster;
use couchbase::authenticator::PasswordAuthenticator;
use couchbase::options::cluster_options::ClusterOptions;
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct User {
    name: String,
    email: String,
    age: u32,
}

let authenticator = PasswordAuthenticator::new("username", "password");
let options = ClusterOptions::new(authenticator.into());
let cluster = Cluster::connect("couchbase://localhost", options).await?;

let bucket = cluster.bucket("my-bucket");
let collection = bucket.default_collection();

// Upsert a document
let user = User { name: "Alice".into(), email: "alice@example.com".into(), age: 30 };
let result = collection.upsert("user::alice", &user, None).await?;
println!("CAS: {}", result.cas());

// Get a document
let result = collection.get("user::alice", None).await?;
let user: User = result.content_as()?;
println!("Got user: {:?}", user);

// Remove a document
collection.remove("user::alice", None).await?;

§SQL++ (N1QL) Queries

Execute SQL++ queries against the cluster or a specific scope using Cluster::query or Scope::query:

use couchbase::cluster::Cluster;
use couchbase::authenticator::PasswordAuthenticator;
use couchbase::options::cluster_options::ClusterOptions;
use couchbase::options::query_options::QueryOptions;
use futures::TryStreamExt;
use serde_json::Value;

let opts = QueryOptions::new()
    .add_positional_parameter("Alice")?;

let mut result = cluster.query(
    "SELECT * FROM `my-bucket` WHERE name = $1",
    opts,
).await?;

let rows: Vec<Value> = result.rows().try_collect().await?;
for row in rows {
    println!("{:?}", row);
}

§Sub-Document Operations

Operate on parts of a JSON document using lookup_in and mutate_in with sub-document specs:

use couchbase::subdoc::lookup_in_specs::LookupInSpec;
use couchbase::subdoc::mutate_in_specs::MutateInSpec;

// Lookup sub-document paths
let result = collection.lookup_in("user::alice", &[
    LookupInSpec::get("name", None),
    LookupInSpec::exists("email", None),
], None).await?;

let name: String = result.content_as(0)?;
let email_exists: bool = result.exists(1)?;

// Mutate sub-document paths
collection.mutate_in("user::alice", &[
    MutateInSpec::upsert("age", 31, None)?,
    MutateInSpec::insert("verified", true, None)?,
], None).await?;

§Error Handling

All fallible operations return error::Result<T>, which wraps error::Error. Inspect the error kind via Error::kind():

use couchbase::error::{Error, ErrorKind};

match collection.get("nonexistent-key", None).await {
    Ok(result) => println!("Found document"),
    Err(e) if *e.kind() == ErrorKind::DocumentNotFound => {
        println!("Document does not exist");
    }
    Err(e) => return Err(e),
}

§Architecture

The SDK follows the Couchbase data model hierarchy:

  • Cluster — Top-level entry point. Connect here, run cluster-level queries, and access management APIs.
  • Bucket — Represents a Couchbase bucket. Obtained from Cluster::bucket().
  • Scope — A namespace within a bucket. Obtained from Bucket::scope(). Supports scoped queries and Full-Text Search.
  • Collection — Holds documents. Obtained from Scope::collection(). Supports all KV, sub-document, and data structure operations.
  • BinaryCollection — Accessed via Collection::binary(). Provides binary append/prepend and counter operations.

§Modules Overview

ModuleDescription
authenticatorAuthentication types (PasswordAuthenticator, CertificateAuthenticator)
clusterCluster — the main entry point
bucketBucket — bucket-level operations
scopeScope — scoped queries and search
collectionCollection and BinaryCollection
collection_dsData structure helpers (list, map, set, queue) on Collection
optionsOption structs for configuring every operation
resultsResult types returned by operations
errorError and ErrorKind
subdocSub-document operation specs (LookupInSpec, MutateInSpec)
searchFull-Text Search queries, facets, sorting, and vector search
transcodingEncoding/decoding helpers (JSON, raw binary, raw JSON, raw string)
managementCluster management (buckets, collections, users, query indexes, search indexes)
durability_levelDurabilityLevel constants
mutation_stateMutationState for scan consistency
retryRetry strategies (BestEffortRetryStrategy)
diagnosticsConnection state types
service_typeServiceType constants
logging_meterLoggingMeter for operation metrics
threshold_logging_tracerThresholdLoggingTracer for slow-operation logging

§Feature Flags

FeatureDefaultDescription
default-tlsAlias for rustls-tls
rustls-tlsUse rustls for TLS (recommended)
native-tlsUse the platform’s native TLS stack instead of rustls
unstable-dns-optionsEnable DNS-SRV bootstrap configuration (volatile)
unstable-error-constructionAllow explicit Error construction (e.g. for mocking)

Note that the SDK does not typically use feature flags for API stability levels. Instead, unstable features are commented with uncommitted or volatile.

Modules§

authenticator
Authentication types for connecting to a Couchbase cluster.
bucket
A Couchbase Bucket and its associated operations.
cluster
The main entry point for the Couchbase SDK.
collection
Couchbase Collection — the primary container for documents.
collection_ds
Data structure operations on a Collection.
diagnostics
Diagnostics types for inspecting connection state.
durability_level
Durability level constants for mutation operations.
error
Error types for all Couchbase SDK operations.
logging_meter
Periodic operation-metrics logging via a tracing layer.
management
Cluster management APIs.
mutation_state
Mutation state tracking for scan consistency.
options
Configuration options for all SDK operations.
results
Result types returned by SDK operations.
retry
Retry strategies for Couchbase operations.
scope
A Scope within a Couchbase Bucket.
search
Full-Text Search (FTS) types for building and executing search requests.
service_type
Couchbase service type identifiers.
subdoc
Sub-document operation specifications.
threshold_logging_tracer
Slow-operation threshold logging via a tracing layer.
transcoding
Transcoding utilities for encoding and decoding document content.

Macros§

mutation_state