Quickstart
For the complete documentation index see: llms.txt
All documentation pages available in markdown.
This Quickstart guide walks you through the essentials of deploying an Aerospike Database and building a simple application to interact with it. You’ll learn how to quickly spin up a local development environment using Docker, set up your project in your preferred programming language, connect to the database, and perform basic read and write operations.
Deploy Aerospike with Docker
The quickest and easiest way to get up and running quickly is with Docker.
The following command creates a single node Aerospike Enterprise database, using the latest version, equipped with a single node feature key and template configuration. No additional setup is needed.
docker run -d --name aerospike -p 3000-3002:3000-3002 aerospike/aerospike-server-enterprise:latestIf you’d like to customize your deployment, see configuring Aerospike for more information. Aerospike has a variety of options when it comes to deploying the database.
- AeroLab is a community-supported tool for quickly spinning up development clusters.
- You can deploy containers directly using Docker or Kubernetes Operator.
- Aerospike supports the three major cloud providers, AWS, GCP, and Azure.
- Bare metal deployments are available with a variety of Linux distributions as well.
Browse your cluster with Voyager
After deploying Aerospike Database, point Aerospike Voyager at the cluster you just started. Voyager is a free desktop app that gives you a visual workspace for adding sample data, browsing, and editing records.
Download Voyager and connect it to 127.0.0.1:3000. See Connecting to clusters for more information.
Set up your development environment
Grab your favorite IDE and create a new project.
The Java SDK requires Java 21 or later. For this quickstart we’ll be using Maven for our build manager. After creating your project, add the following dependency to the pom.xml file.
<dependencies> <dependency> <groupId>com.aerospike</groupId> <artifactId>aerospike-client-sdk</artifactId> <version>1.0.0</version> </dependency></dependencies>If you’re using a different build manager, or looking for more information on getting started with the Java SDK, check out the Developer SDK install docs.
Using Python 3.11 or later and pip, run the following command to install the Aerospike Developer SDK.
python3 -m pip install aerospike-sdkIf you’re looking for more information on getting started with the Python SDK, check out the Developer SDK install docs.
Build from source code
-
Clone the Git repository:
git clone --single-branch --branch v2 https://github.com/aerospike/aerospike-client-rust.gitcd aerospike-client-rust -
Build the project:
cargo build
Use as a dependency
-
To use the client in your own project, add one of the following to your
Cargo.toml:[dependencies]# Async API with tokio Runtimeaerospike = { version = "2.2.0", features = ["rt-tokio"]}# OR# Async API with async-std runtimeaerospike = { version = "2.2.0", features = ["rt-async-std"]}# The library still supports the old sync interface, but it will be deprecated in the future.# This is only for compatibility reasons and will be removed in a later stage.# Sync API with tokioaerospike = { version = "2.2.0", default-features = false, features = ["rt-tokio", "sync"]}# OR# Sync API with async-stdaerospike = { version = "2.2.0", default-features = false, features = ["rt-async-std", "sync"]} -
Build the project:
cargo build
The compiled C# client library dll is available on NuGet. To install, run the following command in the Package Manager Console.
PM> Install-Package Aerospike.ClientIf you’re looking for more information on getting started with the C# client, check out the C# client install docs.
After setting up your Go project, run the following to get the Aerospike Go Client in your $GOPATH.
go get github.com/aerospike/aerospike-client-go/v8@v8.9.0If you’re looking for more information on getting started with the Go client, check out the Go client install docs.
Using npm to install Aerospike, run the following command inside your project directory.
npm install aerospikeIf you’re looking for more information on getting started with the Node.js client, check out the Node.js client install docs.
Download the C client package for your platform from the Download page. Install its development package, which compiles your application with the client, and its runtime package, which runs it: with dpkg -i on Debian and Ubuntu, or rpm -i on Red Hat and Amazon Linux.
dpkg -i DEVELOPMENT_PACKAGE RUNTIME_PACKAGEIf you’re looking for more information on getting started with the C client, check out the C client install docs.
For this quickstart we’ll be using Maven for our build manager. After creating your project, add the following dependency to the pom.xml file. For Java 8 through 20, the artifact is aerospike-client-jdk8.
<dependencies> <dependency> <groupId>com.aerospike</groupId> <artifactId>aerospike-client-jdk21</artifactId> <version>10.5.0</version> </dependency></dependencies>If you’re using a different build manager, or looking for more information on getting started with the Java client, check out the Java client install docs.
Using Python3 and pip, run the following command to install the Aerospike client.
python3 -m pip install aerospikeIf you’re looking for more information on getting started with the Python client, check out the Python client install docs.
Application basics
The following code block contains the necessary imports and basic application shell to get started.
package com.sample;
import java.time.Duration;
import com.aerospike.client.sdk.AerospikeException;import com.aerospike.client.sdk.Cluster;import com.aerospike.client.sdk.ClusterDefinition;import com.aerospike.client.sdk.DataSet;import com.aerospike.client.sdk.Key;import com.aerospike.client.sdk.Record;import com.aerospike.client.sdk.Session;import com.aerospike.client.sdk.policy.Behavior;import com.aerospike.client.sdk.policy.Behavior.Selectors;
public class App{ public static void main( String[] args ) {
}}from datetime import timedelta
from aerospike_sdk import Behavior, DataSetfrom aerospike_sdk.exceptions import AerospikeErrorfrom aerospike_sdk.sync import ClusterDefinitionuse aerospike::{as_bin, as_key, Bins, Client, ClientPolicy, Error, ReadPolicy, WritePolicy};
#[tokio::main]async fn main() -> Result<(), Error> {
Ok(())}using System;using Aerospike.Client;
public class App{ public static void Main() {
}}package main
import ( "log" "time"
"github.com/aerospike/aerospike-client-go/v8")
func main() {
}const Aerospike = require('aerospike');
const main = async () => {
}
main();#include <stdio.h>#include <aerospike/aerospike.h>#include <aerospike/aerospike_key.h>#include <aerospike/as_record.h>
int main(void){
return 0;}package com.sample;
import com.aerospike.client.IAerospikeClient;import com.aerospike.client.AerospikeClient;import com.aerospike.client.AerospikeException;import com.aerospike.client.Bin;import com.aerospike.client.Host;import com.aerospike.client.Key;import com.aerospike.client.Record;import com.aerospike.client.policy.WritePolicy;import com.aerospike.client.policy.Policy;
public class App{ public static void main( String[] args ) {
}}import aerospikefrom aerospike import exception as exClient connection
The minimum information you need to connect to an Aerospike database is the server IP address and port number. If you’re using the basic Docker install from step one, the following information should work just fine.
If your database is deployed with a cloud provider or installed elsewhere, you’ll need information specific to your cluster setup.
Create variables to store the connection information, as well as the namespace and set name.
Using the address and port from above, instantiate the Aerospike client.
String address = "127.0.0.1"; // Aerospike addressint port = 3000; // Aerospike portString namespace = "test"; // Cluster namespaceString set = "foo"; // Set name within namespace
// The session's Behavior sets the timeout: 5 seconds for every commandBehavior behavior = Behavior.DEFAULT.deriveWithChanges("quickstart", b -> b .on(Selectors.all(), ops -> ops.abandonCallAfter(Duration.ofSeconds(5))));
Cluster cluster = new ClusterDefinition(address, port).connect();Session session = cluster.createSession(behavior);address = "127.0.0.1" # Aerospike addressport = 3000 # Aerospike portnamespace = "test" # Cluster namespacesetname = "foo" # Set name within namespace
# The session's Behavior sets the timeout: 5 seconds for every commandbehavior = Behavior.DEFAULT.derive_with_changes("quickstart", total_timeout=timedelta(seconds=5))
cluster = ClusterDefinition(address, port).connect()session = cluster.create_session(behavior)let address = "127.0.0.1"; // Aerospike addresslet port = 3000; // Aerospike portlet namespace = "test"; // Cluster namespacelet set = "foo"; // Set name within namespace
let client = Client::new(&ClientPolicy::default(), &format!("{address}:{port}")).await?;string address = "127.0.0.1"; // Aerospike addressint port = 3000; // Aerospike portstring name_space = "test"; // Cluster namespacestring set = "foo"; // Set name within namespace
AerospikeClient client = new AerospikeClient(null, new Host(address, port));address := "127.0.0.1" // Aerospike addressport := 3000 // Aerospike portnamespace := "test" // Cluster namespaceset := "foo" // Set name within namespace
// Create the client and connect to the databaseclient, err := aerospike.NewClient(address, port)if err != nil { log.Fatal(err)}defer client.Close()const address = "127.0.0.1"; // Aerospike addressconst port = 3000; // Aerospike portconst namespace = "test"; // Cluster namespaceconst set = "foo"; // Set name within namespace
let client = await Aerospike.connect({ hosts: `${address}:${port}` });const char* address = "127.0.0.1"; // Aerospike addressint port = 3000; // Aerospike portconst char* namespace = "test"; // Cluster namespaceconst char* set = "foo"; // Set name within namespace
as_config config;as_config_init(&config);as_config_add_host(&config, address, port);
aerospike as;aerospike_init(&as, &config);
as_error err;if (aerospike_connect(&as, &err) != AEROSPIKE_OK) { fprintf(stderr, "Error connecting: %s\n", err.message); return 1;}String address = "127.0.0.1"; // Aerospike addressInteger port = 3000; // Aerospike portString namespace = "test"; // Cluster namespaceString set = "foo"; // Set name within namespace
IAerospikeClient client = new AerospikeClient(address, port);address = "127.0.0.1" # Aerospike addressport = 3000 # Aerospike portnamespace = "test" # Cluster namespacesetname = "foo" # Set name within namespace
client = aerospike.client({'hosts': [(address, port)]})Write a record
-
Create the record key from a
DataSet, which names the namespace and set, and a user defined key. The session’sBehavioralready sets the timeout, so there is no write policy to create.Key key = DataSet.of(namespace, set).id("bar"); -
Write the record to Aerospike, with a bin to store data within the new record.
try {session.upsert(key).bin("myBin").setTo("Hello World!").execute();System.out.println("Successfully wrote record");}catch (AerospikeException e) {e.printStackTrace();}
-
Create the record key from a
DataSet, which names the namespace and set, and a user defined key. The session’sBehavioralready sets the timeout, so there is no write policy to create.key = DataSet.of(namespace, setname).id("bar") -
Write the record to Aerospike, with a bin to store data within the new record.
try:session.upsert(key).put({"myBin": "Hello World!"}).execute()print("Successfully wrote record")except AerospikeError as e:print(e)
-
Create a
WritePolicyto set thetotal_timeoutfor writes.let mut write_policy = WritePolicy::default();write_policy.base_policy.total_timeout = 5000; -
Create the record key, a tuple consisting of namespace, set name, and user defined key
let key = as_key!(namespace, set, "bar"); -
Create a bin to store data within the new record
let bin = as_bin!("myBin", "Hello World!"); -
Write the record to Aerospike.
match client.put(&write_policy, &key, &[bin]).await {Ok(()) => println!("Successfully wrote record"),Err(err) => println!("Error writing record: {err}"),}
-
Create a
WritePolicyto set thetotalTimeoutfor writes.WritePolicy writePolicy = new WritePolicy();writePolicy.totalTimeout = 5000; -
Create the record key, a tuple consisting of namespace, set name, and user defined key
Key key = new Key(name_space, set, "bar"); -
Create a bin to store data within the new record
Bin bin = new Bin("myBin", "Hello World!"); -
Write the record to Aerospike.
try{client.Put(writePolicy, key, bin);Console.WriteLine("Successfully wrote record");}catch (AerospikeException e){Console.WriteLine(e);}
-
Create a
WritePolicyto set theTotalTimeoutfor writes.writePolicy := aerospike.NewWritePolicy(0, 0)writePolicy.TotalTimeout = 5000 * time.Millisecond -
Create the record key, a tuple consisting of namespace, set name, and user defined key
key, err := aerospike.NewKey(namespace, set, "bar")if err != nil {log.Fatal(err)} -
Create a bin to store data within the new record
bin := aerospike.NewBin("myBin", "Hello World!") -
Write the record to Aerospike.
err = client.PutBins(writePolicy, key, bin)if err != nil {log.Fatal(err)}log.Println("Successfully wrote record")
-
Create a
WritePolicyto set thetotalTimeoutfor writes.let writePolicy = new Aerospike.WritePolicy({totalTimeout: 5000}); -
Create the record key, a tuple consisting of namespace, set name, and user defined key
let key = new Aerospike.Key(namespace, set, "bar"); -
Create a bin to store data within the new record
let bin = { myBin: "Hello World!" }; -
Write the record to Aerospike.
try {await client.put(key, bin, [], writePolicy);console.info("Successfully wrote record");}catch (err) {console.error(err);}
-
Create an
as_policy_writeto set thetotal_timeoutfor writes.as_policy_write write_policy;as_policy_write_init(&write_policy);write_policy.base.total_timeout = 5000; -
Create the record key, from the namespace, set name, and user defined key
as_key key;as_key_init_str(&key, namespace, set, "bar"); -
Create a bin to store data within the new record
as_record rec;as_record_inita(&rec, 1);as_record_set_str(&rec, "myBin", "Hello World!"); -
Write the record to Aerospike.
if (aerospike_key_put(&as, &err, &write_policy, &key, &rec) == AEROSPIKE_OK) {printf("Successfully wrote record\n");}else {fprintf(stderr, "Error writing record: %s\n", err.message);}as_record_destroy(&rec);
-
Create a
WritePolicyto set thetotalTimeoutfor writes.WritePolicy writePolicy = new WritePolicy();writePolicy.totalTimeout = 5000; -
Create the record key, a tuple consisting of namespace, set name, and user defined key
Key key = new Key(namespace, set, "bar"); -
Create a bin to store data within the new record
Bin bin = new Bin("myBin", "Hello World!"); -
Write the record to Aerospike.
try {client.put(writePolicy, key, bin);System.out.println("Successfully wrote record");}catch (AerospikeException e) {e.printStackTrace();}
-
Create a
WritePolicyto set thetotalTimeoutfor writes.write_policy = {'total_timeout': 5000} -
Create the record key, a tuple consisting of namespace, set name, and user defined key
key = (namespace, setname, "bar") -
Create a bin to store data within the new record
bins = {'myBin': 'Hello World!'} -
Write the record to Aerospike.
try:client.put(key, bins, policy=write_policy)print("Successfully wrote record")except ex.ClientError as e:print(e)
Read a record
-
Using the same key from our write command, read the record back. The session’s
Behaviorsets the timeout for reads too.try {Record record = session.query(key).execute().getFirstRecord();System.out.println("Record: " + record.bins);}catch (AerospikeException e) {e.printStackTrace();}finally {cluster.close();}
-
Using the same key from our write command, read the record back. The session’s
Behaviorsets the timeout for reads too.try:record = session.query(key).first_or_raise().record_or_raise()print(record.bins)except AerospikeError as e:print(e)finally:cluster.close()
-
Create a
ReadPolicyto set thetotal_timeoutfor reads.let mut read_policy = ReadPolicy::default();read_policy.base_policy.total_timeout = 5000; -
Using the same key from our write command, read the record back.
match client.get(&read_policy, &key, Bins::All).await {Ok(record) => println!("Record: {:?}", record.bins),Err(err) => println!("Error reading record: {err}"),}client.close().await?;
-
Create a
Policyto set thetotalTimeoutfor reads.Policy readPolicy = new Policy();readPolicy.totalTimeout = 5000; -
Using the same key from our write command, read the record back.
try{Record record = client.Get(readPolicy, key);Console.WriteLine("Record: {0}", record);}catch (AerospikeException e){Console.WriteLine(e);}finally{client.Close();}
-
Create a
Policyto set theTotalTimeoutfor reads.readPolicy := aerospike.NewPolicy()readPolicy.TotalTimeout = 5000 * time.Millisecond -
Read the record.
record, err := client.Get(readPolicy, key)if err != nil {log.Fatal(err)}log.Printf("Record: %s", record.Bins)
-
Create a
Policyto set thetotalTimeoutfor reads.let readPolicy = new Aerospike.ReadPolicy({totalTimeout: 5000}); -
Using the same key from our write command, read the record back.
try {let record = await client.get(key, readPolicy);console.info("Record: %o", record.bins);}catch (err) {console.error(err);}finally {client.close();}
-
Create an
as_policy_readto set thetotal_timeoutfor reads.as_policy_read read_policy;as_policy_read_init(&read_policy);read_policy.base.total_timeout = 5000; -
Using the same key from our write command, read the record back.
as_record* record = NULL;if (aerospike_key_get(&as, &err, &read_policy, &key, &record) == AEROSPIKE_OK) {printf("Record: myBin=%s\n", as_record_get_str(record, "myBin"));as_record_destroy(record);}else {fprintf(stderr, "Error reading record: %s\n", err.message);}aerospike_close(&as, &err);aerospike_destroy(&as);
-
Create a
Policyto set thetotalTimeoutfor reads.Policy readPolicy = new Policy();readPolicy.totalTimeout = 5000; -
Using the same key from our write command, read the record back.
try {Record record = client.get(readPolicy, key);System.out.format("Record: %s", record.bins);}catch (AerospikeException e) {e.printStackTrace();}finally {client.close();}
-
Create a
Policyto set thetotalTimeoutfor reads.read_policy = {'total_timeout': 5000} -
Using the same key from our write command, read the record back.
try:(key_, meta, bins) = client.get(key, policy=read_policy)print(bins)except ex.ClientError as e:print(e)finally:client.close()
Check out the Develop topic for more in-depth code samples and content to help you get started!
Put it all together
Check out the full code sample
package com.sample;
import java.time.Duration;
import com.aerospike.client.sdk.AerospikeException;import com.aerospike.client.sdk.Cluster;import com.aerospike.client.sdk.ClusterDefinition;import com.aerospike.client.sdk.DataSet;import com.aerospike.client.sdk.Key;import com.aerospike.client.sdk.Record;import com.aerospike.client.sdk.Session;import com.aerospike.client.sdk.policy.Behavior;import com.aerospike.client.sdk.policy.Behavior.Selectors;
public class App{ public static void main( String[] args ) { // *** // Setup // ***
String address = "127.0.0.1"; // Aerospike address int port = 3000; // Aerospike port String namespace = "test"; // Cluster namespace String set = "foo"; // Set name within namespace
// The session's Behavior sets the timeout: 5 seconds for every command Behavior behavior = Behavior.DEFAULT.deriveWithChanges("quickstart", b -> b .on(Selectors.all(), ops -> ops.abandonCallAfter(Duration.ofSeconds(5))));
// Create the client and connect to the database Cluster cluster = new ClusterDefinition(address, port).connect(); Session session = cluster.createSession(behavior);
// *** // Write a record // ***
// Create the record key // A DataSet names the namespace and set; id() takes the user defined key Key key = DataSet.of(namespace, set).id("bar");
// Write the record to your database, with a bin to store data within it try { session.upsert(key) .bin("myBin").setTo("Hello World!") .execute(); System.out.println("Successfully wrote record"); } catch (AerospikeException e) { e.printStackTrace(); }
// *** // Read back the record we just wrote // ***
// Read the record try { Record record = session.query(key).execute().getFirstRecord(); System.out.println("Record: " + record.bins); } catch (AerospikeException e) { e.printStackTrace(); } finally { cluster.close(); } }}from datetime import timedelta
from aerospike_sdk import Behavior, DataSetfrom aerospike_sdk.exceptions import AerospikeErrorfrom aerospike_sdk.sync import ClusterDefinition
# ***# Setup# ***
address = "127.0.0.1" # Aerospike addressport = 3000 # Aerospike portnamespace = "test" # Cluster namespacesetname = "foo" # Set name within namespace
# The session's Behavior sets the timeout: 5 seconds for every commandbehavior = Behavior.DEFAULT.derive_with_changes("quickstart", total_timeout=timedelta(seconds=5))
# Create the client and connect to the databasecluster = ClusterDefinition(address, port).connect()session = cluster.create_session(behavior)
# ***# Write a record# ***
# Create the record key# A DataSet names the namespace and set; id() takes the user defined keykey = DataSet.of(namespace, setname).id("bar")
# Write the record to your database, with a bin to store data within ittry: session.upsert(key).put({"myBin": "Hello World!"}).execute() print("Successfully wrote record")except AerospikeError as e: print(e)
# ***# Read back the record we just wrote# ***
# Read the recordtry: record = session.query(key).first_or_raise().record_or_raise() print(record.bins)except AerospikeError as e: print(e)finally: cluster.close()use aerospike::{as_bin, as_key, Bins, Client, ClientPolicy, Error, ReadPolicy, WritePolicy};
#[tokio::main]async fn main() -> Result<(), Error> { // *** // Setup // ***
let address = "127.0.0.1"; // Aerospike address let port = 3000; // Aerospike port let namespace = "test"; // Cluster namespace let set = "foo"; // Set name within namespace
// Create the client and connect to the database let client = Client::new(&ClientPolicy::default(), &format!("{address}:{port}")).await?;
// *** // Write a record // ***
// Create a new write policy let mut write_policy = WritePolicy::default(); write_policy.base_policy.total_timeout = 5000;
// Create the record key // A tuple consisting of namespace, set name, and user defined key let key = as_key!(namespace, set, "bar");
// Create a bin to store data within the new record let bin = as_bin!("myBin", "Hello World!");
// Write the record to your database match client.put(&write_policy, &key, &[bin]).await { Ok(()) => println!("Successfully wrote record"), Err(err) => println!("Error writing record: {err}"), }
// *** // Read back the record we just wrote // ***
// Create a new read policy let mut read_policy = ReadPolicy::default(); read_policy.base_policy.total_timeout = 5000;
// Read the record match client.get(&read_policy, &key, Bins::All).await { Ok(record) => println!("Record: {:?}", record.bins), Err(err) => println!("Error reading record: {err}"), } client.close().await?;
Ok(())}using System;using Aerospike.Client;
public class App{ public static void Main() { // *** // Setup // ***
string address = "127.0.0.1"; // Aerospike address int port = 3000; // Aerospike port string name_space = "test"; // Cluster namespace string set = "foo"; // Set name within namespace
// Create the client and connect to the database AerospikeClient client = new AerospikeClient(null, new Host(address, port));
// *** // Write a record // ***
// Create a new write policy WritePolicy writePolicy = new WritePolicy(); writePolicy.totalTimeout = 5000;
// Create the record key // A tuple consisting of namespace, set name, and user defined key Key key = new Key(name_space, set, "bar");
// Create a bin to store data within the new record Bin bin = new Bin("myBin", "Hello World!");
//Write the record to your database try { client.Put(writePolicy, key, bin); Console.WriteLine("Successfully wrote record"); } catch (AerospikeException e) { Console.WriteLine(e); }
// *** // Read back the record we just wrote // ***
// Create a new read policy Policy readPolicy = new Policy(); readPolicy.totalTimeout = 5000;
// Read the record try { Record record = client.Get(readPolicy, key); Console.WriteLine("Record: {0}", record); } catch (AerospikeException e) { Console.WriteLine(e); } finally { client.Close(); } }}package main
import ( "log" "time"
"github.com/aerospike/aerospike-client-go/v8")
func main() { // *** // Setup // ***
address := "127.0.0.1" // Aerospike address port := 3000 // Aerospike port namespace := "test" // Cluster namespace set := "foo" // Set name within namespace
// Create the client and connect to the database client, err := aerospike.NewClient(address, port) if err != nil { log.Fatal(err) } defer client.Close()
// *** // Write a record // ***
// Create a WritePolicy to set the TotalTimeout for writes // default 1000 ms writePolicy := aerospike.NewWritePolicy(0, 0) writePolicy.TotalTimeout = 5000 * time.Millisecond
// Create the record key // A tuple consisting of namespace, set name, and user defined key key, err := aerospike.NewKey(namespace, set, "bar") if err != nil { log.Fatal(err) }
// Create a bin to store data within the new record bin := aerospike.NewBin("myBin", "Hello World!")
//Write the record to your database err = client.PutBins(writePolicy, key, bin) if err != nil { log.Fatal(err) } log.Println("Successfully wrote record")
// *** // Read back the record we just wrote // ***
// Create a Policy to set the TotalTimeout for reads // default 1000 ms readPolicy := aerospike.NewPolicy() readPolicy.TotalTimeout = 5000 * time.Millisecond
// Read the record record, err := client.Get(readPolicy, key) if err != nil { log.Fatal(err) }
log.Printf("Record: %s", record.Bins)}const Aerospike = require('aerospike');
const main = async () => { // *** // Setup // ***
const address = "127.0.0.1"; // Aerospike address const port = 3000; // Aerospike port const namespace = "test"; // Cluster namespace const set = "foo"; // Set name within namespace
// Create the client and connect to the database let client = await Aerospike.connect({ hosts: `${address}:${port}` });
// *** // Write a record // ***
// Create a new write policy let writePolicy = new Aerospike.WritePolicy({ totalTimeout: 5000 });
// Create the record key // A tuple consisting of namespace, set name, and user defined key let key = new Aerospike.Key(namespace, set, "bar");
// Create a bin to store data within the new record let bin = { myBin: "Hello World!" };
//Write the record to your database try { await client.put(key, bin, [], writePolicy); console.info("Successfully wrote record"); } catch (err) { console.error(err); }
// *** // Read back the record we just wrote // ***
// Create a new read policy let readPolicy = new Aerospike.ReadPolicy({ totalTimeout: 5000 });
// Read the record try { let record = await client.get(key, readPolicy); console.info("Record: %o", record.bins); } catch (err) { console.error(err); } finally { client.close(); }}
main();#include <stdio.h>#include <aerospike/aerospike.h>#include <aerospike/aerospike_key.h>#include <aerospike/as_record.h>
int main(void){ // *** // Setup // ***
const char* address = "127.0.0.1"; // Aerospike address int port = 3000; // Aerospike port const char* namespace = "test"; // Cluster namespace const char* set = "foo"; // Set name within namespace
// Create the client and connect to the database as_config config; as_config_init(&config); as_config_add_host(&config, address, port);
aerospike as; aerospike_init(&as, &config);
as_error err; if (aerospike_connect(&as, &err) != AEROSPIKE_OK) { fprintf(stderr, "Error connecting: %s\n", err.message); return 1; }
// *** // Write a record // ***
// Create a new write policy as_policy_write write_policy; as_policy_write_init(&write_policy); write_policy.base.total_timeout = 5000;
// Create the record key // From the namespace, set name, and user defined key as_key key; as_key_init_str(&key, namespace, set, "bar");
// Create a bin to store data within the new record as_record rec; as_record_inita(&rec, 1); as_record_set_str(&rec, "myBin", "Hello World!");
// Write the record to your database if (aerospike_key_put(&as, &err, &write_policy, &key, &rec) == AEROSPIKE_OK) { printf("Successfully wrote record\n"); } else { fprintf(stderr, "Error writing record: %s\n", err.message); } as_record_destroy(&rec);
// *** // Read back the record we just wrote // ***
// Create a new read policy as_policy_read read_policy; as_policy_read_init(&read_policy); read_policy.base.total_timeout = 5000;
// Read the record as_record* record = NULL; if (aerospike_key_get(&as, &err, &read_policy, &key, &record) == AEROSPIKE_OK) { printf("Record: myBin=%s\n", as_record_get_str(record, "myBin")); as_record_destroy(record); } else { fprintf(stderr, "Error reading record: %s\n", err.message); }
aerospike_close(&as, &err); aerospike_destroy(&as); return 0;}package com.sample;
import com.aerospike.client.IAerospikeClient;import com.aerospike.client.AerospikeClient;import com.aerospike.client.AerospikeException;import com.aerospike.client.Bin;import com.aerospike.client.Host;import com.aerospike.client.Key;import com.aerospike.client.Record;import com.aerospike.client.policy.WritePolicy;import com.aerospike.client.policy.Policy;
public class App{ public static void main( String[] args ) { // *** // Setup // ***
String address = "127.0.0.1"; // Aerospike address Integer port = 3000; // Aerospike port String namespace = "test"; // Cluster namespace String set = "foo"; // Set name within namespace
// Create the client and connect to the database IAerospikeClient client = new AerospikeClient(address, port);
// *** // Write a record // ***
// Create a new write policy WritePolicy writePolicy = new WritePolicy(); writePolicy.totalTimeout = 5000;
// Create the record key // A tuple consisting of namespace, set name, and user defined key Key key = new Key(namespace, set, "bar");
// Create a bin to store data within the new record Bin bin = new Bin("myBin", "Hello World!");
//Write the record to your database try { client.put(writePolicy, key, bin); System.out.println("Successfully wrote record"); } catch (AerospikeException e) { e.printStackTrace(); }
// *** // Read back the record we just wrote // ***
// Create a new read policy Policy readPolicy = new Policy(); readPolicy.totalTimeout = 5000;
// Read the record try { Record record = client.get(readPolicy, key); System.out.format("Record: %s", record.bins); } catch (AerospikeException e) { e.printStackTrace(); } finally { client.close(); } }}import aerospikefrom aerospike import exception as ex
# ***# Setup# ***
address = "127.0.0.1" # Aerospike addressport = 3000 # Aerospike portnamespace = "test" # Cluster namespacesetname = "foo" # Set name within namespace
# Create the client and connect to the databaseclient = aerospike.client({'hosts': [(address, port)]})
# ***# Write a record# ***
# Create a new write policywrite_policy = {'total_timeout': 5000}
# Create the record key# A tuple consisting of namespace, set name, and user defined keykey = (namespace, setname, "bar")
# Create a bin to store data within the new recordbins = {'myBin': 'Hello World!'}
# Write the record to your databasetry: client.put(key, bins, policy=write_policy) print("Successfully wrote record")except ex.ClientError as e: print(e)
# ***# Read back the record we just wrote# ***
# Create a new read policyread_policy = {'total_timeout': 5000}
# Read the recordtry: (key_, meta, bins) = client.get(key, policy=read_policy) print(bins)except ex.ClientError as e: print(e)finally: client.close()