Basic operations
For the complete documentation index see: llms.txt
All documentation pages available in markdown.
In this tutorial, you use basic create, read, update, and delete operations on Aerospike records. You also run several operations on one record in a single command. 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. - Your client installed. To install it, follow the Install the client step of the Hello, World! tutorial.
Records
Data in Aerospike is stored in records. A record belongs to a namespace, which is similar to a database, and optionally to a set, which is similar to a table. A record has bins, which are named, typed containers for values. A bin can hold a scalar value (String, Integer, or Blob) or a collection (List or Map).
For more information, see the Data model.
A key identifies a record. The key has a namespace, a set, and a user key. The client sends the database a 20-byte digest, a hash of the set and the user key. The database uses that digest to find the record. By default, the database doesn’t store the user key.
Import the client modules
import java.util.List;import java.util.Map;
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.RecordResult;import com.aerospike.client.sdk.RecordStream;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::operations::scalar;use aerospike::operations::string::{self, StringPolicy};use aerospike::{as_bin, as_key, as_list, as_map, as_val, BatchOperation, BatchPolicy, BatchReadPolicy, Bins, Client, ClientPolicy, ReadPolicy, Value, WritePolicy};using System;using System.Collections.Generic;using Aerospike.Client;import ( "fmt" "log"
"github.com/aerospike/aerospike-client-go/v8")import Aerospike from 'aerospike';
const { operations: op, strings } = Aerospike;#include <stdio.h>#include <aerospike/aerospike.h>#include <aerospike/aerospike_batch.h>#include <aerospike/aerospike_key.h>#include <aerospike/as_arraylist.h>#include <aerospike/as_batch.h>#include <aerospike/as_bytes.h>#include <aerospike/as_error.h>#include <aerospike/as_hashmap.h>#include <aerospike/as_integer.h>#include <aerospike/as_key.h>#include <aerospike/as_operations.h>#include <aerospike/as_record.h>#include <aerospike/as_string.h>#include <aerospike/as_string_operations.h>import java.util.List;import java.util.Map;
import com.aerospike.client.AerospikeClient;import com.aerospike.client.Bin;import com.aerospike.client.Key;import com.aerospike.client.Operation;import com.aerospike.client.Record;import com.aerospike.client.operation.StringOperation;import com.aerospike.client.operation.StringPolicy;import aerospikefrom aerospike_helpers.operations import operations, string_operationsConnect 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.
let client = Client::new(&ClientPolicy::default(), &"127.0.0.1:3000").await?;let write_policy = WritePolicy::default();let read_policy = ReadPolicy::default();The Rust client takes a policy with each command. This tutorial uses the default write and read policies.
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()Write a record
The put command writes a record. In the SDKs, the same command is an upsert, which creates the record if it doesn’t exist and updates it if it does.
The key identifies the record: a namespace, a set, and a user key. Write a record in the set basicops with the user key bender and six bins. The bins hold a String, an Integer, a Map, a List, a Blob, and another Integer. A put writes all the bins in one command, and it leaves any other bins in the record as they are.
The last step deletes the records that remain, so you can run the tutorial again.
DataSet dataSet = DataSet.of("test", "basicops");Key key = dataSet.id("bender");
session.upsert(key) .bin("name").setTo("Bender") .bin("serialnum").setTo(2716057) .bin("lastsentence").setTo(Map.of("BBS", "Well, we're boned", "TBwaBB", "I love you, meatbags!")) .bin("composition").setTo(List.of("40% zinc", "40% titanium", "30% iron", "40% dolomite")) .bin("apartment").setTo(new byte[] {0x24}) .bin("quote_cnt").setTo(47) .execute();data_set = DataSet.of("test", "basicops")key = data_set.id("bender")
session.upsert(key).put({ "name": "Bender", "serialnum": 2716057, "lastsentence": {"BBS": "Well, we're boned", "TBwaBB": "I love you, meatbags!"}, "composition": ["40% zinc", "40% titanium", "30% iron", "40% dolomite"], "apartment": bytes([0x24]), "quote_cnt": 47,}).execute()let key = as_key!("test", "basicops", "bender");
client.put(&write_policy, &key, &[ as_bin!("name", "Bender"), as_bin!("serialnum", 2716057), as_bin!("lastsentence", as_map!("BBS" => "Well, we're boned", "TBwaBB" => "I love you, meatbags!")), as_bin!("composition", as_list!("40% zinc", "40% titanium", "30% iron", "40% dolomite")), as_bin!("apartment", Value::Blob(vec![0x24])), as_bin!("quote_cnt", 47),]).await?;Key key = new Key("test", "basicops", "bender");
client.Put(null, key, new Bin("name", "Bender"), new Bin("serialnum", 2716057), new Bin("lastsentence", new Dictionary<string, string> { { "BBS", "Well, we're boned" }, { "TBwaBB", "I love you, meatbags!" } }), new Bin("composition", new List<string> { "40% zinc", "40% titanium", "30% iron", "40% dolomite" }), new Bin("apartment", new byte[] { 0x24 }), new Bin("quote_cnt", 47));key, err := aerospike.NewKey("test", "basicops", "bender")if err != nil { log.Fatal(err)}
err = client.PutBins(nil, key, aerospike.NewBin("name", "Bender"), aerospike.NewBin("serialnum", 2716057), aerospike.NewBin("lastsentence", map[string]string{ "BBS": "Well, we're boned", "TBwaBB": "I love you, meatbags!", }), aerospike.NewBin("composition", []string{"40% zinc", "40% titanium", "30% iron", "40% dolomite"}), aerospike.NewBin("apartment", []byte{0x24}), aerospike.NewBin("quote_cnt", 47))if err != nil { log.Fatal(err)}const key = new Aerospike.Key('test', 'basicops', 'bender');
await client.put(key, { name: 'Bender', serialnum: 2716057, lastsentence: { BBS: "Well, we're boned", TBwaBB: 'I love you, meatbags!' }, composition: ['40% zinc', '40% titanium', '30% iron', '40% dolomite'], apartment: Buffer.from([0x24]), quote_cnt: 47,});as_key key;as_key_init_str(&key, "test", "basicops", "bender");
as_hashmap lastsentence;as_hashmap_init(&lastsentence, 2);as_hashmap_set(&lastsentence, (as_val*)as_string_new("BBS", false), (as_val*)as_string_new("Well, we're boned", false));as_hashmap_set(&lastsentence, (as_val*)as_string_new("TBwaBB", false), (as_val*)as_string_new("I love you, meatbags!", false));
as_arraylist composition;as_arraylist_inita(&composition, 4);as_arraylist_append_str(&composition, "40% zinc");as_arraylist_append_str(&composition, "40% titanium");as_arraylist_append_str(&composition, "30% iron");as_arraylist_append_str(&composition, "40% dolomite");
uint8_t apartment[] = {0x24};
as_record rec;as_record_inita(&rec, 6);as_record_set_str(&rec, "name", "Bender");as_record_set_int64(&rec, "serialnum", 2716057);as_record_set_map(&rec, "lastsentence", (as_map*)&lastsentence);as_record_set_list(&rec, "composition", (as_list*)&composition);as_record_set_bytes(&rec, "apartment", as_bytes_new_wrap(apartment, sizeof(apartment), false));as_record_set_int64(&rec, "quote_cnt", 47);
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);Key key = new Key("test", "basicops", "bender");
client.put(null, key, new Bin("name", "Bender"), new Bin("serialnum", 2716057), new Bin("lastsentence", Map.of("BBS", "Well, we're boned", "TBwaBB", "I love you, meatbags!")), new Bin("composition", List.of("40% zinc", "40% titanium", "30% iron", "40% dolomite")), new Bin("apartment", new byte[] {0x24}), new Bin("quote_cnt", 47));key = ("test", "basicops", "bender")
client.put(key, { "name": "Bender", "serialnum": 2716057, "lastsentence": {"BBS": "Well, we're boned", "TBwaBB": "I love you, meatbags!"}, "composition": ["40% zinc", "40% titanium", "30% iron", "40% dolomite"], "apartment": bytes([0x24]), "quote_cnt": 47,})Read a record
The get command reads a record by its key and returns its bins and its metadata. A read returns two metadata values:
- The generation is the number of times the record has been written. A new record has generation 1.
- The time to live (TTL) is the number of seconds until the record expires. When a client writes a record with a TTL of 0, the server applies the
default-ttlof the namespace. For details, see Configuring namespace data retention.
Read the record you wrote and print three bins and the generation.
Record record = session.query(key).execute().getFirstRecord();System.out.println("name: " + record.getString("name"));System.out.println("serialnum: " + record.getLong("serialnum"));System.out.println("quote_cnt: " + record.getLong("quote_cnt"));System.out.println("Generation: " + record.generation);record = session.query(key).execute().first_or_raise().record_or_raise()print("name:", record.bins["name"])print("serialnum:", record.bins["serialnum"])print("quote_cnt:", record.bins["quote_cnt"])print("Generation:", record.generation)let record = client.get(&read_policy, &key, Bins::All).await?;println!("name: {}", record.bins["name"]);println!("serialnum: {}", record.bins["serialnum"]);println!("quote_cnt: {}", record.bins["quote_cnt"]);println!("Generation: {}", record.generation);Record record = client.Get(null, key);Console.WriteLine("name: " + record.GetString("name"));Console.WriteLine("serialnum: " + record.GetLong("serialnum"));Console.WriteLine("quote_cnt: " + record.GetLong("quote_cnt"));Console.WriteLine("Generation: " + record.generation);record, err := client.Get(nil, key)if err != nil { log.Fatal(err)}fmt.Println("name:", record.Bins["name"])fmt.Println("serialnum:", record.Bins["serialnum"])fmt.Println("quote_cnt:", record.Bins["quote_cnt"])fmt.Println("Generation:", record.Generation)let record = await client.get(key);console.log('name:', record.bins.name);console.log('serialnum:', record.bins.serialnum);console.log('quote_cnt:', record.bins.quote_cnt);console.log('Generation:', record.gen);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;}printf("name: %s\n", as_record_get_str(record, "name"));printf("serialnum: %lld\n", (long long)as_record_get_int64(record, "serialnum", 0));printf("quote_cnt: %lld\n", (long long)as_record_get_int64(record, "quote_cnt", 0));printf("Generation: %d\n", record->gen);Record record = client.get(null, key);System.out.println("name: " + record.getString("name"));System.out.println("serialnum: " + record.getLong("serialnum"));System.out.println("quote_cnt: " + record.getLong("quote_cnt"));System.out.println("Generation: " + record.generation);(_, meta, bins) = client.get(key)print("name:", bins["name"])print("serialnum:", bins["serialnum"])print("quote_cnt:", bins["quote_cnt"])print("Generation:", meta["gen"])The get function returns a tuple of the key, the metadata dictionary with the gen and ttl fields, and the bins dictionary. If the record doesn’t exist, get raises RecordNotFound.
name: Benderserialnum: 2716057quote_cnt: 47Generation: 1Prepend, append, and increment bins
Update the record with three commands, each with one operation. Prepend Dr. to the String. Append Bending Rodriguez to the String. Add 3 to the Integer. Each command that writes the record increments its generation, so the generation goes from 1 to 4.
session.upsert(key).bin("name").prepend("Dr. ").execute();session.upsert(key).bin("name").append(" Bending Rodriguez").execute();session.upsert(key).bin("quote_cnt").add(3).execute();
record = session.query(key).execute().getFirstRecord();System.out.println("name: " + record.getString("name"));System.out.println("quote_cnt: " + record.getLong("quote_cnt"));System.out.println("Generation: " + record.generation);session.upsert(key).bin("name").prepend("Dr. ").execute()session.upsert(key).bin("name").append(" Bending Rodriguez").execute()session.upsert(key).bin("quote_cnt").add(3).execute()
record = session.query(key).execute().first_or_raise().record_or_raise()print("name:", record.bins["name"])print("quote_cnt:", record.bins["quote_cnt"])print("Generation:", record.generation)client.operate(&write_policy, &key, &[string::prepend(&StringPolicy::default(), "name", "Dr. ")]).await?;client.operate(&write_policy, &key, &[string::append(&StringPolicy::default(), "name", " Bending Rodriguez")]).await?;client.operate(&write_policy, &key, &[scalar::add(&as_bin!("quote_cnt", 3))]).await?;
let record = client.get(&read_policy, &key, Bins::All).await?;println!("name: {}", record.bins["name"]);println!("quote_cnt: {}", record.bins["quote_cnt"]);println!("Generation: {}", record.generation);client.Operate(null, key, StringOperation.Prepend(StringPolicy.Default, "name", "Dr. "));client.Operate(null, key, StringOperation.Append(StringPolicy.Default, "name", " Bending Rodriguez"));client.Operate(null, key, Operation.Add(new Bin("quote_cnt", 3)));
record = client.Get(null, key);Console.WriteLine("name: " + record.GetString("name"));Console.WriteLine("quote_cnt: " + record.GetLong("quote_cnt"));Console.WriteLine("Generation: " + record.generation);_, err = client.Operate(nil, key, aerospike.StrPrependOp(aerospike.DefaultStringPolicy, "name", "Dr. "))if err != nil { log.Fatal(err)}_, err = client.Operate(nil, key, aerospike.StrAppendOp(aerospike.DefaultStringPolicy, "name", " Bending Rodriguez"))if err != nil { log.Fatal(err)}_, err = client.Operate(nil, key, aerospike.AddOp(aerospike.NewBin("quote_cnt", 3)))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("quote_cnt:", record.Bins["quote_cnt"])fmt.Println("Generation:", record.Generation)await client.operate(key, [strings.prepend('name', 'Dr. ')]);await client.operate(key, [strings.append('name', ' Bending Rodriguez')]);await client.operate(key, [op.incr('quote_cnt', 3)]);
record = await client.get(key);console.log('name:', record.bins.name);console.log('quote_cnt:', record.bins.quote_cnt);console.log('Generation:', record.gen);as_operations ops;as_operations_inita(&ops, 1);as_operations_string_prepend(&ops, "name", NULL, NULL, "Dr. ");if (aerospike_key_operate(&as, &err, NULL, &key, &ops, NULL) != AEROSPIKE_OK) { fprintf(stderr, "Error prepending to the string: %s\n", err.message); return 1;}as_operations_destroy(&ops);
as_operations_inita(&ops, 1);as_operations_string_append(&ops, "name", NULL, NULL, " Bending Rodriguez");if (aerospike_key_operate(&as, &err, NULL, &key, &ops, NULL) != AEROSPIKE_OK) { fprintf(stderr, "Error appending to the string: %s\n", err.message); return 1;}as_operations_destroy(&ops);
as_operations_inita(&ops, 1);as_operations_add_incr(&ops, "quote_cnt", 3);if (aerospike_key_operate(&as, &err, NULL, &key, &ops, NULL) != AEROSPIKE_OK) { fprintf(stderr, "Error adding to the integer: %s\n", err.message); return 1;}as_operations_destroy(&ops);
as_record_destroy(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;}printf("name: %s\n", as_record_get_str(record, "name"));printf("quote_cnt: %lld\n", (long long)as_record_get_int64(record, "quote_cnt", 0));printf("Generation: %d\n", record->gen);The ops variable holds the operations for each command. Call as_operations_inita for each new command, and call as_operations_destroy after each command.
client.operate(null, key, StringOperation.prepend(StringPolicy.Default, "name", "Dr. "));client.operate(null, key, StringOperation.append(StringPolicy.Default, "name", " Bending Rodriguez"));client.operate(null, key, Operation.add(new Bin("quote_cnt", 3)));
record = client.get(null, key);System.out.println("name: " + record.getString("name"));System.out.println("quote_cnt: " + record.getLong("quote_cnt"));System.out.println("Generation: " + record.generation);client.operate(key, [string_operations.prepend("name", "Dr. ")])client.operate(key, [string_operations.append("name", " Bending Rodriguez")])client.operate(key, [operations.increment("quote_cnt", 3)])
(_, meta, bins) = client.get(key)print("name:", bins["name"])print("quote_cnt:", bins["quote_cnt"])print("Generation:", meta["gen"])The legacy Python client also has prepend and append functions, but they are deprecated. Use the String operations instead.
name: Dr. Bender Bending Rodriguezquote_cnt: 50Generation: 4Read specific bins
A read can return only the bins you name. This reduces the data that the database sends over the network.
Read the serialnum and quote_cnt bins, and print how many bins the result has.
record = session.query(key).bin("serialnum").get().bin("quote_cnt").get().execute().getFirstRecord();System.out.println("Bins returned: " + record.bins.size());System.out.println("serialnum: " + record.getLong("serialnum"));System.out.println("quote_cnt: " + record.getLong("quote_cnt"));record = session.query(key).bin("serialnum").get().bin("quote_cnt").get().execute().first_or_raise().record_or_raise()print("Bins returned:", len(record.bins))print("serialnum:", record.bins["serialnum"])print("quote_cnt:", record.bins["quote_cnt"])let record = client.get(&read_policy, &key, ["serialnum", "quote_cnt"]).await?;println!("Bins returned: {}", record.bins.len());println!("serialnum: {}", record.bins["serialnum"]);println!("quote_cnt: {}", record.bins["quote_cnt"]);record = client.Get(null, key, "serialnum", "quote_cnt");Console.WriteLine("Bins returned: " + record.bins.Count);Console.WriteLine("serialnum: " + record.GetLong("serialnum"));Console.WriteLine("quote_cnt: " + record.GetLong("quote_cnt"));record, err = client.Get(nil, key, "serialnum", "quote_cnt")if err != nil { log.Fatal(err)}fmt.Println("Bins returned:", len(record.Bins))fmt.Println("serialnum:", record.Bins["serialnum"])fmt.Println("quote_cnt:", record.Bins["quote_cnt"])record = await client.select(key, ['serialnum', 'quote_cnt']);console.log('Bins returned:', Object.keys(record.bins).length);console.log('serialnum:', record.bins.serialnum);console.log('quote_cnt:', record.bins.quote_cnt);const char* wanted[] = {"serialnum", "quote_cnt", NULL};as_record_destroy(record);record = NULL;if (aerospike_key_select(&as, &err, NULL, &key, wanted, &record) != AEROSPIKE_OK) { fprintf(stderr, "Error reading bins: %s\n", err.message); return 1;}printf("Bins returned: %d\n", (int)as_record_numbins(record));printf("serialnum: %lld\n", (long long)as_record_get_int64(record, "serialnum", 0));printf("quote_cnt: %lld\n", (long long)as_record_get_int64(record, "quote_cnt", 0));record = client.get(null, key, "serialnum", "quote_cnt");System.out.println("Bins returned: " + record.bins.size());System.out.println("serialnum: " + record.getLong("serialnum"));System.out.println("quote_cnt: " + record.getLong("quote_cnt"));(_, _, bins) = client.select(key, ("serialnum", "quote_cnt"))print("Bins returned:", len(bins))print("serialnum:", bins["serialnum"])print("quote_cnt:", bins["quote_cnt"])In the legacy Python client, select takes a list or tuple of bin names.
Bins returned: 2serialnum: 2716057quote_cnt: 50Check whether a record exists
An exists command returns whether a record is in the database, without returning its bins. Check the record you wrote and a key that you never wrote.
Key missing = dataSet.id("nokey");
System.out.println("bender exists: " + session.exists(key).execute().getFirstBoolean().orElse(false));System.out.println("nokey exists: " + session.exists(missing).execute().getFirstBoolean().orElse(false));missing = data_set.id("nokey")
print("bender exists:", str(session.exists(key).execute().first().as_bool()).lower())print("nokey exists:", str(session.exists(missing).execute().first().as_bool()).lower())In the Python SDK, as_bool() returns False when the record doesn’t exist, and raises an error for any other failure.
let missing = as_key!("test", "basicops", "nokey");
println!("bender exists: {}", client.exists(&read_policy, &key).await?);println!("nokey exists: {}", client.exists(&read_policy, &missing).await?);Key missing = new Key("test", "basicops", "nokey");
Console.WriteLine("bender exists: " + client.Exists(null, key).ToString().ToLower());Console.WriteLine("nokey exists: " + client.Exists(null, missing).ToString().ToLower());missing, err := aerospike.NewKey("test", "basicops", "nokey")if err != nil { log.Fatal(err)}
exists, err := client.Exists(nil, key)if err != nil { log.Fatal(err)}fmt.Println("bender exists:", exists)exists, err = client.Exists(nil, missing)if err != nil { log.Fatal(err)}fmt.Println("nokey exists:", exists)const missing = new Aerospike.Key('test', 'basicops', 'nokey');
console.log('bender exists:', await client.exists(key));console.log('nokey exists:', await client.exists(missing));as_key missing;as_key_init_str(&missing, "test", "basicops", "nokey");
as_record* meta = NULL;as_status status = aerospike_key_exists(&as, &err, NULL, &key, &meta);if (status != AEROSPIKE_OK && status != AEROSPIKE_ERR_RECORD_NOT_FOUND) { fprintf(stderr, "Error checking the record: %s\n", err.message); return 1;}printf("bender exists: %s\n", status == AEROSPIKE_OK ? "true" : "false");as_record_destroy(meta);
meta = NULL;status = aerospike_key_exists(&as, &err, NULL, &missing, &meta);if (status != AEROSPIKE_OK && status != AEROSPIKE_ERR_RECORD_NOT_FOUND) { fprintf(stderr, "Error checking the record: %s\n", err.message); return 1;}printf("nokey exists: %s\n", status == AEROSPIKE_OK ? "true" : "false");as_record_destroy(meta);Key missing = new Key("test", "basicops", "nokey");
System.out.println("bender exists: " + client.exists(null, key));System.out.println("nokey exists: " + client.exists(null, missing));missing = ("test", "basicops", "nokey")
(_, meta) = client.exists(key)print("bender exists:", str(meta is not None).lower())(_, meta) = client.exists(missing)print("nokey exists:", str(meta is not None).lower())In the legacy Python client, exists returns the key and the record metadata. The metadata is None if the record doesn’t exist.
bender exists: truenokey exists: falseRead several records in one batch
A batch read gets several records in one call, which saves network round trips compared with reading them one at a time. Write two records, key1 and key2, each with a batch bin. Then read three keys in one batch. The third key, key3, doesn’t exist.
A batch returns a result for each key, in the order of the keys. The result for a missing key has no record. The Java SDK and Python SDK omit missing keys from the results unless you call includeMissingKeys() or include_missing_keys(), as the examples do.
Key key1 = dataSet.id("key1");Key key2 = dataSet.id("key2");Key key3 = dataSet.id("key3");
session.upsert(key1).bin("batch").setTo(1).execute();session.upsert(key2).bin("batch").setTo(2).execute();
RecordStream stream = session.query(key1, key2, key3).includeMissingKeys().execute();while (stream.hasNext()) { RecordResult result = stream.next(); if (result.isOk()) { System.out.println(result.getKey().userKey + ": " + result.getRecord().getLong("batch")); } else { System.out.println(result.getKey().userKey + ": not found"); }}key1 = data_set.id("key1")key2 = data_set.id("key2")key3 = data_set.id("key3")
session.upsert(key1).put({"batch": 1}).execute()session.upsert(key2).put({"batch": 2}).execute()
for result in session.query([key1, key2, key3]).include_missing_keys().execute(): if result.as_bool(): print(f"{result.key.value}: {result.record_or_raise().bins['batch']}") else: print(f"{result.key.value}: not found")let key1 = as_key!("test", "basicops", "key1");let key2 = as_key!("test", "basicops", "key2");let key3 = as_key!("test", "basicops", "key3");
client.put(&write_policy, &key1, &[as_bin!("batch", 1)]).await?;client.put(&write_policy, &key2, &[as_bin!("batch", 2)]).await?;
let batch_read_policy = BatchReadPolicy::default();let mut batch = vec![ BatchOperation::read(&batch_read_policy, key1.clone(), Bins::All), BatchOperation::read(&batch_read_policy, key2.clone(), Bins::All), BatchOperation::read(&batch_read_policy, key3.clone(), Bins::All),];client.batch(&BatchPolicy::default(), &mut batch).await?;
for operation in &batch { let result = operation.batch_record(); match &result.record { Some(record) => println!("{}: {}", result.key.user_key().as_ref().unwrap(), record.bins["batch"]), None => println!("{}: not found", result.key.user_key().as_ref().unwrap()), }}Key key1 = new Key("test", "basicops", "key1");Key key2 = new Key("test", "basicops", "key2");Key key3 = new Key("test", "basicops", "key3");
client.Put(null, key1, new Bin("batch", 1));client.Put(null, key2, new Bin("batch", 2));
Key[] keys = { key1, key2, key3 };Record[] records = client.Get(null, keys);for (int i = 0; i < keys.Length; i++){ if (records[i] != null) { Console.WriteLine(keys[i].userKey + ": " + records[i].GetLong("batch")); } else { Console.WriteLine(keys[i].userKey + ": not found"); }}key1, err := aerospike.NewKey("test", "basicops", "key1")if err != nil { log.Fatal(err)}key2, err := aerospike.NewKey("test", "basicops", "key2")if err != nil { log.Fatal(err)}key3, err := aerospike.NewKey("test", "basicops", "key3")if err != nil { log.Fatal(err)}
if err := client.PutBins(nil, key1, aerospike.NewBin("batch", 1)); err != nil { log.Fatal(err)}if err := client.PutBins(nil, key2, aerospike.NewBin("batch", 2)); err != nil { log.Fatal(err)}
keys := []*aerospike.Key{key1, key2, key3}records, err := client.BatchGet(nil, keys)if err != nil { log.Fatal(err)}for i, batchRecord := range records { if batchRecord != nil { fmt.Printf("%v: %v\n", keys[i].Value(), batchRecord.Bins["batch"]) } else { fmt.Printf("%v: not found\n", keys[i].Value()) }}const key1 = new Aerospike.Key('test', 'basicops', 'key1');const key2 = new Aerospike.Key('test', 'basicops', 'key2');const key3 = new Aerospike.Key('test', 'basicops', 'key3');
await client.put(key1, { batch: 1 });await client.put(key2, { batch: 2 });
const results = await client.batchRead([ { key: key1, readAllBins: true }, { key: key2, readAllBins: true }, { key: key3, readAllBins: true },]);for (const result of results) { if (result.status === Aerospike.status.OK) { console.log(`${result.record.key.key}: ${result.record.bins.batch}`); } else { console.log(`${result.record.key.key}: not found`); }}Each batch result has a status and a record. For a missing key, the record has the key but no bins. The status is Aerospike.status.OK when the record exists.
const char* batch_ids[] = {"key1", "key2", "key3"};
for (int i = 0; i < 2; i++) { as_key batch_key; as_key_init_str(&batch_key, "test", "basicops", batch_ids[i]); as_record_inita(&rec, 1); as_record_set_int64(&rec, "batch", i + 1); if (aerospike_key_put(&as, &err, NULL, &batch_key, &rec) != AEROSPIKE_OK) { fprintf(stderr, "Error writing record: %s\n", err.message); as_record_destroy(&rec); as_key_destroy(&batch_key); return 1; } as_record_destroy(&rec); as_key_destroy(&batch_key);}
as_batch_records records;as_batch_records_inita(&records, 3);for (int i = 0; i < 3; i++) { as_batch_read_record* entry = as_batch_read_reserve(&records); as_key_init_str(&entry->key, "test", "basicops", batch_ids[i]); entry->read_all_bins = true;}if (aerospike_batch_read(&as, &err, NULL, &records) != AEROSPIKE_OK) { fprintf(stderr, "Error reading the batch: %s\n", err.message); return 1;}for (uint32_t i = 0; i < records.list.size; i++) { as_batch_read_record* entry = as_vector_get(&records.list, i); if (entry->result == AEROSPIKE_OK) { printf("%s: %lld\n", batch_ids[i], (long long)as_record_get_int64(&entry->record, "batch", 0)); } else { printf("%s: not found\n", batch_ids[i]); }}as_batch_records_destroy(&records);The C client reads a batch with as_batch_records. Each entry has a key, a result, and the record. The as_batch_records_destroy function frees the entries.
Key key1 = new Key("test", "basicops", "key1");Key key2 = new Key("test", "basicops", "key2");Key key3 = new Key("test", "basicops", "key3");
client.put(null, key1, new Bin("batch", 1));client.put(null, key2, new Bin("batch", 2));
Key[] keys = {key1, key2, key3};Record[] records = client.get(null, keys);for (int i = 0; i < keys.length; i++) { if (records[i] != null) { System.out.println(keys[i].userKey + ": " + records[i].getLong("batch")); } else { System.out.println(keys[i].userKey + ": not found"); }}key1 = ("test", "basicops", "key1")key2 = ("test", "basicops", "key2")key3 = ("test", "basicops", "key3")
client.put(key1, {"batch": 1})client.put(key2, {"batch": 2})
batch = client.batch_read([key1, key2, key3])for result in batch.batch_records: if result.result == 0: print(f"{result.key[2]}: {result.record[2]['batch']}") else: print(f"{result.key[2]}: not found")In the legacy Python client, batch_read returns a BatchRecords object. Each entry in batch_records has a result code, which is 0 when the record exists, and a record tuple of the key, the metadata, and the bins. The record is None when the record doesn’t exist.
key1: 1key2: 2key3: not foundDelete a record
The delete command removes a record. Delete key1, and then check that it no longer exists.
session.delete(key1).execute();
System.out.println("key1 exists: " + session.exists(key1).execute().getFirstBoolean().orElse(false));session.delete(key1).execute()
print("key1 exists:", str(session.exists(key1).execute().first().as_bool()).lower())client.delete(&write_policy, &key1).await?;
println!("key1 exists: {}", client.exists(&read_policy, &key1).await?);client.Delete(null, key1);
Console.WriteLine("key1 exists: " + client.Exists(null, key1).ToString().ToLower());_, err = client.Delete(nil, key1)if err != nil { log.Fatal(err)}
exists, err = client.Exists(nil, key1)if err != nil { log.Fatal(err)}fmt.Println("key1 exists:", exists)await client.remove(key1);
console.log('key1 exists:', await client.exists(key1));as_key key1;as_key_init_str(&key1, "test", "basicops", "key1");if (aerospike_key_remove(&as, &err, NULL, &key1) != AEROSPIKE_OK) { fprintf(stderr, "Error deleting record: %s\n", err.message); return 1;}
meta = NULL;status = aerospike_key_exists(&as, &err, NULL, &key1, &meta);if (status != AEROSPIKE_OK && status != AEROSPIKE_ERR_RECORD_NOT_FOUND) { fprintf(stderr, "Error checking the record: %s\n", err.message); return 1;}printf("key1 exists: %s\n", status == AEROSPIKE_OK ? "true" : "false");as_record_destroy(meta);client.delete(null, key1);
System.out.println("key1 exists: " + client.exists(null, key1));client.remove(key1)
(_, meta) = client.exists(key1)print("key1 exists:", str(meta is not None).lower())In the legacy Python client, remove raises RecordNotFound if the record doesn’t exist.
key1 exists: falseRun several operations in one command
An operate command runs several operations on one record as a single command. The database runs the operations in the order you specify. The whole command is atomic, so no other command sees the record with only some operations applied. The command increments the generation once, however many operations it has.
Write a record for fry with an age bin and a career bin. Then run one command that adds 1000 to the age, builds the name bin in three steps (write J., prepend Phillip , and append Fry), and reads the career bin. Finally, read the record to see the result of the writes.
The command returns only the bin that the read operation names and a value for each operation that reads. If several operations in one command use the same bin, some clients return a list of results for that bin. To keep the results simple, this example reads a bin that no other operation in the command uses.
Key fry = dataSet.id("fry");session.upsert(fry).bin("age").setTo(25).bin("career").setTo("delivery boy").execute();
Record result = session.upsert(fry) .bin("age").add(1000) .bin("name").setTo("J.") .bin("name").prepend("Phillip ") .bin("name").append(" Fry") .bin("career").get() .execute().getFirstRecord();System.out.println("career: " + result.getString("career"));
record = session.query(fry).execute().getFirstRecord();System.out.println("name: " + record.getString("name"));System.out.println("age: " + record.getLong("age"));System.out.println("Generation: " + record.generation);fry = data_set.id("fry")session.upsert(fry).put({"age": 25, "career": "delivery boy"}).execute()
result = ( session.upsert(fry) .bin("age").add(1000) .bin("name").set_to("J.") .bin("name").prepend("Phillip ") .bin("name").append(" Fry") .bin("career").get() .execute().first_or_raise().record_or_raise())print("career:", result.bins["career"])
record = session.query(fry).execute().first_or_raise().record_or_raise()print("name:", record.bins["name"])print("age:", record.bins["age"])print("Generation:", record.generation)let fry = as_key!("test", "basicops", "fry");client.put(&write_policy, &fry, &[as_bin!("age", 25), as_bin!("career", "delivery boy")]).await?;
let result = client.operate(&write_policy, &fry, &[ scalar::add(&as_bin!("age", 1000)), scalar::put(&as_bin!("name", "J.")), string::prepend(&StringPolicy::default(), "name", "Phillip "), string::append(&StringPolicy::default(), "name", " Fry"), scalar::get_bin("career"),]).await?;println!("career: {}", result.bins["career"]);
let record = client.get(&read_policy, &fry, Bins::All).await?;println!("name: {}", record.bins["name"]);println!("age: {}", record.bins["age"]);println!("Generation: {}", record.generation);Key fry = new Key("test", "basicops", "fry");client.Put(null, fry, new Bin("age", 25), new Bin("career", "delivery boy"));
Record result = client.Operate(null, fry, Operation.Add(new Bin("age", 1000)), Operation.Put(new Bin("name", "J.")), StringOperation.Prepend(StringPolicy.Default, "name", "Phillip "), StringOperation.Append(StringPolicy.Default, "name", " Fry"), Operation.Get("career"));Console.WriteLine("career: " + result.GetString("career"));
record = client.Get(null, fry);Console.WriteLine("name: " + record.GetString("name"));Console.WriteLine("age: " + record.GetLong("age"));Console.WriteLine("Generation: " + record.generation);fry, err := aerospike.NewKey("test", "basicops", "fry")if err != nil { log.Fatal(err)}err = client.PutBins(nil, fry, aerospike.NewBin("age", 25), aerospike.NewBin("career", "delivery boy"))if err != nil { log.Fatal(err)}
result, err := client.Operate(nil, fry, aerospike.AddOp(aerospike.NewBin("age", 1000)), aerospike.PutOp(aerospike.NewBin("name", "J.")), aerospike.StrPrependOp(aerospike.DefaultStringPolicy, "name", "Phillip "), aerospike.StrAppendOp(aerospike.DefaultStringPolicy, "name", " Fry"), aerospike.GetBinOp("career"))if err != nil { log.Fatal(err)}fmt.Println("career:", result.Bins["career"])
record, err = client.Get(nil, fry)if err != nil { log.Fatal(err)}fmt.Println("name:", record.Bins["name"])fmt.Println("age:", record.Bins["age"])fmt.Println("Generation:", record.Generation)const fry = new Aerospike.Key('test', 'basicops', 'fry');await client.put(fry, { age: 25, career: 'delivery boy' });
const result = await client.operate(fry, [ op.incr('age', 1000), op.write('name', 'J.'), strings.prepend('name', 'Phillip '), strings.append('name', ' Fry'), op.read('career'),]);console.log('career:', result.bins.career);
record = await client.get(fry);console.log('name:', record.bins.name);console.log('age:', record.bins.age);console.log('Generation:', record.gen);as_key fry;as_key_init_str(&fry, "test", "basicops", "fry");as_record_inita(&rec, 2);as_record_set_int64(&rec, "age", 25);as_record_set_str(&rec, "career", "delivery boy");if (aerospike_key_put(&as, &err, NULL, &fry, &rec) != AEROSPIKE_OK) { fprintf(stderr, "Error writing record: %s\n", err.message); as_record_destroy(&rec); return 1;}as_record_destroy(&rec);
as_operations_inita(&ops, 5);as_operations_add_incr(&ops, "age", 1000);as_operations_add_write_str(&ops, "name", "J.");as_operations_string_prepend(&ops, "name", NULL, NULL, "Phillip ");as_operations_string_append(&ops, "name", NULL, NULL, " Fry");as_operations_add_read(&ops, "career");as_record* result = NULL;if (aerospike_key_operate(&as, &err, NULL, &fry, &ops, &result) != AEROSPIKE_OK) { fprintf(stderr, "Error running the command: %s\n", err.message); return 1;}printf("career: %s\n", as_record_get_str(result, "career"));as_operations_destroy(&ops);as_record_destroy(result);
as_record_destroy(record);record = NULL;if (aerospike_key_get(&as, &err, NULL, &fry, &record) != AEROSPIKE_OK) { fprintf(stderr, "Error reading record: %s\n", err.message); 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);The command has five operations, so the example allocates the operations with as_operations_inita(&ops, 5).
Key fry = new Key("test", "basicops", "fry");client.put(null, fry, new Bin("age", 25), new Bin("career", "delivery boy"));
Record result = client.operate(null, fry, Operation.add(new Bin("age", 1000)), Operation.put(new Bin("name", "J.")), StringOperation.prepend(StringPolicy.Default, "name", "Phillip "), StringOperation.append(StringPolicy.Default, "name", " Fry"), Operation.get("career"));System.out.println("career: " + result.getString("career"));
record = client.get(null, fry);System.out.println("name: " + record.getString("name"));System.out.println("age: " + record.getLong("age"));System.out.println("Generation: " + record.generation);fry = ("test", "basicops", "fry")client.put(fry, {"age": 25, "career": "delivery boy"})
(_, _, result) = client.operate(fry, [ operations.increment("age", 1000), operations.write("name", "J."), string_operations.prepend("name", "Phillip "), string_operations.append("name", " Fry"), operations.read("career"),])print("career:", result["career"])
(_, meta, bins) = client.get(fry)print("name:", bins["name"])print("age:", bins["age"])print("Generation:", meta["gen"])career: delivery boyname: Phillip J. Fryage: 1025Generation: 2Read and delete a record in one command
An operate command can read a record and delete it in the same command. The read comes first, so it returns the bins before the delete removes the record.
Read the name bin of fry and delete the record, and then check that the record no longer exists.
Record last = session.upsert(fry).bin("name").get().deleteRecord().execute().getFirstRecord();System.out.println("name: " + last.getString("name"));
System.out.println("fry exists: " + session.exists(fry).execute().getFirstBoolean().orElse(false));last = session.upsert(fry).bin("name").get().delete_record().execute().first_or_raise().record_or_raise()print("name:", last.bins["name"])
print("fry exists:", str(session.exists(fry).execute().first().as_bool()).lower())let last = client.operate(&write_policy, &fry, &[scalar::get_bin("name"), scalar::delete()]).await?;println!("name: {}", last.bins["name"]);
println!("fry exists: {}", client.exists(&read_policy, &fry).await?);Record last = client.Operate(null, fry, Operation.Get("name"), Operation.Delete());Console.WriteLine("name: " + last.GetString("name"));
Console.WriteLine("fry exists: " + client.Exists(null, fry).ToString().ToLower());last, err := client.Operate(nil, fry, aerospike.GetBinOp("name"), aerospike.DeleteOp())if err != nil { log.Fatal(err)}fmt.Println("name:", last.Bins["name"])
exists, err = client.Exists(nil, fry)if err != nil { log.Fatal(err)}fmt.Println("fry exists:", exists)const last = await client.operate(fry, [op.read('name'), op.delete()]);console.log('name:', last.bins.name);
console.log('fry exists:', await client.exists(fry));as_operations_inita(&ops, 2);as_operations_add_read(&ops, "name");as_operations_add_delete(&ops);as_record* last = NULL;if (aerospike_key_operate(&as, &err, NULL, &fry, &ops, &last) != AEROSPIKE_OK) { fprintf(stderr, "Error running the command: %s\n", err.message); return 1;}printf("name: %s\n", as_record_get_str(last, "name"));as_operations_destroy(&ops);as_record_destroy(last);
meta = NULL;status = aerospike_key_exists(&as, &err, NULL, &fry, &meta);if (status != AEROSPIKE_OK && status != AEROSPIKE_ERR_RECORD_NOT_FOUND) { fprintf(stderr, "Error checking the record: %s\n", err.message); return 1;}printf("fry exists: %s\n", status == AEROSPIKE_OK ? "true" : "false");as_record_destroy(meta);Record last = client.operate(null, fry, Operation.get("name"), Operation.delete());System.out.println("name: " + last.getString("name"));
System.out.println("fry exists: " + client.exists(null, fry));(_, _, last) = client.operate(fry, [operations.read("name"), operations.delete()])print("name:", last["name"])
(_, meta) = client.exists(fry)print("fry exists:", str(meta is not None).lower())name: Phillip J. Fryfry exists: falseDelete the remaining records and close the connection
Delete the two records that are still in the database, and then close the client.
session.delete(key).execute();session.delete(key2).execute();cluster.close();session.delete(key).execute()session.delete(key2).execute()cluster.close()client.delete(&write_policy, &key).await?;client.delete(&write_policy, &key2).await?;client.close().await?;client.Delete(null, key);client.Delete(null, key2);client.Close();for _, k := range []*aerospike.Key{key, key2} { if _, err := client.Delete(nil, k); err != nil { log.Fatal(err) }}client.Close()await client.remove(key);await client.remove(key2);client.close();as_key key2;as_key_init_str(&key2, "test", "basicops", "key2");if (aerospike_key_remove(&as, &err, NULL, &key) != AEROSPIKE_OK || aerospike_key_remove(&as, &err, NULL, &key2) != AEROSPIKE_OK) { fprintf(stderr, "Error deleting records: %s\n", err.message); return 1;}
as_record_destroy(record);as_key_destroy(&key);as_key_destroy(&key1);as_key_destroy(&key2);as_key_destroy(&missing);as_key_destroy(&fry);aerospike_close(&as, &err);aerospike_destroy(&as);client.delete(null, key);client.delete(null, key2);client.close();client.remove(key)client.remove(key2)client.close()Complete program
This program combines the steps. It writes a record, reads it, updates it with one multi-operation command, and deletes it.
import java.util.List;
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 BasicOperations { 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", "basicops").id("bender");
session.upsert(key) .bin("name").setTo("Bender") .bin("composition").setTo(List.of("40% zinc", "40% titanium", "30% iron", "40% dolomite")) .bin("quote_cnt").setTo(47) .execute();
Record record = session.query(key).execute().getFirstRecord(); System.out.println("name: " + record.getString("name")); System.out.println("quote_cnt: " + record.getLong("quote_cnt"));
session.upsert(key) .bin("name").prepend("Dr. ") .bin("name").append(" Bending Rodriguez") .bin("quote_cnt").add(3) .execute();
record = session.query(key).execute().getFirstRecord(); System.out.println("name: " + record.getString("name")); System.out.println("quote_cnt: " + record.getLong("quote_cnt")); System.out.println("Generation: " + record.generation);
session.delete(key).execute(); System.out.println("bender exists: " + session.exists(key).execute().getFirstBoolean().orElse(false)); } }}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", "basicops").id("bender")
session.upsert(key).put({ "name": "Bender", "composition": ["40% zinc", "40% titanium", "30% iron", "40% dolomite"], "quote_cnt": 47, }).execute()
record = session.query(key).execute().first_or_raise().record_or_raise() print("name:", record.bins["name"]) print("quote_cnt:", record.bins["quote_cnt"])
( session.upsert(key) .bin("name").prepend("Dr. ") .bin("name").append(" Bending Rodriguez") .bin("quote_cnt").add(3) .execute() )
record = session.query(key).execute().first_or_raise().record_or_raise() print("name:", record.bins["name"]) print("quote_cnt:", record.bins["quote_cnt"]) print("Generation:", record.generation)
session.delete(key).execute() print("bender exists:", str(session.exists(key).execute().first().as_bool()).lower())except AerospikeError as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1)finally: cluster.close()use aerospike::operations::scalar;use aerospike::operations::string::{self, StringPolicy};use aerospike::{as_bin, as_key, as_list, as_val, 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 write_policy = WritePolicy::default(); let read_policy = ReadPolicy::default(); let key = as_key!("test", "basicops", "bender");
client.put(&write_policy, &key, &[ as_bin!("name", "Bender"), as_bin!("composition", as_list!("40% zinc", "40% titanium", "30% iron", "40% dolomite")), as_bin!("quote_cnt", 47), ]).await?;
let record = client.get(&read_policy, &key, Bins::All).await?; println!("name: {}", record.bins["name"]); println!("quote_cnt: {}", record.bins["quote_cnt"]);
client.operate(&write_policy, &key, &[ string::prepend(&StringPolicy::default(), "name", "Dr. "), string::append(&StringPolicy::default(), "name", " Bending Rodriguez"), scalar::add(&as_bin!("quote_cnt", 3)), ]).await?;
let record = client.get(&read_policy, &key, Bins::All).await?; println!("name: {}", record.bins["name"]); println!("quote_cnt: {}", record.bins["quote_cnt"]); println!("Generation: {}", record.generation);
client.delete(&write_policy, &key).await?; println!("bender exists: {}", client.exists(&read_policy, &key).await?);
client.close().await?; Ok(())}using System;using System.Collections.Generic;using Aerospike.Client;
public class BasicOperations{ public static void Main() { AerospikeClient client = new AerospikeClient("127.0.0.1", 3000); try { Key key = new Key("test", "basicops", "bender");
client.Put(null, key, new Bin("name", "Bender"), new Bin("composition", new List<string> { "40% zinc", "40% titanium", "30% iron", "40% dolomite" }), new Bin("quote_cnt", 47));
Record record = client.Get(null, key); Console.WriteLine("name: " + record.GetString("name")); Console.WriteLine("quote_cnt: " + record.GetLong("quote_cnt"));
client.Operate(null, key, StringOperation.Prepend(StringPolicy.Default, "name", "Dr. "), StringOperation.Append(StringPolicy.Default, "name", " Bending Rodriguez"), Operation.Add(new Bin("quote_cnt", 3)));
record = client.Get(null, key); Console.WriteLine("name: " + record.GetString("name")); Console.WriteLine("quote_cnt: " + record.GetLong("quote_cnt")); Console.WriteLine("Generation: " + record.generation);
client.Delete(null, key); Console.WriteLine("bender exists: " + client.Exists(null, key).ToString().ToLower()); } 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", "basicops", "bender") if err != nil { log.Fatal(err) }
err = client.PutBins(nil, key, aerospike.NewBin("name", "Bender"), aerospike.NewBin("composition", []string{"40% zinc", "40% titanium", "30% iron", "40% dolomite"}), aerospike.NewBin("quote_cnt", 47)) 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("quote_cnt:", record.Bins["quote_cnt"])
_, err = client.Operate(nil, key, aerospike.StrPrependOp(aerospike.DefaultStringPolicy, "name", "Dr. "), aerospike.StrAppendOp(aerospike.DefaultStringPolicy, "name", " Bending Rodriguez"), aerospike.AddOp(aerospike.NewBin("quote_cnt", 3))) 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("quote_cnt:", record.Bins["quote_cnt"]) fmt.Println("Generation:", record.Generation)
if _, err := client.Delete(nil, key); err != nil { log.Fatal(err) } exists, err := client.Exists(nil, key) if err != nil { log.Fatal(err) } fmt.Println("bender exists:", exists)}import Aerospike from 'aerospike';
const { operations: op, strings } = Aerospike;
const client = await Aerospike.connect({ hosts: '127.0.0.1:3000' });try { const key = new Aerospike.Key('test', 'basicops', 'bender');
await client.put(key, { name: 'Bender', composition: ['40% zinc', '40% titanium', '30% iron', '40% dolomite'], quote_cnt: 47, });
let record = await client.get(key); console.log('name:', record.bins.name); console.log('quote_cnt:', record.bins.quote_cnt);
await client.operate(key, [ strings.prepend('name', 'Dr. '), strings.append('name', ' Bending Rodriguez'), op.incr('quote_cnt', 3), ]);
record = await client.get(key); console.log('name:', record.bins.name); console.log('quote_cnt:', record.bins.quote_cnt); console.log('Generation:', record.gen);
await client.remove(key); console.log('bender exists:', await client.exists(key));} finally { client.close();}#include <stdio.h>#include <aerospike/aerospike.h>#include <aerospike/aerospike_key.h>#include <aerospike/as_arraylist.h>#include <aerospike/as_error.h>#include <aerospike/as_key.h>#include <aerospike/as_operations.h>#include <aerospike/as_record.h>#include <aerospike/as_string_operations.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; }
int exit_code = 1; as_record* record = NULL; as_record* header = NULL; as_key key; as_key_init_str(&key, "test", "basicops", "bender");
as_arraylist composition; as_arraylist_inita(&composition, 4); as_arraylist_append_str(&composition, "40% zinc"); as_arraylist_append_str(&composition, "40% titanium"); as_arraylist_append_str(&composition, "30% iron"); as_arraylist_append_str(&composition, "40% dolomite");
as_record rec; as_record_inita(&rec, 3); as_record_set_str(&rec, "name", "Bender"); as_record_set_list(&rec, "composition", (as_list*)&composition); as_record_set_int64(&rec, "quote_cnt", 47); as_status status = aerospike_key_put(&as, &err, NULL, &key, &rec); as_record_destroy(&rec); if (status != AEROSPIKE_OK) { fprintf(stderr, "Error writing record: %s\n", err.message); goto cleanup; }
if (aerospike_key_get(&as, &err, NULL, &key, &record) != AEROSPIKE_OK) { fprintf(stderr, "Error reading record: %s\n", err.message); goto cleanup; } printf("name: %s\n", as_record_get_str(record, "name")); printf("quote_cnt: %lld\n", (long long)as_record_get_int64(record, "quote_cnt", 0));
as_operations ops; as_operations_inita(&ops, 3); as_operations_string_prepend(&ops, "name", NULL, NULL, "Dr. "); as_operations_string_append(&ops, "name", NULL, NULL, " Bending Rodriguez"); as_operations_add_incr(&ops, "quote_cnt", 3); status = aerospike_key_operate(&as, &err, NULL, &key, &ops, NULL); as_operations_destroy(&ops); if (status != AEROSPIKE_OK) { fprintf(stderr, "Error running the command: %s\n", err.message); goto cleanup; }
as_record_destroy(record); record = NULL; if (aerospike_key_get(&as, &err, NULL, &key, &record) != AEROSPIKE_OK) { fprintf(stderr, "Error reading record: %s\n", err.message); goto cleanup; } printf("name: %s\n", as_record_get_str(record, "name")); printf("quote_cnt: %lld\n", (long long)as_record_get_int64(record, "quote_cnt", 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); goto cleanup; } status = aerospike_key_exists(&as, &err, NULL, &key, &header); if (status != AEROSPIKE_OK && status != AEROSPIKE_ERR_RECORD_NOT_FOUND) { fprintf(stderr, "Error checking the record: %s\n", err.message); goto cleanup; } printf("bender exists: %s\n", status == AEROSPIKE_OK ? "true" : "false"); exit_code = 0;
cleanup: as_record_destroy(header); as_record_destroy(record); as_key_destroy(&key); aerospike_close(&as, &err); aerospike_destroy(&as); return exit_code;}import java.util.List;
import com.aerospike.client.AerospikeClient;import com.aerospike.client.Bin;import com.aerospike.client.Key;import com.aerospike.client.Operation;import com.aerospike.client.Record;import com.aerospike.client.operation.StringOperation;import com.aerospike.client.operation.StringPolicy;
public class BasicOperations { public static void main(String[] args) { try (AerospikeClient client = new AerospikeClient("127.0.0.1", 3000)) { Key key = new Key("test", "basicops", "bender");
client.put(null, key, new Bin("name", "Bender"), new Bin("composition", List.of("40% zinc", "40% titanium", "30% iron", "40% dolomite")), new Bin("quote_cnt", 47));
Record record = client.get(null, key); System.out.println("name: " + record.getString("name")); System.out.println("quote_cnt: " + record.getLong("quote_cnt"));
client.operate(null, key, StringOperation.prepend(StringPolicy.Default, "name", "Dr. "), StringOperation.append(StringPolicy.Default, "name", " Bending Rodriguez"), Operation.add(new Bin("quote_cnt", 3)));
record = client.get(null, key); System.out.println("name: " + record.getString("name")); System.out.println("quote_cnt: " + record.getLong("quote_cnt")); System.out.println("Generation: " + record.generation);
client.delete(null, key); System.out.println("bender exists: " + client.exists(null, key)); } }}import sys
import aerospikefrom aerospike import exception as exfrom aerospike_helpers.operations import operations, string_operations
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", "basicops", "bender") client.put(key, { "name": "Bender", "composition": ["40% zinc", "40% titanium", "30% iron", "40% dolomite"], "quote_cnt": 47, })
(_, meta, bins) = client.get(key) print("name:", bins["name"]) print("quote_cnt:", bins["quote_cnt"])
client.operate(key, [ string_operations.prepend("name", "Dr. "), string_operations.append("name", " Bending Rodriguez"), operations.increment("quote_cnt", 3), ])
(_, meta, bins) = client.get(key) print("name:", bins["name"]) print("quote_cnt:", bins["quote_cnt"]) print("Generation:", meta["gen"])
client.remove(key) (_, meta) = client.exists(key) print("bender exists:", str(meta is not None).lower())except ex.AerospikeError as e: print(f"Error: {e}", file=sys.stderr) sys.exit(1)finally: client.close()name: Benderquote_cnt: 47name: Dr. Bender Bending Rodriguezquote_cnt: 50Generation: 2bender exists: falseWhat you learned
You wrote, read, updated, and deleted records, read specific bins and batches, and checked existence. You also ran several operations on one record in one atomic command, including a read and a delete in the same command.
Next steps
- Run several operations on one record in more detail, with the Intro to transactions tutorial.
- Update a record only if no one else has changed it, with the Read-write transactions tutorial.
- Learn how the Developer SDKs run commands in Create records, Read records, Update records, and Delete records.
- Learn how the other clients run multiple operations in one command: Java, Python, Rust, C#, Go, Node.js, or C.