Skip to content

Introduction to transactions

For the complete documentation index see: llms.txt

All documentation pages available in markdown.

In this tutorial, you will perform multiple operations on a single record—first as separate commands, and then combined into one.

Because the database executes every command on a record atomically, combining operations guarantees they run as a single, all-or-nothing transaction, preventing other commands from ever seeing a partial result.

Select your preferred language in any tab group below—your choice will automatically apply across the entire page.

The Java SDK and Python SDK tabs use the Aerospike Developer SDKs. In the SDKs, you chain operations on one upsert or query command. The Java and Python tabs use the legacy clients, which take a list of operations in an operate command. The Rust, C#, Go, Node.js, and C tabs also use operate.

This tutorial covers:

  • Record commands: get, get header, and touch.
  • Operations on simple data types: String, Integer, and Double.
  • Operations on collection data types (List and Map), and on Blob, HyperLogLog, and GeoJSON.
  • A command that combines the operations in one atomic command.
  • A Map write policy for conditional writes.

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 java.util.HexFormat;
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.HllConfig;
import com.aerospike.client.sdk.Key;
import com.aerospike.client.sdk.Record;
import com.aerospike.client.sdk.Session;
import com.aerospike.client.sdk.Value;
import com.aerospike.client.sdk.policy.Behavior;

Connect 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.

Write the records

Write the same record to two keys, txnkey and txnkey2, in the txnset set. The record has a bin for each of these data types: String, Integer, Double, Blob, GeoJSON, List, and Map. The tutorial updates the first record one operation at a time, and then updates the second record with all the operations in one command.

The GeoJSON bin holds a polygon. The record has no HyperLogLog bin yet, because the first HyperLogLog operation creates it.

The tutorial ends by deleting the two records, so you can run it again.

DataSet dataSet = DataSet.of("test", "txnset");
Key key = dataSet.id("txnkey");
Key key2 = dataSet.id("txnkey2");
String geo = "{\"type\": \"Polygon\", \"coordinates\": [[[-122.5, 37.0], [-121.0, 37.0], [-121.0, 38.0], [-122.5, 38.0], [-122.5, 37.0]]]}";
for (Key k : List.of(key, key2)) {
session.upsert(k)
.bin("str").setTo("atomic")
.bin("int").setTo(8)
.bin("double").setTo(6.5)
.bin("blob").setTo(new byte[] {1, 2, 3, 4, 5})
.bin("geo").setTo(Value.getAsGeoJSON(geo))
.bin("list").setTo(List.of(1))
.bin("map").setTo(Map.of(2, 4))
.execute();
}

Read the record

Read the first record and print its String, Integer, and Double bins and its generation. The generation is a counter that the database increments each time the record is written. The record has generation 1 because you wrote it once.

Record record = session.query(key).execute().getFirstRecord();
System.out.println("str: " + record.getString("str"));
System.out.println("int: " + record.getLong("int"));
System.out.println("double: " + record.getDouble("double"));
System.out.println("Generation: " + record.generation);
str: atomic
int: 8
double: 6.5
Generation: 1
Output

Read the record header and touch the record

A header read returns a record’s metadata, including its generation, without its bins. A touch increments the record’s generation without changing its bins. Read the header, touch the record, and read the header again.

Record header = session.query(key).withNoBins().execute().getFirstRecord();
System.out.println("Generation: " + header.generation);
session.touch(key).execute();
header = session.query(key).withNoBins().execute().getFirstRecord();
System.out.println("Generation: " + header.generation);
Generation: 1
Generation: 2
Output

Update String, Integer, and Double bins

Run three commands, each with one operation. Append -operation to the String. Add 5 to the Integer. Add -2.25 to the Double. Then read the record to see the new values.

session.upsert(key).bin("str").append("-operation").execute();
session.upsert(key).bin("int").add(5).execute();
session.upsert(key).bin("double").add(-2.25).execute();
record = session.query(key).execute().getFirstRecord();
System.out.println("str: " + record.getString("str"));
System.out.println("int: " + record.getLong("int"));
System.out.println("double: " + record.getDouble("double"));
str: atomic-operation
int: 13
double: 4.25
Output

Update a List

Append 5 to the List. A List operation returns a result, and append returns the new size of the List. The List changes from [1] to [1, 5], so the size is 2.

Record result = session.upsert(key).bin("list").listAppend(5).execute().getFirstRecord();
System.out.println("List size: " + result.getLong("list"));
List size: 2
Output

