Rust client for the Aerospike database
Welcome to Aerospike's official Rust client.
Execution models:
Advanced data operations:
BatchOperationAPI.Policy and expression enhancements:
allow_inline_ssd, respond_all_keys
in BatchPolicy, read_touch_ttl, and QueryDuration in QueryPolicy.records_per_second for query throttling.Data model improvements:
Exists,
OrderedMap, UnorderedMap now supported for
CDT reads.TryFromaerospike::Value for seamless type interoperability.Infinity, Wildcard, and
corresponding expression builders expressions::infinity() and
expressions::wildcard().expressions::record_size() and expressions::memory_size()
for granular control.Take a look at the changelog for more details.
We are working toward full functional parity with our other officially supported clients. Features on the roadmap include:
Prerequisites:
Clone the repository and change into the project directory:
git clone --single-branch --branch v2 https://github.com/aerospike/aerospike-client-rust.git
cd aerospike-client-rustBuild the project:
cargo buildTo use the client in your own project, add one of the following to your Cargo.toml:
… Then run cargo build in your project.
The following code examples demonstrate some of the Rust client's new features.
The examples below use the async client (default). For a blocking API with no .await, see Sync client below.
Connect to an Aerospike cluster without TLS:
use std::env;
use aerospike::{Client, ClientPolicy};
let policy = ClientPolicy::default();
let hosts = env::var("AEROSPIKE_HOSTS")
.unwrap_or_else(|_| "127.0.0.1:3000".to_string());
let client = Client::new(&policy, &hosts)
.await
.expect("Failed to connect to cluster");The sync feature exposes blocking APIs — no async/.await at call sites. However, the client still uses Tokio
internally for cluster management, so a Tokio runtime must be running for the duration of your program.
Cargo.toml
[dependencies]
aerospike = { version = "", default-features = false, features = ["rt-tokio", "sync"] }
tokio = { version = "1", features = ["full"] } # required even for sync usageSwap
rt-tokioforrt-async-stdif your project uses async-std instead.
Example:
…Why does sync need a Tokio runtime? The
syncfeature wraps the async client and provides blocking call sites — it does not replace the underlying async runtime. Cluster tending (node discovery, connection pooling) runs as a background Tokio task regardless of which API surface you use. CallingClient::newoutside of a runtime context will panic withthere is no reactor running.
Connect to an Aerospike cluster with TLS but without client certificate authentication:
…Connect to an Aerospike cluster with TLS and mutual authentication using client certificates:
…Note: To use TLS features, enable the tls feature in your Cargo.toml:
[dependencies]
aerospike = { version = "...", features = ["tls"] }……A complete working example can be found in examples/batch_operations.rs.
The Rust client supports various query patterns for retrieving data from Aerospike. Below are examples demonstrating different query capabilities.
Query records where a bin equals a specific value:
use aerospike::{QueryPolicy, Statement, Bins};
use aerospike::query::PartitionFilter;
let policy = QueryPolicy::default();
let mut stmt = Statement::new(namespace, set_name, Bins::All);
stmt.add_filter(as_eq!("bin_name", 5));
let rs = client.query(&policy, PartitionFilter::all(), stmt).await.unwrap();
let mut rs = rs.into_stream();
while let Some(r) = rs.next().await {
println!("Record: {:?}", r.unwrap());
}Query records where a bin value falls within a range:
let policy = QueryPolicy::default();
let mut stmt = Statement::new(namespace, set_name, Bins::All);
stmt.add_filter(as_range!("bin_name", 0, 100));
let rs = client.query(&policy, PartitionFilter::all(), stmt).await.unwrap();
let mut rs = rs.into_stream();
while let Some(r) = rs.next().await {
println!("Record: {:?}", r.unwrap());
}Query records but only retrieve metadata (no bin data):
let policy = QueryPolicy::default();
let mut stmt = Statement::new(namespace, set_name, Bins::None);
stmt.add_filter(as_range!("bin_name", 0, 100));
let rs = client.query(&policy, PartitionFilter::all(), stmt).await.unwrap();
let mut rs = rs.into_stream();
while let Some(r) = rs.next().await {
let rec = r.unwrap();
println!("Generation: {}, TTL: {}", rec.generation, rec.expiration);
}Query records in batches using partition cursors for pagination:
let policy = QueryPolicy::default();
let mut pf = PartitionFilter::all();
while !pf.done() {
let stmt = Statement::new(namespace, set_name, Bins::All);
let rs = client.query(&policy, pf, stmt).await.unwrap();
let mut rs = rs.into_stream();
while let Some(r) = rs.next().await {
println!("Record: {:?}", r.unwrap());
}
// Get the next partition filter to continue pagination
pf = rs.partition_filter().await.unwrap();
}Process query results in parallel using multiple async tasks:
…Use filter expressions for more complex filtering logic:
use aerospike_core::expressions::{eq, int_bin, int_val};
let mut policy = QueryPolicy::default();
policy.base_policy.filter_expression.replace(
eq(int_bin("bin_name".to_string()), int_val(42))
);
let stmt = Statement::new(namespace, set_name, Bins::All);
let rs = client.query(&policy, PartitionFilter::all(), stmt).await.unwrap();
let mut rs = rs.into_stream();
while let Some(r) = rs.next().await {
println!("Record: {:?}", r.unwrap());
}Control query throughput by limiting records per second:
let mut policy = QueryPolicy::default();
policy.records_per_second = 100; // Limit to 100 records/second
let mut stmt = Statement::new(namespace, set_name, Bins::All);
stmt.add_filter(as_range!("bin_name", 0, 1000));
let rs = client.query(&policy, PartitionFilter::all(), stmt).await.unwrap();
let mut rs = rs.into_stream();
while let Some(r) = rs.next().await {
match r {
Ok(rec) => println!("Record: {:?}", rec),
Err(err) => eprintln!("Error: {:?}", err),
}
}Before running queries, you need to create a secondary index on the bin you want to query:
use aerospike_core::{AdminPolicy, IndexType, CollectionIndexType};
let policy = AdminPolicy::default();
let task = client
.create_index_on_bin(
&policy,
namespace,
set_name,
"bin_name",
"idx_bin_name",
IndexType::Numeric,
CollectionIndexType::Default,
None,
)
.await
.expect("Failed to create index");
// Wait for index creation to complete
task.wait_till_complete(None).await.unwrap();For a complete working example with all query patterns, see examples/query.rs.
The Rust client provides flexible timeout configuration through socket_timeout and total_timeout parameters in policies. Understanding how these interact is crucial for handling network issues and controlling command execution time.
socket_timeout: Socket idle timeout when processing a database command (in milliseconds). Default value 5000 (5 seconds).total_timeout: Total command timeout, including retries (in milliseconds). Default value 0.socket_timeout inherits total_timeout valuesocket_timeout capped at total_timeoutWhen a socket timeout occurs, the client checks max_retries and total_timeout. If neither is exceeded, the command is automatically retried.
Rust client exposes these parameters through the Read/Write policy, and can be tuned as below:
use aerospike::{ReadPolicy, Bins};
let mut policy = ReadPolicy::default();
policy.base_policy.socket_timeout = 0;
policy.base_policy.total_timeout = 0;
let rec = client.get(&policy, &key, Bins::All).await;The timeout_delay parameter controls how the client handles sockets after a read timeout. This is particularly important for cloud deployments.
let mut policy = ReadPolicy::default();
policy.base_policy.socket_timeout = 2000; // 2 second socket timeout
policy.base_policy.total_timeout = 10000; // 10 second total timeout
policy.base_policy.timeout_delay = 3000; // 3 second delay for socket recovery
let rec = client.get(&policy, &key, Bins::All).await;How timeout_delay works:
timeout_delay = 0 (default): Socket is immediately closed on timeouttimeout_delay > 0: After a socket read timeout, the client attempts to drain remaining data from the socket in the background for up to timeout_delay millisecondsWhy use timeout_delay?
Many cloud providers experience performance issues when clients close sockets while the server still has data to write (results in TCP RST packets). Draining the socket before closing avoids this penalty.
Trade-offs:
No open issues yet, or sync has not completed.