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 fromCluster::bucket().Scope— A namespace within a bucket. Obtained fromBucket::scope(). Supports scoped queries and Full-Text Search.Collection— Holds documents. Obtained fromScope::collection(). Supports all KV, sub-document, and data structure operations.BinaryCollection— Accessed viaCollection::binary(). Provides binary append/prepend and counter operations.
§Modules Overview
| Module | Description |
|---|---|
authenticator | Authentication types (PasswordAuthenticator, CertificateAuthenticator) |
cluster | Cluster — the main entry point |
bucket | Bucket — bucket-level operations |
scope | Scope — scoped queries and search |
collection | Collection and BinaryCollection |
collection_ds | Data structure helpers (list, map, set, queue) on Collection |
options | Option structs for configuring every operation |
results | Result types returned by operations |
error | Error and ErrorKind |
subdoc | Sub-document operation specs (LookupInSpec, MutateInSpec) |
search | Full-Text Search queries, facets, sorting, and vector search |
transcoding | Encoding/decoding helpers (JSON, raw binary, raw JSON, raw string) |
management | Cluster management (buckets, collections, users, query indexes, search indexes) |
durability_level | DurabilityLevel constants |
mutation_state | MutationState for scan consistency |
retry | Retry strategies (BestEffortRetryStrategy) |
diagnostics | Connection state types |
service_type | ServiceType constants |
logging_meter | LoggingMeter for operation metrics |
threshold_logging_tracer | ThresholdLoggingTracer for slow-operation logging |
§Feature Flags
| Feature | Default | Description |
|---|---|---|
default-tls | ✅ | Alias for rustls-tls |
rustls-tls | ✅ | Use rustls for TLS (recommended) |
native-tls | ❌ | Use the platform’s native TLS stack instead of rustls |
unstable-dns-options | ❌ | Enable DNS-SRV bootstrap configuration (volatile) |
unstable-error-construction | ❌ | Allow 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
Bucketand 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
tracinglayer. - 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
Scopewithin a CouchbaseBucket. - 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
tracinglayer. - transcoding
- Transcoding utilities for encoding and decoding document content.