For more about Lists, see the Reading and updating lists tutorial.

Update a Map

Add 57 to the value of Map key 2. A Map increment operation returns the new value. The Map changes from {2: 4} to {2: 61}.

result = session.upsert(key).bin("map").onMapKey(2).add(57).execute().getFirstRecord();
System.out.println("Map value: " + result.getLong("map"));
Map value: 61
Output

For more about Maps, see the Reading and updating maps tutorial.

Update a Blob

Bit operations change the bits of a Blob. Set 8 bits, starting at bit offset 13, to the value 0xE0. The blob changes from the bytes 01 02 03 04 05 to 01 07 03 04 05. Then read the Blob and print it as hexadecimal.

session.upsert(key).bin("blob").bitSet(13, 8, new byte[] {(byte) 0xE0}).execute();
record = session.query(key).bin("blob").get().execute().getFirstRecord();
System.out.println("Blob: " + HexFormat.of().formatHex(record.getBytes("blob")));
Blob: 0107030405
Output

Update a HyperLogLog

A HyperLogLog is a probabilistic data type that estimates the number of distinct values in a large set. The record doesn’t have a HyperLogLog bin yet, so this command initializes the bin with 8 index bits and adds three values to it. The two operations run as one command. Then read the estimated count.

session.upsert(key)
.bin("hll").hllInit(HllConfig.of(8))
.bin("hll").hllAdd(List.of("a", "b", "c"), HllConfig.of(8))
.execute();
record = session.query(key).bin("hll").hllGetCount().execute().getFirstRecord();
System.out.println("HLL count: " + record.getLong("hll"));
HLL count: 3
Output

Read the GeoJSON value

The database stores GeoJSON as its own data type, validates it, and can run geospatial queries on it. For this tutorial, read the GeoJSON bin and print it. To learn about geospatial indexes and queries, see Geospatial.

record = session.query(key).bin("geo").get().execute().getFirstRecord();
System.out.println("Geo: " + record.getGeoJSONString("geo"));
Geo: {"type": "Polygon", "coordinates": [[[-122.5, 37.0], [-121.0, 37.0], [-121.0, 38.0], [-122.5, 38.0], [-122.5, 37.0]]]}
Output

Run the operations as one command

The previous commands each ran one operation. Operations on one record can also run together in one command. The database runs the whole command atomically, so no other command sees the record with only some of the operations applied. The command also increments the generation once, however many operations it contains.

Run all the earlier updates on the second record as one command:

  1. Touch the record.
  2. Append to the String.
  3. Add to the Integer.
  4. Add to the Double.
  5. Append to the List.
  6. Increment the Map value.
  7. Set the bits in the Blob.
  8. Initialize the HyperLogLog and add values to it.

Then read the results with a second command that has one read operation for each bin you want. The second record’s generation is 2: one write for the put, and one for the whole command. The first record’s generation is 9: one write for the put, one for the touch, and one for each of the seven earlier single-operation commands.

session.upsert(key2)
.touchRecord()
.bin("str").append("-operation")
.bin("int").add(5)
.bin("double").add(-2.25)
.bin("list").listAppend(5)
.bin("map").onMapKey(2).add(57)
.bin("blob").bitSet(13, 8, new byte[] {(byte) 0xE0})
.bin("hll").hllInit(HllConfig.of(8))
.bin("hll").hllAdd(List.of("a", "b", "c"), HllConfig.of(8))
.execute();
Record after = session.query(key2)
.bin("str").get()
.bin("int").get()
.bin("double").get()
.bin("blob").get()
.bin("list").listSize()
.bin("map").onMapKey(2).getValues()
.bin("hll").hllGetCount()
.execute().getFirstRecord();
System.out.println("str: " + after.getString("str"));
System.out.println("int: " + after.getLong("int"));
System.out.println("double: " + after.getDouble("double"));
System.out.println("Blob: " + HexFormat.of().formatHex(after.getBytes("blob")));
System.out.println("List size: " + after.getLong("list"));
System.out.println("Map value: " + after.getLong("map"));
System.out.println("HLL count: " + after.getLong("hll"));
System.out.println("Generation: " + after.generation);
Record first = session.query(key).withNoBins().execute().getFirstRecord();
System.out.println("Generation of the first record: " + first.generation);

In the Java SDK, session.upsert(key2) starts one command, and each .bin(...) call adds an operation to it. The command runs when you call execute().

