Secondary index
For the complete documentation index see: llms.txt
All documentation pages available in markdown.
Creating a secondary index
You can create and delete secondary indexes from the database using the Aerospike Rust client.
To create a secondary index, invoke either Client::create_index_on_bin() or Client::create_index_using_expression().
Secondary indexes are created asynchronously, so each method returns an IndexTask before the
index propagates to the cluster. Call IndexTask::wait_till_complete() to block until the index
is fully built.
Building an index scans the set on every node and uses memory on each node. Create indexes during a low-traffic period, and wait for the build to finish before you query. Creating an index that already exists can fail with ResultCode::IndexFound. To rerun an example, first remove the index as described in Removing a secondary index.
The following example creates a numeric index idx_test_bar_baz in
namespace test within set bar and bin baz, then waits for it to be ready:
use std::time::Duration;use aerospike::Task;
match client .create_index_on_bin( &AdminPolicy::default(), "test", "bar", "baz", "idx_test_bar_baz", IndexType::Numeric, CollectionIndexType::Default, None, ) .await{ Ok(index_task) => { index_task .wait_till_complete(Some(Duration::from_secs(30))) .await?; println!("Index created."); } Err(err) => println!("Failed to create index: {}", err),}📖 API reference:
Client::create_index_on_bin|IndexTask::wait_till_complete
Secondary indexes can only be created once on the server as a combination of
namespace, set, and bin name with an integer, string, geospatial, or blob data
type. For example, if you define a secondary index to index bin x that
contains integer values, then only records containing bins named x with
integer values are indexed. Other records with a bin named x that contain
non-integer values are not indexed.
The IndexType argument selects the data type that the index covers:
IndexType | Indexes bins that hold |
|---|---|
Numeric | Integers. Use it with any server version. |
Integer | Integers. Requires Database 8.2.0 or later. From 8.2.0 on, prefer Integer; the server still accepts Numeric. |
String | Strings. |
Geo2DSphere | GeoJSON values. |
Blob | Byte arrays. Requires Database 7.0 or later. |
The CollectionIndexType argument selects what the index covers inside a bin:
CollectionIndexType | Indexes |
|---|---|
Default | The bin’s own value. Use it for scalar bins. |
List | Each element of a list bin. |
MapKeys | Each key of a map bin. |
MapValues | Each value of a map bin. |
📖 API reference:
IndexType|CollectionIndexType
When an index management call is made to any node in the Aerospike Database cluster, the information automatically propagates to the remaining nodes.
Removing a secondary index
To remove a secondary index using Client::drop_index():
match client.drop_index(&AdminPolicy::default(), "test", "bar", "idx_test_bar_baz").await { Err(err) => println!("Couldn't drop index: {}", err), _ => {}}📖 API reference:
Client::drop_index
Defining the query
Use query::Statement to define a query.
First, create an instance of Statement by specifying the namespace test and
set bar to query. Optionally, you can specify a list of bin names to
restrict which record bins are returned by the query. If you wish to return all
bins, use Bins::All.
use aerospike::Statement;
let mut stmt = Statement::new("test", "bar", Bins::Some(vec!["name".into(), "age".into()]));📖 API reference:
Statement::new
Applying filters
To query a secondary index, specify a filter on the query. The server accepts only one filter per query.
Use the Filter type. Common constructors:
Filter::equal(bin, value): equality filter for integer or string values.Filter::range(bin, begin, end): inclusive numeric range filter.Filter::contains(bin, value, collection_index_type)andFilter::contains_range(...): filters for collection secondary indexes.Filter::geo_within_region,Filter::geo_within_radius, andFilter::geo_contains: geospatial filters.
use aerospike::query::Filter;
stmt.set_filter(Filter::equal("status", "active"));This example uses a numeric index on bin baz in namespace test within set bar to find all records with values from 0 to 100 inclusive:
stmt.set_filter(Filter::range("baz", 0_i64, 100_i64));📖 API reference:
Statement::set_filter
Executing the query
To execute the query, invoke Client::query:
pub async fn query( &self, policy: &QueryPolicy, partition_filter: PartitionFilter, statement: Statement, ) -> Result<Arc<Recordset>>📖 API reference:
Client::query
Where,
policy: Query behavior definition.partition_filter: Query partition filter, which acts something like a cursor. For this tutorial, set this toPartitionFilter::all().statement: Query to execute.
Recordset lets you iterate over the results of the query.
To execute the query and iterate over the results:
let qpolicy = QueryPolicy::default();let pf = PartitionFilter::all();match client.query(&qpolicy, pf, stmt).await { Ok(rs) => { let mut rs = rs.into_stream(); while let Some(res) = rs.next().await { match res { Ok(rec) => { // .. process record }
Err(err) => println!("Error fetching record: {}", err), } } }
Err(err) => println!("Error with query: {}", err),}📖 API reference:
QueryPolicy::default|PartitionFilter::all|Client::query
Query a string index
To query a string bin, create the index with IndexType::String, and then filter with Filter::equal. This example indexes the status bin, writes two records, and queries for the records whose status is "active". Bins::Some limits the returned bins to status:
use std::time::Duration;use aerospike::{ as_bin, as_key, as_list, as_val, AdminPolicy, Bins, CollectionIndexType, IndexType, PartitionFilter, QueryPolicy, Statement, Task, WritePolicy,};use aerospike::query::Filter;use futures::stream::StreamExt;
// Create the index and wait until it's built.let index_task = client .create_index_on_bin( &AdminPolicy::default(), "test", "users", "status", "status_idx", IndexType::String, CollectionIndexType::Default, None, ) .await?;index_task.wait_till_complete(Some(Duration::from_secs(30))).await?;
let policy = WritePolicy::default();client.put(&policy, &as_key!("test", "users", "user-1"), &[as_bin!("status", "active")]).await?;client.put(&policy, &as_key!("test", "users", "user-2"), &[as_bin!("status", "inactive")]).await?;
let mut stmt = Statement::new("test", "users", Bins::Some(vec!["status".into()]));stmt.set_filter(Filter::equal("status", "active"));let rs = client.query(&QueryPolicy::default(), PartitionFilter::all(), stmt).await?;let mut stream = rs.into_stream();while let Some(result) = stream.next().await { let record = result?; println!("{:?}", record.bins);}📖 API reference:
IndexType::String|Filter::equal|Bins::Some
Query the elements of a list
To find records by the elements inside a list bin, create the index with CollectionIndexType::List. The index type is the type of the elements, here IndexType::String. Then filter with Filter::contains, passing the same CollectionIndexType:
let index_task = client .create_index_on_bin( &AdminPolicy::default(), "test", "products", "tags", "tags_idx", IndexType::String, CollectionIndexType::List, None, ) .await?;index_task.wait_till_complete(Some(Duration::from_secs(30))).await?;
let policy = WritePolicy::default();client.put(&policy, &as_key!("test", "products", "p1"), &[as_bin!("name", "p1"), as_bin!("tags", as_list!("sale", "new"))]).await?;client.put(&policy, &as_key!("test", "products", "p2"), &[as_bin!("name", "p2"), as_bin!("tags", as_list!("clearance"))]).await?;client.put(&policy, &as_key!("test", "products", "p3"), &[as_bin!("name", "p3"), as_bin!("tags", as_list!("sale"))]).await?;
// Find every product whose tags list contains "sale".let mut stmt = Statement::new("test", "products", Bins::Some(vec!["name".into()]));stmt.set_filter(Filter::contains("tags", "sale", CollectionIndexType::List));let rs = client.query(&QueryPolicy::default(), PartitionFilter::all(), stmt).await?;let mut stream = rs.into_stream();while let Some(result) = stream.next().await { let record = result?; println!("{:?}", record.bins.get("name"));}📖 API reference:
Filter::contains|CollectionIndexType::List|as_list!
The same pattern indexes map keys or map values: create the index with CollectionIndexType::MapKeys or CollectionIndexType::MapValues, and pass the same value to Filter::contains.
Query a geospatial index
To query by location, store each location as a GeoJSON value, create the index with IndexType::Geo2DSphere, and filter with Filter::geo_within_radius. Build the value with as_geo! from a GeoJSON string. GeoJSON coordinates are [longitude, latitude].
Filter::geo_within_radius(bin, longitude, latitude, radius) takes the radius in meters and matches the points inside that circle:
use aerospike::as_geo;
let index_task = client .create_index_on_bin( &AdminPolicy::default(), "test", "places", "loc", "loc_idx", IndexType::Geo2DSphere, CollectionIndexType::Default, None, ) .await?;index_task.wait_till_complete(Some(Duration::from_secs(30))).await?;
let policy = WritePolicy::default();let places = [ ("place-1", -122.4194, 37.7749), ("place-2", -122.2711, 37.8044), ("place-3", -118.2437, 34.0522),];for (name, longitude, latitude) in places { let point = format!(r#"{{"type": "Point", "coordinates": [{longitude}, {latitude}]}}"#); let bins = [as_bin!("name", name), as_bin!("loc", as_geo!(point))]; client.put(&policy, &as_key!("test", "places", name), &bins).await?;}
// Find the places within 20,000 meters of longitude -122.4194, latitude 37.7749.let mut stmt = Statement::new("test", "places", Bins::Some(vec!["name".into()]));stmt.set_filter(Filter::geo_within_radius("loc", -122.4194, 37.7749, 20_000.0));let rs = client.query(&QueryPolicy::default(), PartitionFilter::all(), stmt).await?;let mut stream = rs.into_stream();while let Some(result) = stream.next().await { let record = result?; println!("{:?}", record.bins.get("name"));}📖 API reference:
IndexType::Geo2DSphere|as_geo!|Filter::geo_within_radius
Cursor-based pagination
// Paginate query results in pages of 100 records.let mut pf = PartitionFilter::all();let page_size: u64 = 100;
loop { let mut stmt = Statement::new("test", "bar", Bins::All); stmt.set_filter(Filter::range("baz", 0_i64, 100_i64));
let mut qpolicy = QueryPolicy::default(); qpolicy.max_records = page_size;
let rs = client.query(&qpolicy, pf, stmt).await?; let mut stream = rs.into_stream(); let mut count: u64 = 0;
while let Some(result) = stream.next().await { match result { Ok(record) => count += 1, Err(err) => println!("Error: {err}"), } }
pf = stream .partition_filter() .expect("partition filter should be available after query");
if pf.done() || count < page_size { break; }}Complete example
The following complete program connects to an Aerospike instance on localhost, writes sample records, creates a secondary index on bin baz, runs a query using that index, and then closes the client connection.
#[macro_use]extern crate aerospike;
use std::time::Duration;
use aerospike::{ as_bin, as_key, AdminPolicy, Bins, Client, ClientPolicy, CollectionIndexType, IndexType, PartitionFilter, QueryPolicy, Statement, Task, WritePolicy,};use aerospike::query::Filter;use futures::stream::StreamExt;
#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> { // Connect to localhost Aerospike. let client = Client::new(&ClientPolicy::default(), &"127.0.0.1:3000").await?; println!("Connected to Aerospike.");
// Write a few records so the query has data to return. for (id, baz_value) in [(1, 10), (2, 55), (3, 120)] { let key = as_key!("test", "bar", id); let bins = vec![ as_bin!("name", format!("item-{id}")), as_bin!("baz", baz_value), ]; client.put(&WritePolicy::default(), &key, &bins).await?; }
// Create a secondary index on test.bar.baz (ignore if it already exists). let index_name = "idx_test_bar_baz_complete_example"; match client .create_index_on_bin( &AdminPolicy::default(), "test", "bar", "baz", index_name, IndexType::Numeric, CollectionIndexType::Default, None, ) .await { Ok(index_task) => { index_task .wait_till_complete(Some(Duration::from_secs(30))) .await?; println!("Secondary index created: {index_name}"); } Err(e) => { println!("Index already exists or creation skipped: {e}"); } }
// Query the secondary index. let mut stmt = Statement::new("test", "bar", Bins::All); stmt.set_filter(Filter::range("baz", 0_i64, 100_i64));
let rs = client .query(&QueryPolicy::default(), PartitionFilter::all(), stmt) .await?; let mut stream = rs.into_stream();
println!("Query results (baz between 0 and 100):"); while let Some(result) = stream.next().await { match result { Ok(record) => { println!("key: {:?}", record.key); println!("bins: {:?}", record.bins); } Err(err) => eprintln!("Error fetching record: {err}"), } }
// Close the connection. client.close().await?; println!("Connection closed.");
Ok(())}📖 API reference:
Client::new|Client::put|Client::create_index_on_bin|IndexTask::wait_till_complete|Statement::new|Statement::set_filter|PartitionFilter::all|Client::query|Client::close
Expected results
When run against a local Aerospike instance with namespace test and set bar, output should be similar to:
Connected to Aerospike.Secondary index created: idx_test_bar_baz_complete_exampleQuery results (baz between 0 and 100):{"name": String("item-1"), "baz": Int(10)}{"name": String("item-2"), "baz": Int(55)}Connection closed.