Hello, World!
For the complete documentation index see: llms.txt
All documentation pages available in markdown.
In this tutorial, you write a short program that connects to an Aerospike Database, writes a record, reads the record back, and closes the connection. Choose your client in any tab group. The page remembers your choice.
The Java SDK and Python SDK tabs use the Aerospike Developer SDKs. The Java and Python tabs use the legacy clients.
Prerequisites
- An Aerospike Database running on your computer and listening on port 3000, with a namespace named
test. The Java SDK and Python SDK tabs require Aerospike Database 8.2.0 or later. For the other clients, see the Client Compatibility Matrix. To set up a database, see the Quickstart, or Install on macOS and Windows with Docker to run one in a container. - A development environment for your language. The install links give the language versions each client supports.
Install the client
The Java SDK requires JDK 21 or later. Add the aerospike-client-sdk dependency to your pom.xml file.
<dependency> <groupId>com.aerospike</groupId> <artifactId>aerospike-client-sdk</artifactId> <version>1.0.0</version></dependency>For other build tools, see the Installation page.
The Python SDK requires Python 3.11 or later. Install the aerospike-sdk package with pip.
python3 -m pip install aerospike-sdk==1.0.0For more information, see the Installation page.
The Rust client requires Rust 1.87 or later. Add the client and the Tokio runtime to your Cargo.toml file.
[dependencies]aerospike = { version = "3.0.0", features = ["rt-tokio"] }tokio = { version = "1", features = ["full"] }For more information, see the Rust client install page.
Add the Aerospike.Client package to your project from NuGet.
dotnet add package Aerospike.Client --version 8.5.0For more information, see the C# client install page.
In your Go module, get the Aerospike Go client.
go get github.com/aerospike/aerospike-client-go/v8@v8.9.0For more information, see the Go client install page.
In your project directory, install the aerospike package with npm.
npm install aerospike@7.0.1The examples on this page are ES modules. Save them in files with the .mjs extension. For more information, see the Node.js client install page.
Download the C client package for your platform from the Download page. Install the development package to compile your application with the client. Install the runtime package to run it.
For example, on Debian or Ubuntu, extract the package that you downloaded with tar xvf, and then install the two .deb packages it contains. Replace DEVELOPMENT_PACKAGE and RUNTIME_PACKAGE with the package file names.
sudo dpkg -i DEVELOPMENT_PACKAGE RUNTIME_PACKAGEFor more information, see the C client install page.
Add the aerospike-client-jdk21 dependency to your pom.xml file.
<dependency> <groupId>com.aerospike</groupId> <artifactId>aerospike-client-jdk21</artifactId> <version>10.5.0</version></dependency>If your runtime is JDK 8 through JDK 20, use aerospike-client-jdk8 instead. The API is the same. The Java examples in these tutorials need JDK 17 or later, whichever artifact you use. For other build tools and version guidance, see Install the Aerospike client.
Install the aerospike package with pip. The client works with Python 3.10 through 3.14.
pip install aerospike==19.3.0For supported platforms and version guidance, see Install the Aerospike client.
Import the client modules
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;from aerospike_sdk import Behavior, DataSetfrom aerospike_sdk.sync import ClusterDefinitionuse aerospike::{as_bin, as_key, Bins, Client, ClientPolicy, ReadPolicy, WritePolicy};using System;using Aerospike.Client;import ( "fmt" "log"
"github.com/aerospike/aerospike-client-go/v8")import Aerospike from 'aerospike';#include <stdio.h>#include <aerospike/aerospike.h>#include <aerospike/aerospike_key.h>#include <aerospike/as_error.h>#include <aerospike/as_record.h>import com.aerospike.client.AerospikeClient;import com.aerospike.client.Bin;import com.aerospike.client.Key;import com.aerospike.client.Record;import aerospikeConnect to the database
Connect to the database on port 3000 of your computer. This is the default port. If your database runs on another host or port, change the address.
The client connects to the seed node you specify, which is the first node it contacts, and then discovers the other nodes in the cluster.
Cluster cluster = new ClusterDefinition("127.0.0.1", 3000).connect();Session session = cluster.createSession(Behavior.DEFAULT);The session applies a Behavior, which sets the timeouts and retries for each command. Behavior.DEFAULT is a reasonable starting point.
cluster = ClusterDefinition("127.0.0.1", 3000).connect()session = cluster.create_session(Behavior.DEFAULT)The session applies a Behavior, which sets the timeouts and retries for each command. Behavior.DEFAULT is a reasonable starting point.
let client = Client::new(&ClientPolicy::default(), &"127.0.0.1:3000").await?;AerospikeClient client = new AerospikeClient("127.0.0.1", 3000);client, err := aerospike.NewClient("127.0.0.1", 3000)if err != nil { log.Fatal(err)}const client = await Aerospike.connect({ hosts: '127.0.0.1:3000' });as_config config;as_config_init(&config);as_config_add_host(&config, "127.0.0.1", 3000);
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;}AerospikeClient client = new AerospikeClient("127.0.0.1", 3000);config = {"hosts": [("127.0.0.1", 3000)]}client = aerospike.client(config).connect()Define a record key
A record key has three parts: a namespace, an optional set, and a user key. Together they identify a record so you can read or write the record with its key.
By default, the database doesn’t store the user key. It stores a 20-byte digest, a hash of the set and the user key. For details, see the Data model.
Key key = DataSet.of("test", "demo").id("foo");key = DataSet.of("test", "demo").id("foo")let key = as_key!("test", "demo", "foo");Key key = new Key("test", "demo", "foo");key, err := aerospike.NewKey("test", "demo", "foo")if err != nil { log.Fatal(err)}const key = new Aerospike.Key('test', 'demo', 'foo');as_key key;as_key_init_str(&key, "test", "demo", "foo");Key key = new Key("test", "demo", "foo");key = ("test", "demo", "foo")Write a record
Aerospike has no schema, so you can write a record without any setup. This step writes the bins name, age, and greeting to the record that the key identifies.
session.upsert(key) .bin("name").setTo("John Doe") .bin("age").setTo(32) .bin("greeting").setTo("Hello, World!") .execute();An upsert creates the record, or replaces the listed bins if the record exists.
session.upsert(key).put({"name": "John Doe", "age": 32, "greeting": "Hello, World!"}).execute()An upsert creates the record, or replaces the listed bins if the record exists.
client.put(&WritePolicy::default(), &key, &[ as_bin!("name", "John Doe"), as_bin!("age", 32), as_bin!("greeting", "Hello, World!"),]).await?;client.Put(null, key, new Bin("name", "John Doe"), new Bin("age", 32), new Bin("greeting", "Hello, World!"));The null argument tells the client to use its default write policy.
err = client.PutBins(nil, key, aerospike.NewBin("name", "John Doe"), aerospike.NewBin("age", 32), aerospike.NewBin("greeting", "Hello, World!"))if err != nil { log.Fatal(err)}The nil argument tells the client to use its default write policy.
await client.put(key, { name: 'John Doe', age: 32, greeting: 'Hello, World!' });as_record rec;as_record_inita(&rec, 3);as_record_set_str(&rec, "name", "John Doe");as_record_set_int64(&rec, "age", 32);as_record_set_str(&rec, "greeting", "Hello, World!");
if (aerospike_key_put(&as, &err, NULL, &key, &rec) != AEROSPIKE_OK) { fprintf(stderr, "Error writing record: %s\n", err.message); as_record_destroy(&rec); return 1;}as_record_destroy(&rec);The NULL argument tells the client to use its default write policy.
client.put(null, key, new Bin("name", "John Doe"), new Bin("age", 32), new Bin("greeting", "Hello, World!"));The null argument tells the client to use its default write policy.
client.put(key, {"name": "John Doe", "age": 32, "greeting": "Hello, World!"})Read the record
Read the record with the same key.
Record record = session.query(key).execute().getFirstRecord();record = session.query(key).execute().first_or_raise().record_or_raise()let record = client.get(&ReadPolicy::default(), &key, Bins::All).await?;Record record = client.Get(null, key);record, err := client.Get(nil, key)if err != nil { log.Fatal(err)}const record = await client.get(key);as_record* record = NULL;if (aerospike_key_get(&as, &err, NULL, &key, &record) != AEROSPIKE_OK) { fprintf(stderr, "Error reading record: %s\n", err.message); return 1;}Record record = client.get(null, key);(read_key, meta, bins) = client.get(key)In the legacy Python client, the call returns the record’s key, its metadata, and its bins.
Display the record
Print the values of the bins and the record’s generation. The generation counts the writes to the record. It is 1 after the first write and increases with each later write.
System.out.println("name: " + record.getString("name"));System.out.println("age: " + record.getInt("age"));System.out.println("greeting: " + record.getString("greeting"));System.out.println("Generation: " + record.generation);print("name:", record.bins["name"])print("age:", record.bins["age"])print("greeting:", record.bins["greeting"])print("Generation:", record.generation)println!("name: {}", record.bins["name"]);println!("age: {}", record.bins["age"]);println!("greeting: {}", record.bins["greeting"]);println!("Generation: {}", record.generation);Console.WriteLine("name: " + record.GetString("name"));Console.WriteLine("age: " + record.GetInt("age"));Console.WriteLine("greeting: " + record.GetString("greeting"));Console.WriteLine("Generation: " + record.generation);fmt.Println("name:", record.Bins["name"])fmt.Println("age:", record.Bins["age"])fmt.Println("greeting:", record.Bins["greeting"])fmt.Println("Generation:", record.Generation)console.log('name:', record.bins.name);console.log('age:', record.bins.age);console.log('greeting:', record.bins.greeting);console.log('Generation:', record.gen);printf("name: %s\n", as_record_get_str(record, "name"));printf("age: %lld\n", (long long)as_record_get_int64(record, "age", 0));printf("greeting: %s\n", as_record_get_str(record, "greeting"));printf("Generation: %d\n", record->gen);System.out.println("name: " + record.getString("name"));System.out.println("age: " + record.getInt("age"));System.out.println("greeting: " + record.getString("greeting"));System.out.println("Generation: " + record.generation);print("name:", bins["name"])print("age:", bins["age"])print("greeting:", bins["greeting"])print("Generation:", meta["gen"])name: John Doeage: 32greeting: Hello, World!Generation: 1Delete the record
Delete the record, so that the tutorial leaves no data behind and you can run it again.
session.delete(key).execute();session.delete(key).execute()client.delete(&WritePolicy::default(), &key).await?;client.Delete(null, key);_, err = client.Delete(nil, key)if err != nil { log.Fatal(err)}await client.remove(key);if (aerospike_key_remove(&as, &err, NULL, &key) != AEROSPIKE_OK) { fprintf(stderr, "Error deleting record: %s\n", err.message); return 1;}client.delete(null, key);client.remove(key)Close the connection
When your program is finished with the database, close the client.
cluster.close();cluster.close()client.close().await?;client.Close();client.Close()client.close();as_record_destroy(record);as_key_destroy(&key);aerospike_close(&as, &err);aerospike_destroy(&as);client.close();client.close()Complete program
This program combines the steps.
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;
public class HelloWorld { public static void main(String[] args) { try (Cluster cluster = new ClusterDefinition("127.0.0.1", 3000).connect()) { Session session = cluster.createSession(Behavior.DEFAULT); Key key = DataSet.of("test", "demo").id("foo");
session.upsert(key) .bin("name").setTo("John Doe") .bin("age").setTo(32) .bin("greeting").setTo("Hello, World!") .execute();
Record record = session.query(key).execute().getFirstRecord(); System.out.println("name: " + record.getString("name")); System.out.println("age: " + record.getInt("age")); System.out.println("greeting: " + record.getString("greeting")); System.out.println("Generation: " + record.generation);
session.delete(key).execute(); } }}import sys
from aerospike_sdk import Behavior, DataSetfrom aerospike_sdk.exceptions import AerospikeErrorfrom aerospike_sdk.sync import ClusterDefinition
cluster = ClusterDefinition("127.0.0.1", 3000).connect()try: session = cluster.create_session(Behavior.DEFAULT) key = DataSet.of("test", "demo").id("foo")
session.upsert(key).put({"name": "John Doe", "age": 32, "greeting": "Hello, World!"}).execute()
record = session.query(key).execute().first_or_raise().record_or_raise() print("name:", record.bins["name"]) print("age:", record.bins["age"]) print("greeting:", record.bins["greeting"]) print("Generation:", record.generation)
session.delete(key).execute()except AerospikeError as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1)finally: cluster.close()use aerospike::{as_bin, as_key, Bins, Client, ClientPolicy, ReadPolicy, WritePolicy};
#[tokio::main]async fn main() -> Result<(), Box<dyn std::error::Error>> { let client = Client::new(&ClientPolicy::default(), &"127.0.0.1:3000").await?; let key = as_key!("test", "demo", "foo");
client.put(&WritePolicy::default(), &key, &[ as_bin!("name", "John Doe"), as_bin!("age", 32), as_bin!("greeting", "Hello, World!"), ]).await?;
let record = client.get(&ReadPolicy::default(), &key, Bins::All).await?; println!("name: {}", record.bins["name"]); println!("age: {}", record.bins["age"]); println!("greeting: {}", record.bins["greeting"]); println!("Generation: {}", record.generation);
client.delete(&WritePolicy::default(), &key).await?;
client.close().await?; Ok(())}using System;using Aerospike.Client;
public class HelloWorld{ public static void Main() { AerospikeClient client = new AerospikeClient("127.0.0.1", 3000); try { Key key = new Key("test", "demo", "foo");
client.Put(null, key, new Bin("name", "John Doe"), new Bin("age", 32), new Bin("greeting", "Hello, World!"));
Record record = client.Get(null, key); Console.WriteLine("name: " + record.GetString("name")); Console.WriteLine("age: " + record.GetInt("age")); Console.WriteLine("greeting: " + record.GetString("greeting")); Console.WriteLine("Generation: " + record.generation);
client.Delete(null, key); } finally { client.Close(); } }}package main
import ( "fmt" "log"
"github.com/aerospike/aerospike-client-go/v8")
func main() { client, err := aerospike.NewClient("127.0.0.1", 3000) if err != nil { log.Fatal(err) } defer client.Close()
key, err := aerospike.NewKey("test", "demo", "foo") if err != nil { log.Fatal(err) }
err = client.PutBins(nil, key, aerospike.NewBin("name", "John Doe"), aerospike.NewBin("age", 32), aerospike.NewBin("greeting", "Hello, World!")) if err != nil { log.Fatal(err) }
record, err := client.Get(nil, key) if err != nil { log.Fatal(err) } fmt.Println("name:", record.Bins["name"]) fmt.Println("age:", record.Bins["age"]) fmt.Println("greeting:", record.Bins["greeting"]) fmt.Println("Generation:", record.Generation)
_, err = client.Delete(nil, key) if err != nil { log.Fatal(err) }}import Aerospike from 'aerospike';
const client = await Aerospike.connect({ hosts: '127.0.0.1:3000' });try { const key = new Aerospike.Key('test', 'demo', 'foo');
await client.put(key, { name: 'John Doe', age: 32, greeting: 'Hello, World!' });
const record = await client.get(key); console.log('name:', record.bins.name); console.log('age:', record.bins.age); console.log('greeting:', record.bins.greeting); console.log('Generation:', record.gen);
await client.remove(key);} finally { client.close();}#include <stdio.h>#include <aerospike/aerospike.h>#include <aerospike/aerospike_key.h>#include <aerospike/as_error.h>#include <aerospike/as_record.h>
int main(void){ as_config config; as_config_init(&config); as_config_add_host(&config, "127.0.0.1", 3000);
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; }
as_key key; as_key_init_str(&key, "test", "demo", "foo");
as_record rec; as_record_inita(&rec, 3); as_record_set_str(&rec, "name", "John Doe"); as_record_set_int64(&rec, "age", 32); as_record_set_str(&rec, "greeting", "Hello, World!");
if (aerospike_key_put(&as, &err, NULL, &key, &rec) != AEROSPIKE_OK) { fprintf(stderr, "Error writing record: %s\n", err.message); as_record_destroy(&rec); aerospike_close(&as, &err); aerospike_destroy(&as); return 1; } as_record_destroy(&rec);
as_record* record = NULL; if (aerospike_key_get(&as, &err, NULL, &key, &record) != AEROSPIKE_OK) { fprintf(stderr, "Error reading record: %s\n", err.message); aerospike_close(&as, &err); aerospike_destroy(&as); return 1; } printf("name: %s\n", as_record_get_str(record, "name")); printf("age: %lld\n", (long long)as_record_get_int64(record, "age", 0)); printf("greeting: %s\n", as_record_get_str(record, "greeting")); printf("Generation: %d\n", record->gen);
if (aerospike_key_remove(&as, &err, NULL, &key) != AEROSPIKE_OK) { fprintf(stderr, "Error deleting record: %s\n", err.message); }
as_record_destroy(record); as_key_destroy(&key); aerospike_close(&as, &err); aerospike_destroy(&as); return 0;}import com.aerospike.client.AerospikeClient;import com.aerospike.client.Bin;import com.aerospike.client.Key;import com.aerospike.client.Record;
public class HelloWorld { public static void main(String[] args) { try (AerospikeClient client = new AerospikeClient("127.0.0.1", 3000)) { Key key = new Key("test", "demo", "foo");
client.put(null, key, new Bin("name", "John Doe"), new Bin("age", 32), new Bin("greeting", "Hello, World!"));
Record record = client.get(null, key); System.out.println("name: " + record.getString("name")); System.out.println("age: " + record.getInt("age")); System.out.println("greeting: " + record.getString("greeting")); System.out.println("Generation: " + record.generation);
client.delete(null, key); } }}import sys
import aerospikefrom aerospike import exception as ex
config = {"hosts": [("127.0.0.1", 3000)]}
try: client = aerospike.client(config).connect()except ex.ClientError as e: print(f"Failed to connect to the cluster with {config['hosts']}: {e}", file=sys.stderr) sys.exit(1)
try: key = ("test", "demo", "foo") client.put(key, {"name": "John Doe", "age": 32, "greeting": "Hello, World!"})
(read_key, meta, bins) = client.get(key) print("name:", bins["name"]) print("age:", bins["age"]) print("greeting:", bins["greeting"]) print("Generation:", meta["gen"])
client.remove(key)except ex.AerospikeError as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1)finally: client.close()name: John Doeage: 32greeting: Hello, World!Generation: 1What you learned
In this tutorial, you connected to a database and used a key to write and read a record. You read the record generation, deleted the record, and closed the connection.
Next steps
- Practice the
putandgetcalls in the Simple put-get tutorial. - Update a record with the Basic operations tutorial.
- Learn how each client connects: Java SDK and Python SDK, Rust, C#, Go, Node.js, C, Java, or Python.