str: atomic-operation
int: 13
double: 4.25
Blob: 0107030405
List size: 2
Map value: 61
HLL count: 3
Generation: 2
Generation of the first record: 9
Output

Control writes with a Map write policy

Use a write policy to run conditional logic without reading the record first. A map operation can take write flags that say what to do when a key does or doesn’t exist:

  • CREATE_ONLY writes the item only if the key doesn’t exist.
  • NO_FAIL doesn’t return an error when the database denies a write. Without it, a denied write fails the command.
  • PARTIAL lets the other items in a multi-item operation succeed when the database denies one. It takes effect only together with NO_FAIL.

Maps, Lists, Blobs, and HyperLogLogs each have their own write flags. By default, a Map write creates the key or updates its value.

Put key 2 in the Map with a value of 1, but only if key 2 doesn’t exist. The example passes NO_FAIL, so the denied write doesn’t return an error. The Map already has key 2, so the database denies the write and the value stays at 61.

session.upsert(key).bin("map").mapInsertItems(Map.of(2, 1), o -> o.allowFailures().allowPartial()).execute();
record = session.query(key).bin("map").onMapKey(2).getValues().execute().getFirstRecord();
System.out.println("Map value: " + record.getLong("map"));

In the Java SDK, the Map operation’s options set the write flags. allowFailures() is the NO_FAIL flag, and allowPartial() is the PARTIAL flag. The mapInsertItems operation doesn’t overwrite an existing key, so it already behaves as CREATE_ONLY.

Map value: 61
Output

For other conditional logic, check the data in your application and write only if the record’s generation hasn’t changed since you read it. This pattern is read-modify-write. See the Read-write transactions tutorial, or the transactions blog post. For logic that runs in the database, use record UDFs.

Delete the records and close the connection

Delete the two records to remove the tutorial’s data, and then close the client.

To remove every record in a set with one command, you can truncate the set instead. A truncate removes the records that were last updated before the database receives the command. A record written at about the same moment can survive, so this tutorial deletes the records. A truncate permanently removes the records in the set, so use it only on data that you don’t need.

session.delete(key).execute();
session.delete(key2).execute();
cluster.close();

Complete program

This program combines the steps. It writes one record, updates and reads it with two commands, and deletes the record.

import java.util.HexFormat;
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.HllConfig;
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 IntroToTransactions {
public static void main(String[] args) {
try (Cluster cluster = new ClusterDefinition("127.0.0.1", 3000).connect()) {
Session session = cluster.createSession(Behavior.DEFAULT);
DataSet dataSet = DataSet.of("test", "txnset");
Key key = dataSet.id("txnkey");
session.upsert(key)
.bin("str").setTo("atomic")
.bin("int").setTo(8)
.bin("double").setTo(6.5)
.bin("blob").setTo(new byte[] {1, 2, 3, 4, 5})
.bin("list").setTo(List.of(1))
.bin("map").setTo(Map.of(2, 4))
.execute();
session.upsert(key)
.touchRecord()
.bin("str").append("-operation")
.bin("int").add(5)
.bin("double").add(-2.25)
.bin("list").listAppend(5)
.bin("map").onMapKey(2).add(57)
.bin("blob").bitSet(13, 8, new byte[] {(byte) 0xE0})
.bin("hll").hllInit(HllConfig.of(8))
.bin("hll").hllAdd(List.of("a", "b", "c"), HllConfig.of(8))
.execute();
Record after = session.query(key)
.bin("str").get()
.bin("int").get()
.bin("double").get()
.bin("blob").get()
.bin("list").listSize()
.bin("map").onMapKey(2).getValues()
.bin("hll").hllGetCount()
.execute().getFirstRecord();
System.out.println("str: " + after.getString("str"));
System.out.println("int: " + after.getLong("int"));
System.out.println("double: " + after.getDouble("double"));
System.out.println("Blob: " + HexFormat.of().formatHex(after.getBytes("blob")));
System.out.println("List size: " + after.getLong("list"));
System.out.println("Map value: " + after.getLong("map"));
System.out.println("HLL count: " + after.getLong("hll"));
System.out.println("Generation: " + after.generation);
session.delete(key).execute();
}
}
}
str: atomic-operation
int: 13
double: 4.25
Blob: 0107030405
List size: 2
Map value: 61
HLL count: 3
Generation: 2
Output

What you learned

  • You ran operations on a record one at a time.
  • You ran them together as one atomic command.
  • You used a map write policy for a conditional write.

Next steps