Simple put-get
For the complete documentation index see: llms.txt
All documentation pages available in markdown.
In this tutorial, you use the two most basic Aerospike calls: put, which writes a record, and get, which reads one. 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. In the SDKs, the write is an upsert and the read is a query by key.
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. - Your client installed. To install it, follow the Install the client step of the Hello, World! tutorial.
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 that the client computes from the key. For details, see the Data model.
Key key = DataSet.of("test", "demo").id("putgetkey");key = DataSet.of("test", "demo").id("putgetkey")let key = as_key!("test", "demo", "putgetkey");Key key = new Key("test", "demo", "putgetkey");key, err := aerospike.NewKey("test", "demo", "putgetkey")if err != nil { log.Fatal(err)}const key = new Aerospike.Key('test', 'demo', 'putgetkey');as_key key;as_key_init_str(&key, "test", "demo", "putgetkey");Key key = new Key("test", "demo", "putgetkey");key = ("test", "demo", "putgetkey")Write a record
Aerospike has no schema, so you can write a record without any setup. This step writes the bins name and age to the record that the key identifies.
session.upsert(key) .bin("name").setTo("John Doe") .bin("age").setTo(32) .execute();An upsert creates the record, or replaces the listed bins if the record exists.
session.upsert(key).put({"name": "John Doe", "age": 32}).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),]).await?;client.Put(null, key, new Bin("name", "John Doe"), new Bin("age", 32));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))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 });as_record rec;as_record_inita(&rec, 2);as_record_set_str(&rec, "name", "John Doe");as_record_set_int64(&rec, "age", 32);
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));The null argument tells the client to use its default write policy.
client.put(key, {"name": "John Doe", "age": 32})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("Generation: " + record.generation);print("name:", record.bins["name"])print("age:", record.bins["age"])print("Generation:", record.generation)println!("name: {}", record.bins["name"]);println!("age: {}", record.bins["age"]);println!("Generation: {}", record.generation);Console.WriteLine("name: " + record.GetString("name"));Console.WriteLine("age: " + record.GetInt("age"));Console.WriteLine("Generation: " + record.generation);fmt.Println("name:", record.Bins["name"])fmt.Println("age:", record.Bins["age"])fmt.Println("Generation:", record.Generation)console.log('name:', record.bins.name);console.log('age:', record.bins.age);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("Generation: %d\n", record->gen);System.out.println("name: " + record.getString("name"));System.out.println("age: " + record.getInt("age"));System.out.println("Generation: " + record.generation);print("name:", bins["name"])print("age:", bins["age"])print("Generation:", meta["gen"])name: John Doeage: 32Generation: 1Delete the record
Delete the record so 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 SimplePutGet { 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("putgetkey");
session.upsert(key) .bin("name").setTo("John Doe") .bin("age").setTo(32) .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("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("putgetkey")
session.upsert(key).put({"name": "John Doe", "age": 32}).execute()
record = session.query(key).execute().first_or_raise().record_or_raise() print("name:", record.bins["name"]) print("age:", record.bins["age"]) 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", "putgetkey");
client.put(&WritePolicy::default(), &key, &[ as_bin!("name", "John Doe"), as_bin!("age", 32), ]).await?;
let record = client.get(&ReadPolicy::default(), &key, Bins::All).await?; println!("name: {}", record.bins["name"]); println!("age: {}", record.bins["age"]); println!("Generation: {}", record.generation);
client.delete(&WritePolicy::default(), &key).await?;
client.close().await?; Ok(())}using System;using Aerospike.Client;
public class SimplePutGet{ public static void Main() { AerospikeClient client = new AerospikeClient("127.0.0.1", 3000); try { Key key = new Key("test", "demo", "putgetkey");
client.Put(null, key, new Bin("name", "John Doe"), new Bin("age", 32));
Record record = client.Get(null, key); Console.WriteLine("name: " + record.GetString("name")); Console.WriteLine("age: " + record.GetInt("age")); 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", "putgetkey") if err != nil { log.Fatal(err) }
err = client.PutBins(nil, key, aerospike.NewBin("name", "John Doe"), aerospike.NewBin("age", 32)) 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("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', 'putgetkey');
await client.put(key, { name: 'John Doe', age: 32 });
const record = await client.get(key); console.log('name:', record.bins.name); console.log('age:', record.bins.age); 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", "putgetkey");
as_record rec; as_record_inita(&rec, 2); as_record_set_str(&rec, "name", "John Doe"); as_record_set_int64(&rec, "age", 32);
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("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 SimplePutGet { public static void main(String[] args) { try (AerospikeClient client = new AerospikeClient("127.0.0.1", 3000)) { Key key = new Key("test", "demo", "putgetkey");
client.put(null, key, new Bin("name", "John Doe"), new Bin("age", 32));
Record record = client.get(null, key); System.out.println("name: " + record.getString("name")); System.out.println("age: " + record.getInt("age")); 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", "putgetkey") client.put(key, {"name": "John Doe", "age": 32})
(read_key, meta, bins) = client.get(key) print("name:", bins["name"]) print("age:", bins["age"]) 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: 32Generation: 1What you learned
You wrote a record with two bins, read the record back, printed its bins and generation, and deleted the record.
Next steps
- 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.