Single-record commands
For the complete documentation index see: llms.txt
All documentation pages available in markdown.
Aerospike provides simple interfaces for reading data from and writing data to an Aerospike cluster. They cover the standard CRUD (create, read, update, delete) use cases.
Every Aerospike client can perform the following single-record commands, no matter which language it’s written in:
| Command | Description |
|---|---|
put | Write a record. Performs the equivalent of create, update or replace, depending on the write policy given to the write command. |
get | Read the record. Specific bins can be selected. |
operate | Executes multiple bin operations atomically and in isolation as a single record command. |
touch | Increment the generation counter and reset its time-to-live (TTL) |
delete | Remove a record from the database. Generates a tombstone when using the durable-delete policy. |
Filtering operations
A command can be conditionally applied, based on the result of a record filter expression. If the filter expression evaluates to true, the operation executes.
Code examples of record operations
Every record is identified by a key consisting of a namespace, an optional set, and a user key. In the following examples, the key is ("test", "demo", "user1"), placing the record in the demo set of the test namespace.
A record can also be created without a set by passing null (or None) as the set component. Such records belong to the null set. Records in the null set are fully accessible through single-record commands (put, get, operate, touch, delete) and batch commands, but cannot be targeted by a secondary index query unless the index covers the entire namespace. You can prevent null-set records from being created by setting disallow-null-setname to true.
The following examples demonstrate put (create and merge-style update), get, operate (atomic multi-bin updates in one round trip), touch, and delete on a single record.
They use a record with a string bin, an integer bin, and a map bin:
| Bin | Type | Value |
|---|---|---|
name | string | "Alice" |
visits | integer | 1 |
prefs | map | {"theme": "dark", "lang": "en"} |
Each section below shows an excerpt. See the Code block at the bottom of the page for the full, continuous program in each language.
Create a record
Use put to write a new record. By default, put creates the record if it does not exist, or merges bins into the existing record if it does. This behavior is controlled by the write policy’s recordExistsAction, which defaults to UPDATE (upsert). Other options include CREATE_ONLY, UPDATE_ONLY, and REPLACE. In the Developer SDKs, the write verb sets the behavior: upsert, insert, update, or replace.
Map<String, Object> prefs = new HashMap<>();prefs.put("theme", "dark");prefs.put("lang", "en");
// upsert creates the record or merges bins into it;// insert, update and replace are the other write verbs.session.upsert(key) .bin("name").setTo("Alice") .bin("visits").setTo(1) .bin("prefs").setTo(prefs) .execute();bins = { "name": "Alice", "visits": 1, "prefs": {"theme": "dark", "lang": "en"},}
# upsert creates the record or merges bins into it;# insert, update and replace are the other write verbs.session.upsert(key).put(bins).execute()let bins = [ as_bin!("name", "Alice"), as_bin!("visits", 1), as_bin!("prefs", as_map!("theme" => "dark", "lang" => "en")),];
// Default upsert behavior (RecordExistsAction::Update)// let mut wp = WritePolicy::default();// wp.record_exists_action = RecordExistsAction::Update;// client.put(&wp, &key, &bins).await?;
client.put(&WritePolicy::default(), &key, &bins).await?;var prefs = new Dictionary<string, object> { { "theme", "dark" }, { "lang", "en" }};
// Default upsert behavior (RecordExistsAction.UPDATE)// WritePolicy wp = new WritePolicy();// wp.recordExistsAction = RecordExistsAction.UPDATE;// client.Put(wp, key, ...);
client.Put(null, key, new Bin("name", "Alice"), new Bin("visits", 1), new Bin("prefs", prefs));// Requires: import as "github.com/aerospike/aerospike-client-go/v8"prefs := map[interface{}]interface{}{ "theme": "dark", "lang": "en",}
// Default upsert behavior (as.UPDATE)// wp := as.NewWritePolicy(0, 0)// wp.RecordExistsAction = as.UPDATE// err = client.PutBins(wp, key, ...)
err = client.PutBins(nil, key, as.NewBin("name", "Alice"), as.NewBin("visits", 1), as.NewBin("prefs", prefs))if err != nil { log.Fatal(err)}const bins = { name: "Alice", visits: 1, prefs: { theme: "dark", lang: "en" },};
// Default upsert behavior (Aerospike.policy.exists.UPDATE)// const wp = new Aerospike.WritePolicy({// exists: Aerospike.policy.exists.UPDATE,// });// await client.put(key, bins, {}, wp);
await client.put(key, bins);as_hashmap prefs;as_hashmap_init(&prefs, 2);as_stringmap_set_str((as_map *)&prefs, "theme", "dark");as_stringmap_set_str((as_map *)&prefs, "lang", "en");
as_record rec;as_record_inita(&rec, 3);as_record_set_str(&rec, "name", "Alice");as_record_set_int64(&rec, "visits", 1);as_record_set_map(&rec, "prefs", (as_map *)&prefs);
// Default upsert behavior (AS_POLICY_EXISTS_UPDATE)// as_policy_write wp;// as_policy_write_init(&wp);// wp.exists = AS_POLICY_EXISTS_UPDATE;// aerospike_key_put(&as, &err, &wp, &key, &rec);
aerospike_key_put(&as, &err, NULL, &key, &rec);as_record_destroy(&rec);Map<String, Object> prefs = new HashMap<>();prefs.put("theme", "dark");prefs.put("lang", "en");
// Default upsert behavior (RecordExistsAction.UPDATE)// WritePolicy wp = new WritePolicy();// wp.recordExistsAction = RecordExistsAction.UPDATE;// client.put(wp, key, ...);
client.put(null, key, new Bin("name", "Alice"), new Bin("visits", 1), new Bin("prefs", prefs));bins = { "name": "Alice", "visits": 1, "prefs": {"theme": "dark", "lang": "en"},}
# Default upsert behavior (POLICY_EXISTS_UPDATE)# policy = {"exists": aerospike.POLICY_EXISTS_UPDATE}# client.put(key, bins, policy=policy)
client.put(key, bins)Read a record
Use get to read the full record (metadata and all bins), or select specific bins.
Record record = session.query(key).execute().getFirstRecord();System.out.format("Record: %s%n", record.bins);record = session.query(key).first_or_raise().record_or_raise()print("Record:", record.bins)let record = client.get(&ReadPolicy::default(), &key, Bins::All).await?;println!("Record: {:?}", record.bins);Record rec = client.Get(null, key);Console.WriteLine("Record: {0}", rec);// Requires: import as "github.com/aerospike/aerospike-client-go/v8"record, err := client.Get(nil, key)if err != nil { log.Fatal(err)}fmt.Printf("Record: %v\n", record.Bins)let record = await client.get(key);console.info("Record:", record.bins);as_record *p_rec = NULL;aerospike_key_get(&as, &err, NULL, &key, &p_rec);
char *prefs_str = as_val_tostring(as_record_get(p_rec, "prefs"));printf("Record: name=%s visits=%lld prefs=%s\n", as_record_get_str(p_rec, "name"), (long long)as_record_get_int64(p_rec, "visits", 0), prefs_str);free(prefs_str);as_record_destroy(p_rec);Record record = client.get(null, key);System.out.format("Record: %s%n", record.bins);(key_, meta, bins) = client.get(key)print("Record:", bins)Merge-update bins with put
Use put again to change one or more bins. With default write policies, the server merges new bins into the existing record and leaves other bins unchanged (this is not a full replace of every bin unless you use a replace-style policy).
session.upsert(key).bin("name").setTo("Alice K.").execute();session.upsert(key).put({"name": "Alice K."}).execute()client.put(&WritePolicy::default(), &key, &[as_bin!("name", "Alice K.")]).await?;client.Put(null, key, new Bin("name", "Alice K."));// Requires: import as "github.com/aerospike/aerospike-client-go/v8"err = client.PutBins(nil, key, as.NewBin("name", "Alice K."))if err != nil { log.Fatal(err)}await client.put(key, { name: "Alice K." });as_record upd;as_record_inita(&upd, 1);as_record_set_str(&upd, "name", "Alice K.");aerospike_key_put(&as, &err, NULL, &key, &upd);as_record_destroy(&upd);client.put(null, key, new Bin("name", "Alice K."));client.put(key, {"name": "Alice K."})Atomic updates with operate
Use operate to execute multiple bin operations atomically in a single command.
The following example increments the visits counter, updates a value inside the
prefs map, and reads both bins — all in one round trip.
record = session.upsert(key) .bin("visits").add(1) .bin("prefs").onMapKey("lang").setTo("fr") .bin("visits").get() .bin("prefs").get() .execute() .getFirstRecord();
// Each bin holds a result per operation: the write's, then the read'sSystem.out.format("visits: %s, prefs: %s%n", record.getList("visits").get(1), record.getList("prefs").get(1));record = ( session.upsert(key) .bin("visits").add(1) .bin("prefs").on_map_key("lang").set_to("fr") .bin("visits").get() .bin("prefs").get() .execute() .first_or_raise() .record_or_raise())# prefs holds a result per operation: the map's size after the put, then the mapprint("visits:", record.bins["visits"], "prefs:", record.bins["prefs"][1])let ops = vec![ operations::add(&as_bin!("visits", 1)), maps::put(&MapPolicy::default(), "prefs", as_val!("lang"), as_val!("fr")), operations::get_bin("visits"), operations::get_bin("prefs"),];
let record = client.operate(&WritePolicy::default(), &key, &ops).await?;
// prefs holds a result per operation: the map's size after the put, then the mapif let Value::MultiResult(prefs) = &record.bins["prefs"] { println!("visits: {}, prefs: {}", record.bins["visits"], prefs[1]);}rec = client.Operate(null, key, Operation.Add(new Bin("visits", 1)), MapOperation.Put(MapPolicy.Default, "prefs", Value.Get("lang"), Value.Get("fr")), Operation.Get("visits"), Operation.Get("prefs"));
// Each bin holds a result per operation: the write's, then the read'sConsole.WriteLine("visits: {0}, prefs: {1}", rec.GetList("visits")[1], string.Join(", ", (IDictionary<object, object>)rec.GetList("prefs")[1]));// Requires: import as "github.com/aerospike/aerospike-client-go/v8"addVisits := as.NewBin("visits", 1)
record, err = client.Operate(nil, key, as.AddOp(addVisits), as.MapPutOp(as.DefaultMapPolicy(), "prefs", as.NewValue("lang"), as.NewValue("fr")), as.GetBinOp("visits"), as.GetBinOp("prefs"))if err != nil { log.Fatal(err)}
// Each bin holds a result per operation: the write's, then the read'sfmt.Printf("visits: %v, prefs: %v\n", record.Bins["visits"].(as.OpResults)[1], record.Bins["prefs"].(as.OpResults)[1])const ops = [ op.incr("visits", 1), maps.put("prefs", "lang", "fr"), op.read("visits"), op.read("prefs"),];
record = await client.operate(key, ops);console.info("visits:", record.bins.visits, "prefs:", record.bins.prefs);as_operations ops;as_operations_inita(&ops, 4);as_operations_add_incr(&ops, "visits", 1);
as_string lang_key;as_string_init(&lang_key, "lang", false);as_string lang_val;as_string_init(&lang_val, "fr", false);as_operations_map_put(&ops, "prefs", NULL, NULL, (as_val *)&lang_key, (as_val *)&lang_val);
as_operations_add_read(&ops, "visits");as_operations_add_read(&ops, "prefs");
as_record *op_rec = NULL;aerospike_key_operate(&as, &err, NULL, &key, &ops, &op_rec);
// The record holds a bin per operation, in order: visits (incr),// prefs (the put), then the reads of visits and prefs.char *op_prefs = as_val_tostring(op_rec->bins.entries[3].valuep);printf("visits: %lld, prefs: %s\n", (long long)op_rec->bins.entries[2].valuep->integer.value, op_prefs);free(op_prefs);as_operations_destroy(&ops);as_record_destroy(op_rec);record = client.operate(null, key, Operation.add(new Bin("visits", 1)), MapOperation.put(MapPolicy.Default, "prefs", Value.get("lang"), Value.get("fr")), Operation.get("visits"), Operation.get("prefs"));
// Each bin holds a result per operation: the write's, then the read'sSystem.out.format("visits: %s, prefs: %s%n", record.getList("visits").get(1), record.getList("prefs").get(1));ops = [ op.increment("visits", 1), mop.map_put("prefs", "lang", "fr"), op.read("visits"), op.read("prefs"),]
(key_, meta, bins) = client.operate(key, ops)print("visits:", bins["visits"], "prefs:", bins["prefs"])Touch a record
Use touch to increment the record’s generation counter and optionally reset its time-to-live (TTL).
session.touch(key).expireRecordAfterSeconds(300).execute(); // TTL in secondssession.touch(key).expire_record_after_seconds(300).execute() # TTL in secondslet mut touch_policy = WritePolicy::default();touch_policy.expiration = Expiration::Seconds(300); // TTL in seconds
client.touch(&touch_policy, &key).await?;WritePolicy touchPolicy = new WritePolicy();touchPolicy.expiration = 300; // TTL in seconds
client.Touch(touchPolicy, key);// Requires: import as "github.com/aerospike/aerospike-client-go/v8"touchPolicy := as.NewWritePolicy(0, 300) // generation, TTL in secondserr = client.Touch(touchPolicy, key)if err != nil { log.Fatal(err)}await client.operate(key, [op.touch(300)]); // TTL in secondsas_operations touch_ops;as_operations_inita(&touch_ops, 1);as_operations_add_touch(&touch_ops);touch_ops.ttl = 300; // TTL in seconds
as_record *touch_rec = NULL;aerospike_key_operate(&as, &err, NULL, &key, &touch_ops, &touch_rec);as_operations_destroy(&touch_ops);as_record_destroy(touch_rec);WritePolicy touchPolicy = new WritePolicy();touchPolicy.expiration = 300; // TTL in seconds
client.touch(touchPolicy, key);client.touch(key, 300) # TTL in secondsDelete a record
Use delete (or remove) to delete a record. Enable durableDelete in the write policy to write a tombstone that prevents the record from resurrecting on a cold restart. See Durable Deletes for details.
// Durable delete:// session.delete(key).withDurableDelete().execute();
session.delete(key).execute();# Durable delete:# session.delete(key).with_durable_delete().execute()
session.delete(key).execute()// Durable delete:// let mut delete_policy = WritePolicy::default();// delete_policy.durable_delete = true;// client.delete(&delete_policy, &key).await?;
let remove_policy = WritePolicy::default(); // default write policyclient.delete(&remove_policy, &key).await?;// Durable delete:// WritePolicy deletePolicy = new WritePolicy();// deletePolicy.durableDelete = true;// client.Delete(deletePolicy, key);
WritePolicy removePolicy = new WritePolicy(); // empty / defaultclient.Delete(removePolicy, key);// Requires: import as "github.com/aerospike/aerospike-client-go/v8"// Durable delete:// deletePolicy := as.NewWritePolicy(0, 0)// deletePolicy.DurableDelete = true// _, err = client.Delete(deletePolicy, key)
removePolicy := as.NewWritePolicy(0, 0) // empty write policy_, err = client.Delete(removePolicy, key)if err != nil { log.Fatal(err)}// Durable delete:// const deletePolicy = new Aerospike.WritePolicy({ durableDelete: true });// await client.remove(key, deletePolicy);
const removePolicy = new Aerospike.WritePolicy(); // empty write policyawait client.remove(key, removePolicy);// Durable delete:// as_policy_remove deletePolicy;// as_policy_remove_init(&deletePolicy);// deletePolicy.durable_delete = true;// aerospike_key_remove(&as, &err, &deletePolicy, &key);
as_policy_remove removePolicy;as_policy_remove_init(&removePolicy);aerospike_key_remove(&as, &err, &removePolicy, &key);// Durable delete:// WritePolicy deletePolicy = new WritePolicy();// deletePolicy.durableDelete = true;// client.delete(deletePolicy, key);
WritePolicy removePolicy = new WritePolicy(); // empty / defaultclient.delete(removePolicy, key);# Durable delete:# durable_policy = {"durable_delete": True}# client.remove(key, policy=durable_policy)
remove_policy = {} # empty write policyclient.remove(key, policy=remove_policy)Usage note for all examples
All full record read and write commands accept policy parameters: Max Retries and Total Timeout.
Write operations take an optional time-to-live (TTL) parameter that sets when the record expires. Set the TTL to -1 so the record never expires.
Code block
Expand for the full single-record operations example
import com.aerospike.client.sdk.Cluster;import com.aerospike.client.sdk.ClusterDefinition;import com.aerospike.client.sdk.DataSet;import com.aerospike.client.sdk.Key;import com.aerospike.client.sdk.Record;import com.aerospike.client.sdk.Session;import com.aerospike.client.sdk.policy.Behavior;import java.util.HashMap;import java.util.Map;
public class SingleExample { public static void main(String[] args) { // Connect try (Cluster cluster = new ClusterDefinition("127.0.0.1", 3000).connect()) { Session session = cluster.createSession(Behavior.DEFAULT);
Key key = DataSet.of("test", "demo").id("user1");
// Upsert Map<String, Object> prefs = new HashMap<>(); prefs.put("theme", "dark"); prefs.put("lang", "en");
// upsert creates the record or merges bins into it; // insert, update and replace are the other write verbs. session.upsert(key) .bin("name").setTo("Alice") .bin("visits").setTo(1) .bin("prefs").setTo(prefs) .execute();
// Read Record record = session.query(key).execute().getFirstRecord(); System.out.format("Record: %s%n", record.bins);
// Merge-update (put) session.upsert(key).bin("name").setTo("Alice K.").execute();
// Update (operate) record = session.upsert(key) .bin("visits").add(1) .bin("prefs").onMapKey("lang").setTo("fr") .bin("visits").get() .bin("prefs").get() .execute() .getFirstRecord();
// Each bin holds a result per operation: the write's, then the read's System.out.format("visits: %s, prefs: %s%n", record.getList("visits").get(1), record.getList("prefs").get(1));
// Touch session.touch(key).expireRecordAfterSeconds(300).execute(); // TTL in seconds
// Delete // Durable delete: // session.delete(key).withDurableDelete().execute();
session.delete(key).execute(); } }}from aerospike_sdk import Behavior, DataSetfrom aerospike_sdk.sync import ClusterDefinition
# Connectwith ClusterDefinition("127.0.0.1", 3000).connect() as cluster: session = cluster.create_session(Behavior.DEFAULT)
key = DataSet.of("test", "demo").id("user1")
# Upsert bins = { "name": "Alice", "visits": 1, "prefs": {"theme": "dark", "lang": "en"}, }
# upsert creates the record or merges bins into it; # insert, update and replace are the other write verbs. session.upsert(key).put(bins).execute()
# Read record = session.query(key).first_or_raise().record_or_raise() print("Record:", record.bins)
# Merge-update (put) session.upsert(key).put({"name": "Alice K."}).execute()
# Update (operate) record = ( session.upsert(key) .bin("visits").add(1) .bin("prefs").on_map_key("lang").set_to("fr") .bin("visits").get() .bin("prefs").get() .execute() .first_or_raise() .record_or_raise() ) # prefs holds a result per operation: the map's size after the put, then the map print("visits:", record.bins["visits"], "prefs:", record.bins["prefs"][1])
# Touch session.touch(key).expire_record_after_seconds(300).execute() # TTL in seconds
# Delete # Durable delete: # session.delete(key).with_durable_delete().execute()
session.delete(key).execute()use aerospike::{ as_bin, as_key, as_map, as_val, operations, operations::maps, Bins, Client, ClientPolicy, Expiration, MapPolicy, ReadPolicy, Value, WritePolicy,};
#[tokio::main]async fn main() -> aerospike::Result<()> { // Connect let client = Client::new(&ClientPolicy::default(), &"127.0.0.1:3000").await?;
let key = as_key!("test", "demo", "user1");
// Upsert let bins = [ as_bin!("name", "Alice"), as_bin!("visits", 1), as_bin!("prefs", as_map!("theme" => "dark", "lang" => "en")), ];
// Default upsert behavior (RecordExistsAction::Update) // let mut wp = WritePolicy::default(); // wp.record_exists_action = RecordExistsAction::Update; // client.put(&wp, &key, &bins).await?;
client.put(&WritePolicy::default(), &key, &bins).await?;
// Read let record = client.get(&ReadPolicy::default(), &key, Bins::All).await?; println!("Record: {:?}", record.bins);
// Merge-update (put) client.put(&WritePolicy::default(), &key, &[as_bin!("name", "Alice K.")]).await?;
// Update (operate) let ops = vec![ operations::add(&as_bin!("visits", 1)), maps::put(&MapPolicy::default(), "prefs", as_val!("lang"), as_val!("fr")), operations::get_bin("visits"), operations::get_bin("prefs"), ];
let record = client.operate(&WritePolicy::default(), &key, &ops).await?;
// prefs holds a result per operation: the map's size after the put, then the map if let Value::MultiResult(prefs) = &record.bins["prefs"] { println!("visits: {}, prefs: {}", record.bins["visits"], prefs[1]); }
// Touch let mut touch_policy = WritePolicy::default(); touch_policy.expiration = Expiration::Seconds(300); // TTL in seconds
client.touch(&touch_policy, &key).await?;
// Delete // Durable delete: // let mut delete_policy = WritePolicy::default(); // delete_policy.durable_delete = true; // client.delete(&delete_policy, &key).await?;
let remove_policy = WritePolicy::default(); // default write policy client.delete(&remove_policy, &key).await?;
client.close().await?; Ok(())}using Aerospike.Client;using System.Collections.Generic;
// ConnectAerospikeClient client = new AerospikeClient("127.0.0.1", 3000);
Key key = new Key("test", "demo", "user1");
// Upsertvar prefs = new Dictionary<string, object> { { "theme", "dark" }, { "lang", "en" }};
// Default upsert behavior (RecordExistsAction.UPDATE)// WritePolicy wp = new WritePolicy();// wp.recordExistsAction = RecordExistsAction.UPDATE;// client.Put(wp, key, ...);
client.Put(null, key, new Bin("name", "Alice"), new Bin("visits", 1), new Bin("prefs", prefs));
// ReadRecord rec = client.Get(null, key);Console.WriteLine("Record: {0}", rec);
// Merge-update (put)client.Put(null, key, new Bin("name", "Alice K."));
// Update (operate)rec = client.Operate(null, key, Operation.Add(new Bin("visits", 1)), MapOperation.Put(MapPolicy.Default, "prefs", Value.Get("lang"), Value.Get("fr")), Operation.Get("visits"), Operation.Get("prefs"));
// Each bin holds a result per operation: the write's, then the read'sConsole.WriteLine("visits: {0}, prefs: {1}", rec.GetList("visits")[1], string.Join(", ", (IDictionary<object, object>)rec.GetList("prefs")[1]));
// TouchWritePolicy touchPolicy = new WritePolicy();touchPolicy.expiration = 300; // TTL in seconds
client.Touch(touchPolicy, key);
// Delete// Durable delete:// WritePolicy deletePolicy = new WritePolicy();// deletePolicy.durableDelete = true;// client.Delete(deletePolicy, key);
WritePolicy removePolicy = new WritePolicy(); // empty / defaultclient.Delete(removePolicy, key);
client.Close();package main
import ( "fmt" "log"
as "github.com/aerospike/aerospike-client-go/v8")
func main() { // Connect client, err := as.NewClient("127.0.0.1", 3000) if err != nil { log.Fatal(err) } defer client.Close()
key, _ := as.NewKey("test", "demo", "user1")
// Upsert prefs := map[interface{}]interface{}{ "theme": "dark", "lang": "en", }
// Default upsert behavior (as.UPDATE) // wp := as.NewWritePolicy(0, 0) // wp.RecordExistsAction = as.UPDATE // err = client.PutBins(wp, key, ...)
err = client.PutBins(nil, key, as.NewBin("name", "Alice"), as.NewBin("visits", 1), as.NewBin("prefs", prefs)) if err != nil { log.Fatal(err) }
// Read record, err := client.Get(nil, key) if err != nil { log.Fatal(err) } fmt.Printf("Record: %v\n", record.Bins)
// Merge-update (put) err = client.PutBins(nil, key, as.NewBin("name", "Alice K.")) if err != nil { log.Fatal(err) }
// Update (operate) addVisits := as.NewBin("visits", 1)
record, err = client.Operate(nil, key, as.AddOp(addVisits), as.MapPutOp(as.DefaultMapPolicy(), "prefs", as.NewValue("lang"), as.NewValue("fr")), as.GetBinOp("visits"), as.GetBinOp("prefs")) if err != nil { log.Fatal(err) }
// Each bin holds a result per operation: the write's, then the read's fmt.Printf("visits: %v, prefs: %v\n", record.Bins["visits"].(as.OpResults)[1], record.Bins["prefs"].(as.OpResults)[1])
// Touch touchPolicy := as.NewWritePolicy(0, 300) // generation, TTL in seconds err = client.Touch(touchPolicy, key) if err != nil { log.Fatal(err) }
// Delete // Durable delete: // deletePolicy := as.NewWritePolicy(0, 0) // deletePolicy.DurableDelete = true // _, err = client.Delete(deletePolicy, key)
removePolicy := as.NewWritePolicy(0, 0) // empty write policy _, err = client.Delete(removePolicy, key) if err != nil { log.Fatal(err) }}const Aerospike = await import("aerospike");const op = Aerospike.operations;const maps = Aerospike.maps;
// Connectconst client = await Aerospike.connect({ hosts: "127.0.0.1:3000" });
const key = new Aerospike.Key("test", "demo", "user1");
// Upsertconst bins = { name: "Alice", visits: 1, prefs: { theme: "dark", lang: "en" },};
// Default upsert behavior (Aerospike.policy.exists.UPDATE)// const wp = new Aerospike.WritePolicy({// exists: Aerospike.policy.exists.UPDATE,// });// await client.put(key, bins, {}, wp);
await client.put(key, bins);
// Readlet record = await client.get(key);console.info("Record:", record.bins);
// Merge-update (put)await client.put(key, { name: "Alice K." });
// Update (operate)const ops = [ op.incr("visits", 1), maps.put("prefs", "lang", "fr"), op.read("visits"), op.read("prefs"),];
record = await client.operate(key, ops);console.info("visits:", record.bins.visits, "prefs:", record.bins.prefs);
// Touchawait client.operate(key, [op.touch(300)]); // TTL in seconds
// Delete// Durable delete:// const deletePolicy = new Aerospike.WritePolicy({ durableDelete: true });// await client.remove(key, deletePolicy);
const removePolicy = new Aerospike.WritePolicy(); // empty write policyawait client.remove(key, removePolicy);
await client.close();#include <stdio.h>#include <stdlib.h>#include <aerospike/aerospike.h>#include <aerospike/aerospike_key.h>#include <aerospike/as_hashmap.h>#include <aerospike/as_map_operations.h>#include <aerospike/as_operations.h>#include <aerospike/as_policy.h>#include <aerospike/as_record.h>#include <aerospike/as_stringmap.h>
int main() { // Connect 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; aerospike_connect(&as, &err);
as_key key; as_key_init_str(&key, "test", "demo", "user1");
// Upsert as_hashmap prefs; as_hashmap_init(&prefs, 2); as_stringmap_set_str((as_map *)&prefs, "theme", "dark"); as_stringmap_set_str((as_map *)&prefs, "lang", "en");
as_record rec; as_record_inita(&rec, 3); as_record_set_str(&rec, "name", "Alice"); as_record_set_int64(&rec, "visits", 1); as_record_set_map(&rec, "prefs", (as_map *)&prefs);
// Default upsert behavior (AS_POLICY_EXISTS_UPDATE) // as_policy_write wp; // as_policy_write_init(&wp); // wp.exists = AS_POLICY_EXISTS_UPDATE; // aerospike_key_put(&as, &err, &wp, &key, &rec);
aerospike_key_put(&as, &err, NULL, &key, &rec); as_record_destroy(&rec);
// Read as_record *p_rec = NULL; aerospike_key_get(&as, &err, NULL, &key, &p_rec);
char *prefs_str = as_val_tostring(as_record_get(p_rec, "prefs")); printf("Record: name=%s visits=%lld prefs=%s\n", as_record_get_str(p_rec, "name"), (long long)as_record_get_int64(p_rec, "visits", 0), prefs_str); free(prefs_str); as_record_destroy(p_rec);
// Merge-update (put) as_record upd; as_record_inita(&upd, 1); as_record_set_str(&upd, "name", "Alice K."); aerospike_key_put(&as, &err, NULL, &key, &upd); as_record_destroy(&upd);
// Update (operate) as_operations ops; as_operations_inita(&ops, 4); as_operations_add_incr(&ops, "visits", 1);
as_string lang_key; as_string_init(&lang_key, "lang", false); as_string lang_val; as_string_init(&lang_val, "fr", false); as_operations_map_put(&ops, "prefs", NULL, NULL, (as_val *)&lang_key, (as_val *)&lang_val);
as_operations_add_read(&ops, "visits"); as_operations_add_read(&ops, "prefs");
as_record *op_rec = NULL; aerospike_key_operate(&as, &err, NULL, &key, &ops, &op_rec);
// The record holds a bin per operation, in order: visits (incr), // prefs (the put), then the reads of visits and prefs. char *op_prefs = as_val_tostring(op_rec->bins.entries[3].valuep); printf("visits: %lld, prefs: %s\n", (long long)op_rec->bins.entries[2].valuep->integer.value, op_prefs); free(op_prefs); as_operations_destroy(&ops); as_record_destroy(op_rec);
// Touch as_operations touch_ops; as_operations_inita(&touch_ops, 1); as_operations_add_touch(&touch_ops); touch_ops.ttl = 300; // TTL in seconds
as_record *touch_rec = NULL; aerospike_key_operate(&as, &err, NULL, &key, &touch_ops, &touch_rec); as_operations_destroy(&touch_ops); as_record_destroy(touch_rec);
// Delete // Durable delete: // as_policy_remove deletePolicy; // as_policy_remove_init(&deletePolicy); // deletePolicy.durable_delete = true; // aerospike_key_remove(&as, &err, &deletePolicy, &key);
as_policy_remove removePolicy; as_policy_remove_init(&removePolicy); aerospike_key_remove(&as, &err, &removePolicy, &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.Operation;import com.aerospike.client.Record;import com.aerospike.client.Value;import com.aerospike.client.cdt.MapOperation;import com.aerospike.client.cdt.MapPolicy;import com.aerospike.client.policy.WritePolicy;import java.util.HashMap;import java.util.Map;
public class SingleExample { public static void main(String[] args) { // Connect AerospikeClient client = new AerospikeClient("127.0.0.1", 3000);
Key key = new Key("test", "demo", "user1");
// Upsert Map<String, Object> prefs = new HashMap<>(); prefs.put("theme", "dark"); prefs.put("lang", "en");
// Default upsert behavior (RecordExistsAction.UPDATE) // WritePolicy wp = new WritePolicy(); // wp.recordExistsAction = RecordExistsAction.UPDATE; // client.put(wp, key, ...);
client.put(null, key, new Bin("name", "Alice"), new Bin("visits", 1), new Bin("prefs", prefs));
// Read Record record = client.get(null, key); System.out.format("Record: %s%n", record.bins);
// Merge-update (put) client.put(null, key, new Bin("name", "Alice K."));
// Update (operate) record = client.operate(null, key, Operation.add(new Bin("visits", 1)), MapOperation.put(MapPolicy.Default, "prefs", Value.get("lang"), Value.get("fr")), Operation.get("visits"), Operation.get("prefs"));
// Each bin holds a result per operation: the write's, then the read's System.out.format("visits: %s, prefs: %s%n", record.getList("visits").get(1), record.getList("prefs").get(1));
// Touch WritePolicy touchPolicy = new WritePolicy(); touchPolicy.expiration = 300; // TTL in seconds
client.touch(touchPolicy, key);
// Delete // Durable delete: // WritePolicy deletePolicy = new WritePolicy(); // deletePolicy.durableDelete = true; // client.delete(deletePolicy, key);
WritePolicy removePolicy = new WritePolicy(); // empty / default client.delete(removePolicy, key);
client.close(); }}import aerospikefrom aerospike_helpers.operations import operations as opfrom aerospike_helpers.operations import map_operations as mop
# Connectconfig = {"hosts": [("127.0.0.1", 3000)]}client = aerospike.client(config).connect()
key = ("test", "demo", "user1")
# Upsertbins = { "name": "Alice", "visits": 1, "prefs": {"theme": "dark", "lang": "en"},}
# Default upsert behavior (POLICY_EXISTS_UPDATE)# policy = {"exists": aerospike.POLICY_EXISTS_UPDATE}# client.put(key, bins, policy=policy)
client.put(key, bins)
# Read(key_, meta, bins) = client.get(key)print("Record:", bins)
# Merge-update (put)client.put(key, {"name": "Alice K."})
# Update (operate)ops = [ op.increment("visits", 1), mop.map_put("prefs", "lang", "fr"), op.read("visits"), op.read("prefs"),]
(key_, meta, bins) = client.operate(key, ops)print("visits:", bins["visits"], "prefs:", bins["prefs"])
# Touchclient.touch(key, 300) # TTL in seconds
# Delete# Durable delete:# durable_policy = {"durable_delete": True}# client.remove(key, policy=durable_policy)
remove_policy = {} # empty write policyclient.remove(key, policy=remove_policy)
client.close()References
See these topics for language-specific examples: