---
title: "Introduction to transactions"
description: "Run several operations on one Aerospike record as a single atomic command with the Java and Python Developer SDKs or the Rust, C#, Go, Node.js, C, Java, or Python client."
---

# Introduction to transactions

> For the complete documentation index see: [llms.txt](https://aerospike.com/docs/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.

::: note
**A note on terminology:**

-   An **operation** is a discrete action on the contents of a [bin](https://aerospike.com/docs/database/learn/architecture/data-storage/data-model). Create, read, update, and delete actions using the `operate` API method are operations.
    
-   A **command** consists of one or more operations and affects one or more [records](https://aerospike.com/docs/database/learn/architecture/data-storage/data-model).
    
-   A **transaction** is made up of one or more commands, which occur in a guaranteed order and must all complete for the transaction to be successful.
:::

The **Java SDK** and **Python SDK** tabs use the [Aerospike Developer SDKs](https://aerospike.com/docs/develop/client/sdk). 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](https://aerospike.com/docs/develop/client-matrix). To set up a database, see the [Quickstart](https://aerospike.com/docs/database/quick-start).
-   Your client installed. To install it, follow the [Install the client](https://aerospike.com/docs/develop/tutorials/intro/hello-world/#install-the-client) step of the Hello, World! tutorial.

::: caution
The programs in this tutorial write, change, and delete records in the `test` namespace and use no authentication or TLS. Run them against a local development database that holds no data you need.
:::

## Import the client modules

-   [Java SDK](#tab-panel-6738)
-   [Python SDK](#tab-panel-6739)
-   [Rust](#tab-panel-6740)
-   [C#](#tab-panel-6741)
-   [Go](#tab-panel-6742)
-   [Node.js](#tab-panel-6743)
-   [C](#tab-panel-6744)
-   [Java](#tab-panel-6745)
-   [Python](#tab-panel-6746)

```java
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;
```

```python
from aerospike_native import GeoJSON

from aerospike_sdk import Behavior, DataSet, HllConfig

from aerospike_sdk.sync import ClusterDefinition
```

`aerospike_native` is the native package that the Python SDK depends on. The SDK takes GeoJSON values from it.

```rust
use aerospike::operations::bitwise::{self, BitPolicy};

use aerospike::operations::hll::{self, HllPolicy};

use aerospike::operations::maps::{self, MapOrder, MapPolicy, MapReturnType, MapWriteFlags};

use aerospike::operations::string::{self, StringPolicy};

use aerospike::operations::{lists, scalar, ListPolicy};

use aerospike::{as_bin, as_geo, as_key, as_list, as_map, as_val, Bins, Client, ClientPolicy, ReadPolicy, Value, WritePolicy};
```

```csharp
using System;

using System.Collections.Generic;

using Aerospike.Client;
```

```go
import (

  "fmt"

  "log"

  "github.com/aerospike/aerospike-client-go/v8"

)
```

```js
import Aerospike from 'aerospike';

const { operations: op, strings, lists, maps, bitwise, hll } = Aerospike;
```

```c
#include <stdio.h>

#include <aerospike/aerospike.h>

#include <aerospike/aerospike_key.h>

#include <aerospike/as_arraylist.h>

#include <aerospike/as_bit_operations.h>

#include <aerospike/as_bytes.h>

#include <aerospike/as_error.h>

#include <aerospike/as_geojson.h>

#include <aerospike/as_hashmap.h>

#include <aerospike/as_hll_operations.h>

#include <aerospike/as_integer.h>

#include <aerospike/as_key.h>

#include <aerospike/as_list_operations.h>

#include <aerospike/as_map_operations.h>

#include <aerospike/as_operations.h>

#include <aerospike/as_record.h>

#include <aerospike/as_string_operations.h>
```

```java
import java.util.HexFormat;

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.Value;

import com.aerospike.client.cdt.ListOperation;

import com.aerospike.client.cdt.MapOperation;

import com.aerospike.client.cdt.MapOrder;

import com.aerospike.client.cdt.MapPolicy;

import com.aerospike.client.cdt.MapReturnType;

import com.aerospike.client.cdt.MapWriteFlags;

import com.aerospike.client.operation.BitOperation;

import com.aerospike.client.operation.BitPolicy;

import com.aerospike.client.operation.HLLOperation;

import com.aerospike.client.operation.HLLPolicy;

import com.aerospike.client.operation.StringOperation;

import com.aerospike.client.operation.StringPolicy;
```

```python
import aerospike

from aerospike_helpers.operations import bitwise_operations, hll_operations, list_operations, map_operations, operations, string_operations
```

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

-   [Java SDK](#tab-panel-6747)
-   [Python SDK](#tab-panel-6748)
-   [Rust](#tab-panel-6749)
-   [C#](#tab-panel-6750)
-   [Go](#tab-panel-6751)
-   [Node.js](#tab-panel-6752)
-   [C](#tab-panel-6753)
-   [Java](#tab-panel-6754)
-   [Python](#tab-panel-6755)

```java
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.

```python
cluster = ClusterDefinition("127.0.0.1", 3000).connect()

session = cluster.create_session(Behavior.DEFAULT)
```

The session applies a `Behavior`, which sets the timeouts and retries for each command. `Behavior.DEFAULT` is a reasonable starting point.

```rust
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.

```csharp
AerospikeClient client = new AerospikeClient("127.0.0.1", 3000);
```

```go
client, err := aerospike.NewClient("127.0.0.1", 3000)

if err != nil {

  log.Fatal(err)

}
```

```js
const client = await Aerospike.connect({ hosts: '127.0.0.1:3000' });
```

```c
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;

}
```

```java
AerospikeClient client = new AerospikeClient("127.0.0.1", 3000);
```

```python
config = {"hosts": [("127.0.0.1", 3000)]}

client = aerospike.client(config).connect()
```

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

-   [Java SDK](#tab-panel-6756)
-   [Python SDK](#tab-panel-6757)
-   [Rust](#tab-panel-6758)
-   [C#](#tab-panel-6759)
-   [Go](#tab-panel-6760)
-   [Node.js](#tab-panel-6761)
-   [C](#tab-panel-6762)
-   [Java](#tab-panel-6763)
-   [Python](#tab-panel-6764)

```java
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();

}
```

```python
data_set = DataSet.of("test", "txnset")

key = data_set.id("txnkey")

key2 = data_set.id("txnkey2")

geo = '{"type": "Polygon", "coordinates": [[[-122.5, 37.0], [-121.0, 37.0], [-121.0, 38.0], [-122.5, 38.0], [-122.5, 37.0]]]}'

bins = {

    "str": "atomic",

    "int": 8,

    "double": 6.5,

    "blob": bytes([1, 2, 3, 4, 5]),

    "geo": GeoJSON(geo),

    "list": [1],

    "map": {2: 4},

}

for k in (key, key2):

    session.upsert(k).put(bins).execute()
```

```rust
let key = as_key!("test", "txnset", "txnkey");

let key2 = as_key!("test", "txnset", "txnkey2");

let geo = r#"{"type": "Polygon", "coordinates": [[[-122.5, 37.0], [-121.0, 37.0], [-121.0, 38.0], [-122.5, 38.0], [-122.5, 37.0]]]}"#;

let bins = [

    as_bin!("str", "atomic"),

    as_bin!("int", 8),

    as_bin!("double", 6.5),

    as_bin!("blob", Value::Blob(vec![1, 2, 3, 4, 5])),

    as_bin!("geo", as_geo!(geo)),

    as_bin!("list", as_list!(1)),

    as_bin!("map", as_map!(2 => 4)),

];

client.put(&write_policy, &key, &bins).await?;

client.put(&write_policy, &key2, &bins).await?;
```

```csharp
Key key = new Key("test", "txnset", "txnkey");

Key key2 = new Key("test", "txnset", "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]]]}";

Bin[] bins = {

    new Bin("str", "atomic"),

    new Bin("int", 8),

    new Bin("double", 6.5),

    new Bin("blob", new byte[] { 1, 2, 3, 4, 5 }),

    new Bin("geo", Value.GetAsGeoJSON(geo)),

    new Bin("list", new List<int> { 1 }),

    new Bin("map", new Dictionary<int, int> { { 2, 4 } })

};

client.Put(null, key, bins);

client.Put(null, key2, bins);
```

```go
key, err := aerospike.NewKey("test", "txnset", "txnkey")

if err != nil {

  log.Fatal(err)

}

key2, err := aerospike.NewKey("test", "txnset", "txnkey2")

if err != nil {

  log.Fatal(err)

}

geo := `{"type": "Polygon", "coordinates": [[[-122.5, 37.0], [-121.0, 37.0], [-121.0, 38.0], [-122.5, 38.0], [-122.5, 37.0]]]}`

bins := []*aerospike.Bin{

  aerospike.NewBin("str", "atomic"),

  aerospike.NewBin("int", 8),

  aerospike.NewBin("double", 6.5),

  aerospike.NewBin("blob", []byte{1, 2, 3, 4, 5}),

  aerospike.NewBin("geo", aerospike.NewGeoJSONValue(geo)),

  aerospike.NewBin("list", []int{1}),

  aerospike.NewBin("map", map[int]int{2: 4}),

}

for _, k := range []*aerospike.Key{key, key2} {

  if err := client.PutBins(nil, k, bins...); err != nil {

    log.Fatal(err)

  }

}
```

```js
const key = new Aerospike.Key('test', 'txnset', 'txnkey');

const key2 = new Aerospike.Key('test', 'txnset', 'txnkey2');

const geo = '{"type": "Polygon", "coordinates": [[[-122.5, 37.0], [-121.0, 37.0], [-121.0, 38.0], [-122.5, 38.0], [-122.5, 37.0]]]}';

const bins = {

    str: 'atomic',

    int: 8,

    double: 6.5,

    blob: Buffer.from([1, 2, 3, 4, 5]),

    geo: new Aerospike.GeoJSON(geo),

    list: [1],

    map: new Map([[2, 4]]),

};

await client.put(key, bins);

await client.put(key2, bins);
```

```c
as_key key;

as_key_init_str(&key, "test", "txnset", "txnkey");

as_key key2;

as_key_init_str(&key2, "test", "txnset", "txnkey2");

const char* geo = "{\"type\": \"Polygon\", \"coordinates\": [[[-122.5, 37.0], [-121.0, 37.0], [-121.0, 38.0], [-122.5, 38.0], [-122.5, 37.0]]]}";

uint8_t blob[] = {1, 2, 3, 4, 5};

as_arraylist list;

as_arraylist_inita(&list, 1);

as_arraylist_append_int64(&list, 1);

as_hashmap map;

as_hashmap_init(&map, 1);

as_hashmap_set(&map, (as_val*)as_integer_new(2), (as_val*)as_integer_new(4));

as_record rec;

as_record_inita(&rec, 7);

as_record_set_str(&rec, "str", "atomic");

as_record_set_int64(&rec, "int", 8);

as_record_set_double(&rec, "double", 6.5);

as_record_set_bytes(&rec, "blob", as_bytes_new_wrap(blob, sizeof(blob), false));

as_record_set_geojson_str(&rec, "geo", geo);

as_record_set_list(&rec, "list", (as_list*)&list);

as_record_set_map(&rec, "map", (as_map*)&map);

if (aerospike_key_put(&as, &err, NULL, &key, &rec) != AEROSPIKE_OK ||

    aerospike_key_put(&as, &err, NULL, &key2, &rec) != AEROSPIKE_OK) {

    fprintf(stderr, "Error writing records: %s\n", err.message);

    as_record_destroy(&rec);

    return 1;

}

as_record_destroy(&rec);
```

The record takes ownership of the List, Map, and Blob values that you set in it, and `as_record_destroy` releases them. The same record is written to both keys before it is destroyed.

```java
Key key = new Key("test", "txnset", "txnkey");

Key key2 = new Key("test", "txnset", "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]]]}";

Bin[] bins = {

    new Bin("str", "atomic"),

    new Bin("int", 8),

    new Bin("double", 6.5),

    new Bin("blob", new byte[] {1, 2, 3, 4, 5}),

    new Bin("geo", Value.getAsGeoJSON(geo)),

    new Bin("list", List.of(1)),

    new Bin("map", Map.of(2, 4))

};

client.put(null, key, bins);

client.put(null, key2, bins);
```

```python
key = ("test", "txnset", "txnkey")

key2 = ("test", "txnset", "txnkey2")

geo = '{"type": "Polygon", "coordinates": [[[-122.5, 37.0], [-121.0, 37.0], [-121.0, 38.0], [-122.5, 38.0], [-122.5, 37.0]]]}'

bins = {

    "str": "atomic",

    "int": 8,

    "double": 6.5,

    "blob": bytes([1, 2, 3, 4, 5]),

    "geo": aerospike.geojson(geo),

    "list": [1],

    "map": {2: 4},

}

client.put(key, bins)

client.put(key2, bins)
```

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

-   [Java SDK](#tab-panel-6765)
-   [Python SDK](#tab-panel-6766)
-   [Rust](#tab-panel-6767)
-   [C#](#tab-panel-6768)
-   [Go](#tab-panel-6769)
-   [Node.js](#tab-panel-6770)
-   [C](#tab-panel-6771)
-   [Java](#tab-panel-6772)
-   [Python](#tab-panel-6773)

```java
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);
```

```python
record = session.query(key).execute().first_or_raise().record_or_raise()

print("str:", record.bins["str"])

print("int:", record.bins["int"])

print("double:", record.bins["double"])

print("Generation:", record.generation)
```

```rust
let record = client.get(&read_policy, &key, Bins::All).await?;

println!("str: {}", record.bins["str"]);

println!("int: {}", record.bins["int"]);

println!("double: {}", record.bins["double"]);

println!("Generation: {}", record.generation);
```

```csharp
Record record = client.Get(null, key);

Console.WriteLine("str: " + record.GetString("str"));

Console.WriteLine("int: " + record.GetLong("int"));

Console.WriteLine("double: " + record.GetDouble("double"));

Console.WriteLine("Generation: " + record.generation);
```

```go
record, err := client.Get(nil, key)

if err != nil {

  log.Fatal(err)

}

fmt.Println("str:", record.Bins["str"])

fmt.Println("int:", record.Bins["int"])

fmt.Println("double:", record.Bins["double"])

fmt.Println("Generation:", record.Generation)
```

```js
let record = await client.get(key);

console.log('str:', record.bins.str);

console.log('int:', record.bins.int);

console.log('double:', record.bins.double);

console.log('Generation:', record.gen);
```

```c
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("str: %s\n", as_record_get_str(record, "str"));

printf("int: %lld\n", (long long)as_record_get_int64(record, "int", 0));

printf("double: %g\n", as_record_get_double(record, "double", 0));

printf("Generation: %d\n", record->gen);
```

```java
Record record = client.get(null, key);

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);
```

```python
(_, meta, bins) = client.get(key)

print("str:", bins["str"])

print("int:", bins["int"])

print("double:", bins["double"])

print("Generation:", meta["gen"])
```

```text
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.

-   [Java SDK](#tab-panel-6774)
-   [Python SDK](#tab-panel-6775)
-   [Rust](#tab-panel-6776)
-   [C#](#tab-panel-6777)
-   [Go](#tab-panel-6778)
-   [Node.js](#tab-panel-6779)
-   [C](#tab-panel-6780)
-   [Java](#tab-panel-6781)
-   [Python](#tab-panel-6782)

```java
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);
```

```python
header = session.query(key).with_no_bins().execute().first_or_raise().record_or_raise()

print("Generation:", header.generation)

session.touch(key).execute()

header = session.query(key).with_no_bins().execute().first_or_raise().record_or_raise()

print("Generation:", header.generation)
```

```rust
let header = client.get(&read_policy, &key, Bins::None).await?;

println!("Generation: {}", header.generation);

client.touch(&write_policy, &key).await?;

let header = client.get(&read_policy, &key, Bins::None).await?;

println!("Generation: {}", header.generation);
```

```csharp
Record header = client.GetHeader(null, key);

Console.WriteLine("Generation: " + header.generation);

client.Touch(null, key);

header = client.GetHeader(null, key);

Console.WriteLine("Generation: " + header.generation);
```

```go
header, err := client.GetHeader(nil, key)

if err != nil {

  log.Fatal(err)

}

fmt.Println("Generation:", header.Generation)

if err := client.Touch(nil, key); err != nil {

  log.Fatal(err)

}

header, err = client.GetHeader(nil, key)

if err != nil {

  log.Fatal(err)

}

fmt.Println("Generation:", header.Generation)
```

```js
let header = await client.select(key, ['str']);

console.log('Generation:', header.gen);

await client.operate(key, [op.touch()]);

header = await client.select(key, ['str']);

console.log('Generation:', header.gen);
```

The Node.js client has no header-only read, so the example selects one bin and reads the generation from the result. The touch is an `operate` command with a touch operation.

```c
as_record* header = NULL;

if (aerospike_key_exists(&as, &err, NULL, &key, &header) != AEROSPIKE_OK) {

    fprintf(stderr, "Error reading header: %s\n", err.message);

    return 1;

}

printf("Generation: %d\n", header->gen);

as_record_destroy(header);

as_operations ops;

as_operations_inita(&ops, 1);

as_operations_add_touch(&ops);

if (aerospike_key_operate(&as, &err, NULL, &key, &ops, NULL) != AEROSPIKE_OK) {

    fprintf(stderr, "Error touching record: %s\n", err.message);

    return 1;

}

as_operations_destroy(&ops);

header = NULL;

if (aerospike_key_exists(&as, &err, NULL, &key, &header) != AEROSPIKE_OK) {

    fprintf(stderr, "Error reading header: %s\n", err.message);

    return 1;

}

printf("Generation: %d\n", header->gen);

as_record_destroy(header);
```

The C client has no separate touch function, so the example runs a touch operation with `aerospike_key_operate`. The `aerospike_key_exists` function returns the record header.

```java
Record header = client.getHeader(null, key);

System.out.println("Generation: " + header.generation);

client.touch(null, key);

header = client.getHeader(null, key);

System.out.println("Generation: " + header.generation);
```

```python
(_, header) = client.exists(key)

print("Generation:", header["gen"])

client.touch(key)

(_, header) = client.exists(key)

print("Generation:", header["gen"])
```

```text
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.

-   [Java SDK](#tab-panel-6783)
-   [Python SDK](#tab-panel-6784)
-   [Rust](#tab-panel-6785)
-   [C#](#tab-panel-6786)
-   [Go](#tab-panel-6787)
-   [Node.js](#tab-panel-6788)
-   [C](#tab-panel-6789)
-   [Java](#tab-panel-6790)
-   [Python](#tab-panel-6791)

```java
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"));
```

```python
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().first_or_raise().record_or_raise()

print("str:", record.bins["str"])

print("int:", record.bins["int"])

print("double:", record.bins["double"])
```

```rust
client.operate(&write_policy, &key, &[string::append(&StringPolicy::default(), "str", "-operation")]).await?;

client.operate(&write_policy, &key, &[scalar::add(&as_bin!("int", 5))]).await?;

client.operate(&write_policy, &key, &[scalar::add(&as_bin!("double", -2.25))]).await?;

let record = client.get(&read_policy, &key, Bins::All).await?;

println!("str: {}", record.bins["str"]);

println!("int: {}", record.bins["int"]);

println!("double: {}", record.bins["double"]);
```

```csharp
client.Operate(null, key, StringOperation.Append(StringPolicy.Default, "str", "-operation"));

client.Operate(null, key, Operation.Add(new Bin("int", 5)));

client.Operate(null, key, Operation.Add(new Bin("double", -2.25)));

record = client.Get(null, key);

Console.WriteLine("str: " + record.GetString("str"));

Console.WriteLine("int: " + record.GetLong("int"));

Console.WriteLine("double: " + record.GetDouble("double"));
```

```go
_, err = client.Operate(nil, key, aerospike.StrAppendOp(aerospike.DefaultStringPolicy, "str", "-operation"))

if err != nil {

  log.Fatal(err)

}

_, err = client.Operate(nil, key, aerospike.AddOp(aerospike.NewBin("int", 5)))

if err != nil {

  log.Fatal(err)

}

_, err = client.Operate(nil, key, aerospike.AddOp(aerospike.NewBin("double", -2.25)))

if err != nil {

  log.Fatal(err)

}

record, err = client.Get(nil, key)

if err != nil {

  log.Fatal(err)

}

fmt.Println("str:", record.Bins["str"])

fmt.Println("int:", record.Bins["int"])

fmt.Println("double:", record.Bins["double"])
```

```js
await client.operate(key, [strings.append('str', '-operation')]);

await client.operate(key, [op.incr('int', 5)]);

await client.operate(key, [op.incr('double', -2.25)]);

record = await client.get(key);

console.log('str:', record.bins.str);

console.log('int:', record.bins.int);

console.log('double:', record.bins.double);
```

```c
as_operations_inita(&ops, 1);

as_operations_string_append(&ops, "str", NULL, NULL, "-operation");

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, "int", 5);

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_operations_inita(&ops, 1);

as_operations_add_incr_double(&ops, "double", -2.25);

if (aerospike_key_operate(&as, &err, NULL, &key, &ops, NULL) != AEROSPIKE_OK) {

    fprintf(stderr, "Error adding to the double: %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("str: %s\n", as_record_get_str(record, "str"));

printf("int: %lld\n", (long long)as_record_get_int64(record, "int", 0));

printf("double: %g\n", as_record_get_double(record, "double", 0));
```

The C client reuses the `ops` variable from the previous step. Call `as_operations_inita` again for each new command, and call `as_operations_destroy` after each command.

```java
client.operate(null, key, StringOperation.append(StringPolicy.Default, "str", "-operation"));

client.operate(null, key, Operation.add(new Bin("int", 5)));

client.operate(null, key, Operation.add(new Bin("double", -2.25)));

record = client.get(null, key);

System.out.println("str: " + record.getString("str"));

System.out.println("int: " + record.getLong("int"));

System.out.println("double: " + record.getDouble("double"));
```

```python
client.operate(key, [string_operations.append("str", "-operation")])

client.operate(key, [operations.increment("int", 5)])

client.operate(key, [operations.increment("double", -2.25)])

(_, meta, bins) = client.get(key)

print("str:", bins["str"])

print("int:", bins["int"])

print("double:", bins["double"])
```

```text
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.

-   [Java SDK](#tab-panel-6792)
-   [Python SDK](#tab-panel-6793)
-   [Rust](#tab-panel-6794)
-   [C#](#tab-panel-6795)
-   [Go](#tab-panel-6796)
-   [Node.js](#tab-panel-6797)
-   [C](#tab-panel-6798)
-   [Java](#tab-panel-6799)
-   [Python](#tab-panel-6800)

```java
Record result = session.upsert(key).bin("list").listAppend(5).execute().getFirstRecord();

System.out.println("List size: " + result.getLong("list"));
```

```python
result = session.upsert(key).bin("list").list_append(5).execute().first_or_raise().record_or_raise()

print("List size:", result.bins["list"])
```

```rust
let result = client.operate(&write_policy, &key, &[lists::append(&ListPolicy::default(), "list", as_val!(5))]).await?;

println!("List size: {}", result.bins["list"]);
```

```csharp
Record result = client.Operate(null, key, ListOperation.Append("list", Value.Get(5)));

Console.WriteLine("List size: " + result.GetLong("list"));
```

```go
listResult, err := client.Operate(nil, key, aerospike.ListAppendOp("list", 5))

if err != nil {

  log.Fatal(err)

}

fmt.Println("List size:", listResult.Bins["list"])
```

```js
const listResult = await client.operate(key, [lists.append('list', 5)]);

console.log('List size:', listResult.bins.list);
```

```c
as_operations_inita(&ops, 1);

as_operations_list_append(&ops, "list", NULL, NULL, (as_val*)as_integer_new(5));

as_record* result = NULL;

if (aerospike_key_operate(&as, &err, NULL, &key, &ops, &result) != AEROSPIKE_OK) {

    fprintf(stderr, "Error appending to the list: %s\n", err.message);

    return 1;

}

printf("List size: %lld\n", (long long)as_record_get_int64(result, "list", 0));

as_operations_destroy(&ops);

as_record_destroy(result);
```

The `as_integer_new` function creates the value on the heap. The operation takes ownership of the value, and `as_operations_destroy` frees it.

```java
Record result = client.operate(null, key, ListOperation.append("list", Value.get(5)));

System.out.println("List size: " + result.getLong("list"));
```

```python
(_, _, result) = client.operate(key, [list_operations.list_append("list", 5)])

print("List size:", result["list"])
```

```text
List size: 2
```

Output

For more about Lists, see the [Reading and updating lists](https://aerospike.com/docs/develop/tutorials/cdt/working-with-lists-java) 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}`.

-   [Java SDK](#tab-panel-6801)
-   [Python SDK](#tab-panel-6802)
-   [Rust](#tab-panel-6803)
-   [C#](#tab-panel-6804)
-   [Go](#tab-panel-6805)
-   [Node.js](#tab-panel-6806)
-   [C](#tab-panel-6807)
-   [Java](#tab-panel-6808)
-   [Python](#tab-panel-6809)

```java
result = session.upsert(key).bin("map").onMapKey(2).add(57).execute().getFirstRecord();

System.out.println("Map value: " + result.getLong("map"));
```

```python
result = session.upsert(key).bin("map").on_map_key(2).add(57).execute().first_or_raise().record_or_raise()

print("Map value:", result.bins["map"])
```

```rust
let result = client.operate(&write_policy, &key, &[maps::increment_value(&MapPolicy::default(), "map", as_val!(2), as_val!(57))]).await?;

println!("Map value: {}", result.bins["map"]);
```

```csharp
result = client.Operate(null, key, MapOperation.Increment(MapPolicy.Default, "map", Value.Get(2), Value.Get(57)));

Console.WriteLine("Map value: " + result.GetLong("map"));
```

```go
mapResult, err := client.Operate(nil, key, aerospike.MapIncrementOp(aerospike.DefaultMapPolicy(), "map", 2, 57))

if err != nil {

  log.Fatal(err)

}

fmt.Println("Map value:", mapResult.Bins["map"])
```

```js
const mapResult = await client.operate(key, [maps.increment('map', 2, 57)]);

console.log('Map value:', mapResult.bins.map);
```

```c
as_map_policy map_policy;

as_map_policy_init(&map_policy);

as_operations_inita(&ops, 1);

as_operations_map_increment(&ops, "map", NULL, &map_policy,

    (as_val*)as_integer_new(2), (as_val*)as_integer_new(57));

result = NULL;

if (aerospike_key_operate(&as, &err, NULL, &key, &ops, &result) != AEROSPIKE_OK) {

    fprintf(stderr, "Error incrementing the map value: %s\n", err.message);

    return 1;

}

printf("Map value: %lld\n", (long long)as_record_get_int64(result, "map", 0));

as_operations_destroy(&ops);

as_record_destroy(result);
```

```java
result = client.operate(null, key, MapOperation.increment(MapPolicy.Default, "map", Value.get(2), Value.get(57)));

System.out.println("Map value: " + result.getLong("map"));
```

```python
(_, _, result) = client.operate(key, [map_operations.map_increment("map", 2, 57)])

print("Map value:", result["map"])
```

```text
Map value: 61
```

Output

For more about Maps, see the [Reading and updating maps](https://aerospike.com/docs/develop/tutorials/cdt/working-with-maps-java) 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.

-   [Java SDK](#tab-panel-6810)
-   [Python SDK](#tab-panel-6811)
-   [Rust](#tab-panel-6812)
-   [C#](#tab-panel-6813)
-   [Go](#tab-panel-6814)
-   [Node.js](#tab-panel-6815)
-   [C](#tab-panel-6816)
-   [Java](#tab-panel-6817)
-   [Python](#tab-panel-6818)

```java
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")));
```

```python
session.upsert(key).bin("blob").bit_set(13, 8, bytes([0xE0])).execute()

record = session.query(key).bin("blob").get().execute().first_or_raise().record_or_raise()

print("Blob:", record.bins["blob"].hex())
```

```rust
client.operate(&write_policy, &key, &[bitwise::set("blob", 13, 8, Value::Blob(vec![0xE0]), &BitPolicy::default())]).await?;

let record = client.get(&read_policy, &key, ["blob"]).await?;

let Value::Blob(bytes) = &record.bins["blob"] else {

    panic!("the blob bin is not a Blob");

};

println!("Blob: {}", bytes.iter().map(|b| format!("{b:02x}")).collect::<String>());
```

```csharp
client.Operate(null, key, BitOperation.Set(BitPolicy.Default, "blob", 13, 8, new byte[] { 0xE0 }));

record = client.Get(null, key, "blob");

Console.WriteLine("Blob: " + Convert.ToHexString((byte[])record.GetValue("blob")).ToLower());
```

```go
_, err = client.Operate(nil, key, aerospike.BitSetOp(aerospike.DefaultBitPolicy(), "blob", 13, 8, []byte{0xE0}))

if err != nil {

  log.Fatal(err)

}

blobRecord, err := client.Get(nil, key, "blob")

if err != nil {

  log.Fatal(err)

}

fmt.Printf("Blob: %x\n", blobRecord.Bins["blob"])
```

```js
await client.operate(key, [bitwise.set('blob', 13, 8, Buffer.from([0xe0]))]);

const blobRecord = await client.select(key, ['blob']);

console.log('Blob:', blobRecord.bins.blob.toString('hex'));
```

```c
uint8_t bits[] = {0xE0};

as_operations_inita(&ops, 1);

as_operations_bit_set(&ops, "blob", NULL, NULL, 13, 8, sizeof(bits), bits);

if (aerospike_key_operate(&as, &err, NULL, &key, &ops, NULL) != AEROSPIKE_OK) {

    fprintf(stderr, "Error setting the bits: %s\n", err.message);

    return 1;

}

as_operations_destroy(&ops);

const char* blob_bin[] = {"blob", NULL};

result = NULL;

if (aerospike_key_select(&as, &err, NULL, &key, blob_bin, &result) != AEROSPIKE_OK) {

    fprintf(stderr, "Error reading the blob: %s\n", err.message);

    return 1;

}

as_bytes* blob_value = as_record_get_bytes(result, "blob");

const uint8_t* blob_data = as_bytes_get(blob_value);

printf("Blob: ");

for (uint32_t i = 0; i < as_bytes_size(blob_value); i++) {

    printf("%02x", blob_data[i]);

}

printf("\n");

as_record_destroy(result);
```

```java
client.operate(null, key, BitOperation.set(BitPolicy.Default, "blob", 13, 8, new byte[] {(byte) 0xE0}));

record = client.get(null, key, "blob");

System.out.println("Blob: " + HexFormat.of().formatHex(record.getBytes("blob")));
```

```python
client.operate(key, [bitwise_operations.bit_set("blob", 13, 8, 1, bytes([0xE0]))])

(_, _, bins) = client.select(key, ["blob"])

print("Blob:", bins["blob"].hex())
```

The `1` is the `value_byte_size` argument. The client ignores it and takes the size from the value, but the function still requires it.

```text
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.

-   [Java SDK](#tab-panel-6819)
-   [Python SDK](#tab-panel-6820)
-   [Rust](#tab-panel-6821)
-   [C#](#tab-panel-6822)
-   [Go](#tab-panel-6823)
-   [Node.js](#tab-panel-6824)
-   [C](#tab-panel-6825)
-   [Java](#tab-panel-6826)
-   [Python](#tab-panel-6827)

```java
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"));
```

```python
(

    session.upsert(key)

    .bin("hll").hll_init(HllConfig.of(8))

    .bin("hll").hll_add(["a", "b", "c"], config=HllConfig.of(8))

    .execute()

)

record = session.query(key).bin("hll").hll_get_count().execute().first_or_raise().record_or_raise()

print("HLL count:", record.bins["hll"])
```

```rust
client.operate(&write_policy, &key, &[

    hll::init(&HllPolicy::default(), "hll", 8),

    hll::add_with_index(&HllPolicy::default(), "hll", vec![as_val!("a"), as_val!("b"), as_val!("c")], 8),

]).await?;

let record = client.operate(&write_policy, &key, &[hll::get_count("hll")]).await?;

println!("HLL count: {}", record.bins["hll"]);
```

```csharp
client.Operate(null, key,

    HLLOperation.Init(HLLPolicy.Default, "hll", 8),

    HLLOperation.Add(HLLPolicy.Default, "hll", new List<Value> { Value.Get("a"), Value.Get("b"), Value.Get("c") }, 8));

record = client.Operate(null, key, HLLOperation.GetCount("hll"));

Console.WriteLine("HLL count: " + record.GetLong("hll"));
```

```go
_, err = client.Operate(nil, key,

  aerospike.HLLInitOp(aerospike.DefaultHLLPolicy(), "hll", 8, -1),

  aerospike.HLLAddOp(aerospike.DefaultHLLPolicy(), "hll",

    []aerospike.Value{aerospike.NewValue("a"), aerospike.NewValue("b"), aerospike.NewValue("c")}, 8, -1))

if err != nil {

  log.Fatal(err)

}

hllResult, err := client.Operate(nil, key, aerospike.HLLGetCountOp("hll"))

if err != nil {

  log.Fatal(err)

}

fmt.Println("HLL count:", hllResult.Bins["hll"])
```

```js
await client.operate(key, [

    hll.init('hll', 8),

    hll.add('hll', ['a', 'b', 'c'], 8),

]);

const hllResult = await client.operate(key, [hll.getCount('hll')]);

console.log('HLL count:', hllResult.bins.hll);
```

```c
as_arraylist* values = as_arraylist_new(3, 0);

as_arraylist_append_str(values, "a");

as_arraylist_append_str(values, "b");

as_arraylist_append_str(values, "c");

as_operations_inita(&ops, 2);

as_operations_hll_init(&ops, "hll", NULL, NULL, 8);

as_operations_hll_add(&ops, "hll", NULL, NULL, (as_list*)values, 8);

if (aerospike_key_operate(&as, &err, NULL, &key, &ops, NULL) != AEROSPIKE_OK) {

    fprintf(stderr, "Error updating the HyperLogLog: %s\n", err.message);

    return 1;

}

as_operations_destroy(&ops);

as_operations_inita(&ops, 1);

as_operations_hll_get_count(&ops, "hll", NULL);

result = NULL;

if (aerospike_key_operate(&as, &err, NULL, &key, &ops, &result) != AEROSPIKE_OK) {

    fprintf(stderr, "Error reading the HyperLogLog count: %s\n", err.message);

    return 1;

}

printf("HLL count: %lld\n", (long long)as_record_get_int64(result, "hll", 0));

as_operations_destroy(&ops);

as_record_destroy(result);
```

```java
client.operate(null, key,

    HLLOperation.init(HLLPolicy.Default, "hll", 8),

    HLLOperation.add(HLLPolicy.Default, "hll", List.of(Value.get("a"), Value.get("b"), Value.get("c")), 8));

record = client.operate(null, key, HLLOperation.getCount("hll"));

System.out.println("HLL count: " + record.getLong("hll"));
```

```python
client.operate(key, [

    hll_operations.hll_init("hll", 8),

    hll_operations.hll_add("hll", ["a", "b", "c"], 8),

])

(_, _, result) = client.operate(key, [hll_operations.hll_get_count("hll")])

print("HLL count:", result["hll"])
```

```text
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](https://aerospike.com/docs/develop/data-types/geospatial).

-   [Java SDK](#tab-panel-6828)
-   [Python SDK](#tab-panel-6829)
-   [Rust](#tab-panel-6830)
-   [C#](#tab-panel-6831)
-   [Go](#tab-panel-6832)
-   [Node.js](#tab-panel-6833)
-   [C](#tab-panel-6834)
-   [Java](#tab-panel-6835)
-   [Python](#tab-panel-6836)

```java
record = session.query(key).bin("geo").get().execute().getFirstRecord();

System.out.println("Geo: " + record.getGeoJSONString("geo"));
```

```python
record = session.query(key).bin("geo").get().execute().first_or_raise().record_or_raise()

print("Geo:", record.bins["geo"])
```

```rust
let record = client.get(&read_policy, &key, ["geo"]).await?;

println!("Geo: {}", record.bins["geo"]);
```

```csharp
record = client.Get(null, key, "geo");

Console.WriteLine("Geo: " + record.GetGeoJSON("geo"));
```

```go
geoRecord, err := client.Get(nil, key, "geo")

if err != nil {

  log.Fatal(err)

}

fmt.Println("Geo:", geoRecord.Bins["geo"])
```

```js
const geoRecord = await client.select(key, ['geo']);

console.log('Geo:', geoRecord.bins.geo);
```

```c
const char* geo_bin[] = {"geo", NULL};

result = NULL;

if (aerospike_key_select(&as, &err, NULL, &key, geo_bin, &result) != AEROSPIKE_OK) {

    fprintf(stderr, "Error reading the GeoJSON value: %s\n", err.message);

    return 1;

}

printf("Geo: %s\n", as_geojson_get(as_record_get_geojson(result, "geo")));

as_record_destroy(result);
```

```java
record = client.get(null, key, "geo");

System.out.println("Geo: " + record.getGeoJSONString("geo"));
```

```python
(_, _, bins) = client.select(key, ["geo"])

print("Geo:", bins["geo"])
```

```text
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.

-   [Java SDK](#tab-panel-6837)
-   [Python SDK](#tab-panel-6838)
-   [Rust](#tab-panel-6839)
-   [C#](#tab-panel-6840)
-   [Go](#tab-panel-6841)
-   [Node.js](#tab-panel-6842)
-   [C](#tab-panel-6843)
-   [Java](#tab-panel-6844)
-   [Python](#tab-panel-6845)

```java
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()`.

```python
(

    session.upsert(key2).touch_record()

    .bin("str").append("-operation")

    .bin("int").add(5)

    .bin("double").add(-2.25)

    .bin("list").list_append(5)

    .bin("map").on_map_key(2).add(57)

    .bin("blob").bit_set(13, 8, bytes([0xE0]))

    .bin("hll").hll_init(HllConfig.of(8))

    .bin("hll").hll_add(["a", "b", "c"], config=HllConfig.of(8))

    .execute()

)

after = (

    session.query(key2)

    .bin("str").get()

    .bin("int").get()

    .bin("double").get()

    .bin("blob").get()

    .bin("list").list_size()

    .bin("map").on_map_key(2).get_values()

    .bin("hll").hll_get_count()

    .execute().first_or_raise().record_or_raise()

)

print("str:", after.bins["str"])

print("int:", after.bins["int"])

print("double:", after.bins["double"])

print("Blob:", after.bins["blob"].hex())

print("List size:", after.bins["list"])

print("Map value:", after.bins["map"])

print("HLL count:", after.bins["hll"])

print("Generation:", after.generation)

first = session.query(key).with_no_bins().execute().first_or_raise().record_or_raise()

print("Generation of the first record:", first.generation)
```

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

```rust
client.operate(&write_policy, &key2, &[

    scalar::touch(),

    string::append(&StringPolicy::default(), "str", "-operation"),

    scalar::add(&as_bin!("int", 5)),

    scalar::add(&as_bin!("double", -2.25)),

    lists::append(&ListPolicy::default(), "list", as_val!(5)),

    maps::increment_value(&MapPolicy::default(), "map", as_val!(2), as_val!(57)),

    bitwise::set("blob", 13, 8, Value::Blob(vec![0xE0]), &BitPolicy::default()),

    hll::init(&HllPolicy::default(), "hll", 8),

    hll::add_with_index(&HllPolicy::default(), "hll", vec![as_val!("a"), as_val!("b"), as_val!("c")], 8),

]).await?;

let after = client.operate(&write_policy, &key2, &[

    scalar::get_bin("str"),

    scalar::get_bin("int"),

    scalar::get_bin("double"),

    scalar::get_bin("blob"),

    lists::size("list"),

    maps::get_by_key("map", as_val!(2), MapReturnType::VALUE),

    hll::get_count("hll"),

]).await?;

println!("str: {}", after.bins["str"]);

println!("int: {}", after.bins["int"]);

println!("double: {}", after.bins["double"]);

let Value::Blob(bytes) = &after.bins["blob"] else {

    panic!("the blob bin is not a Blob");

};

println!("Blob: {}", bytes.iter().map(|b| format!("{b:02x}")).collect::<String>());

println!("List size: {}", after.bins["list"]);

println!("Map value: {}", after.bins["map"]);

println!("HLL count: {}", after.bins["hll"]);

println!("Generation: {}", after.generation);

let first = client.get(&read_policy, &key, Bins::None).await?;

println!("Generation of the first record: {}", first.generation);
```

```csharp
client.Operate(null, key2,

    Operation.Touch(),

    StringOperation.Append(StringPolicy.Default, "str", "-operation"),

    Operation.Add(new Bin("int", 5)),

    Operation.Add(new Bin("double", -2.25)),

    ListOperation.Append("list", Value.Get(5)),

    MapOperation.Increment(MapPolicy.Default, "map", Value.Get(2), Value.Get(57)),

    BitOperation.Set(BitPolicy.Default, "blob", 13, 8, new byte[] { 0xE0 }),

    HLLOperation.Init(HLLPolicy.Default, "hll", 8),

    HLLOperation.Add(HLLPolicy.Default, "hll", new List<Value> { Value.Get("a"), Value.Get("b"), Value.Get("c") }, 8));

Record after = client.Operate(null, key2,

    Operation.Get("str"),

    Operation.Get("int"),

    Operation.Get("double"),

    Operation.Get("blob"),

    ListOperation.Size("list"),

    MapOperation.GetByKey("map", Value.Get(2), MapReturnType.VALUE),

    HLLOperation.GetCount("hll"));

Console.WriteLine("str: " + after.GetString("str"));

Console.WriteLine("int: " + after.GetLong("int"));

Console.WriteLine("double: " + after.GetDouble("double"));

Console.WriteLine("Blob: " + Convert.ToHexString((byte[])after.GetValue("blob")).ToLower());

Console.WriteLine("List size: " + after.GetLong("list"));

Console.WriteLine("Map value: " + after.GetLong("map"));

Console.WriteLine("HLL count: " + after.GetLong("hll"));

Console.WriteLine("Generation: " + after.generation);

Record first = client.GetHeader(null, key);

Console.WriteLine("Generation of the first record: " + first.generation);
```

```go
_, err = client.Operate(nil, key2,

  aerospike.TouchOp(),

  aerospike.StrAppendOp(aerospike.DefaultStringPolicy, "str", "-operation"),

  aerospike.AddOp(aerospike.NewBin("int", 5)),

  aerospike.AddOp(aerospike.NewBin("double", -2.25)),

  aerospike.ListAppendOp("list", 5),

  aerospike.MapIncrementOp(aerospike.DefaultMapPolicy(), "map", 2, 57),

  aerospike.BitSetOp(aerospike.DefaultBitPolicy(), "blob", 13, 8, []byte{0xE0}),

  aerospike.HLLInitOp(aerospike.DefaultHLLPolicy(), "hll", 8, -1),

  aerospike.HLLAddOp(aerospike.DefaultHLLPolicy(), "hll",

    []aerospike.Value{aerospike.NewValue("a"), aerospike.NewValue("b"), aerospike.NewValue("c")}, 8, -1))

if err != nil {

  log.Fatal(err)

}

after, err := client.Operate(nil, key2,

  aerospike.GetBinOp("str"),

  aerospike.GetBinOp("int"),

  aerospike.GetBinOp("double"),

  aerospike.GetBinOp("blob"),

  aerospike.ListSizeOp("list"),

  aerospike.MapGetByKeyOp("map", 2, aerospike.MapReturnType.VALUE),

  aerospike.HLLGetCountOp("hll"))

if err != nil {

  log.Fatal(err)

}

fmt.Println("str:", after.Bins["str"])

fmt.Println("int:", after.Bins["int"])

fmt.Println("double:", after.Bins["double"])

fmt.Printf("Blob: %x\n", after.Bins["blob"])

fmt.Println("List size:", after.Bins["list"])

fmt.Println("Map value:", after.Bins["map"])

fmt.Println("HLL count:", after.Bins["hll"])

fmt.Println("Generation:", after.Generation)

first, err := client.GetHeader(nil, key)

if err != nil {

  log.Fatal(err)

}

fmt.Println("Generation of the first record:", first.Generation)
```

```js
await client.operate(key2, [

    op.touch(),

    strings.append('str', '-operation'),

    op.incr('int', 5),

    op.incr('double', -2.25),

    lists.append('list', 5),

    maps.increment('map', 2, 57),

    bitwise.set('blob', 13, 8, Buffer.from([0xe0])),

    hll.init('hll', 8),

    hll.add('hll', ['a', 'b', 'c'], 8),

]);

const after = await client.operate(key2, [

    op.read('str'),

    op.read('int'),

    op.read('double'),

    op.read('blob'),

    lists.size('list'),

    maps.getByKey('map', 2, maps.returnType.VALUE),

    hll.getCount('hll'),

]);

console.log('str:', after.bins.str);

console.log('int:', after.bins.int);

console.log('double:', after.bins.double);

console.log('Blob:', after.bins.blob.toString('hex'));

console.log('List size:', after.bins.list);

console.log('Map value:', after.bins.map);

console.log('HLL count:', after.bins.hll);

console.log('Generation:', after.gen);

const first = await client.select(key, ['str']);

console.log('Generation of the first record:', first.gen);
```

```c
values = as_arraylist_new(3, 0);

as_arraylist_append_str(values, "a");

as_arraylist_append_str(values, "b");

as_arraylist_append_str(values, "c");

as_operations_inita(&ops, 9);

as_operations_add_touch(&ops);

as_operations_string_append(&ops, "str", NULL, NULL, "-operation");

as_operations_add_incr(&ops, "int", 5);

as_operations_add_incr_double(&ops, "double", -2.25);

as_operations_list_append(&ops, "list", NULL, NULL, (as_val*)as_integer_new(5));

as_operations_map_increment(&ops, "map", NULL, &map_policy,

    (as_val*)as_integer_new(2), (as_val*)as_integer_new(57));

as_operations_bit_set(&ops, "blob", NULL, NULL, 13, 8, sizeof(bits), bits);

as_operations_hll_init(&ops, "hll", NULL, NULL, 8);

as_operations_hll_add(&ops, "hll", NULL, NULL, (as_list*)values, 8);

if (aerospike_key_operate(&as, &err, NULL, &key2, &ops, NULL) != AEROSPIKE_OK) {

    fprintf(stderr, "Error running the command: %s\n", err.message);

    return 1;

}

as_operations_destroy(&ops);

as_operations_inita(&ops, 7);

as_operations_add_read(&ops, "str");

as_operations_add_read(&ops, "int");

as_operations_add_read(&ops, "double");

as_operations_add_read(&ops, "blob");

as_operations_list_size(&ops, "list", NULL);

as_operations_map_get_by_key(&ops, "map", NULL, (as_val*)as_integer_new(2), AS_MAP_RETURN_VALUE);

as_operations_hll_get_count(&ops, "hll", NULL);

as_record* after = NULL;

if (aerospike_key_operate(&as, &err, NULL, &key2, &ops, &after) != AEROSPIKE_OK) {

    fprintf(stderr, "Error reading the results: %s\n", err.message);

    return 1;

}

printf("str: %s\n", as_record_get_str(after, "str"));

printf("int: %lld\n", (long long)as_record_get_int64(after, "int", 0));

printf("double: %g\n", as_record_get_double(after, "double", 0));

as_bytes* after_blob = as_record_get_bytes(after, "blob");

const uint8_t* after_data = as_bytes_get(after_blob);

printf("Blob: ");

for (uint32_t i = 0; i < as_bytes_size(after_blob); i++) {

    printf("%02x", after_data[i]);

}

printf("\n");

printf("List size: %lld\n", (long long)as_record_get_int64(after, "list", 0));

printf("Map value: %lld\n", (long long)as_record_get_int64(after, "map", 0));

printf("HLL count: %lld\n", (long long)as_record_get_int64(after, "hll", 0));

printf("Generation: %d\n", after->gen);

as_operations_destroy(&ops);

as_record_destroy(after);

as_record* first = NULL;

if (aerospike_key_exists(&as, &err, NULL, &key, &first) != AEROSPIKE_OK) {

    fprintf(stderr, "Error reading header: %s\n", err.message);

    return 1;

}

printf("Generation of the first record: %d\n", first->gen);

as_record_destroy(first);
```

The command has nine operations, so the example allocates the operations with `as_operations_inita(&ops, 9)`. Create a new List for the HyperLogLog values, because `as_operations_destroy` freed the earlier one.

```java
client.operate(null, key2,

    Operation.touch(),

    StringOperation.append(StringPolicy.Default, "str", "-operation"),

    Operation.add(new Bin("int", 5)),

    Operation.add(new Bin("double", -2.25)),

    ListOperation.append("list", Value.get(5)),

    MapOperation.increment(MapPolicy.Default, "map", Value.get(2), Value.get(57)),

    BitOperation.set(BitPolicy.Default, "blob", 13, 8, new byte[] {(byte) 0xE0}),

    HLLOperation.init(HLLPolicy.Default, "hll", 8),

    HLLOperation.add(HLLPolicy.Default, "hll", List.of(Value.get("a"), Value.get("b"), Value.get("c")), 8));

Record after = client.operate(null, key2,

    Operation.get("str"),

    Operation.get("int"),

    Operation.get("double"),

    Operation.get("blob"),

    ListOperation.size("list"),

    MapOperation.getByKey("map", Value.get(2), MapReturnType.VALUE),

    HLLOperation.getCount("hll"));

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 = client.getHeader(null, key);

System.out.println("Generation of the first record: " + first.generation);
```

```python
client.operate(key2, [

    operations.touch(),

    string_operations.append("str", "-operation"),

    operations.increment("int", 5),

    operations.increment("double", -2.25),

    list_operations.list_append("list", 5),

    map_operations.map_increment("map", 2, 57),

    bitwise_operations.bit_set("blob", 13, 8, 1, bytes([0xE0])),

    hll_operations.hll_init("hll", 8),

    hll_operations.hll_add("hll", ["a", "b", "c"], 8),

])

(_, meta, after) = client.operate(key2, [

    operations.read("str"),

    operations.read("int"),

    operations.read("double"),

    operations.read("blob"),

    list_operations.list_size("list"),

    map_operations.map_get_by_key("map", 2, aerospike.MAP_RETURN_VALUE),

    hll_operations.hll_get_count("hll"),

])

print("str:", after["str"])

print("int:", after["int"])

print("double:", after["double"])

print("Blob:", after["blob"].hex())

print("List size:", after["list"])

print("Map value:", after["map"])

print("HLL count:", after["hll"])

print("Generation:", meta["gen"])

(_, first) = client.exists(key)

print("Generation of the first record:", first["gen"])
```

```text
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.

-   [Java SDK](#tab-panel-6846)
-   [Python SDK](#tab-panel-6847)
-   [Rust](#tab-panel-6848)
-   [C#](#tab-panel-6849)
-   [Go](#tab-panel-6850)
-   [Node.js](#tab-panel-6851)
-   [C](#tab-panel-6852)
-   [Java](#tab-panel-6853)
-   [Python](#tab-panel-6854)

```java
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`.

```python
session.upsert(key).bin("map").map_insert_items({2: 1}, no_fail=True, partial=True).execute()

record = session.query(key).bin("map").on_map_key(2).get_values().execute().first_or_raise().record_or_raise()

print("Map value:", record.bins["map"])
```

In the Python SDK, `map_insert_items` doesn’t overwrite an existing key, so it already behaves as `CREATE_ONLY`. The `no_fail` and `partial` arguments are the other two flags.

```rust
let create_only = MapPolicy::new(

    MapOrder::Unordered,

    MapWriteFlags::CREATE_ONLY | MapWriteFlags::NO_FAIL | MapWriteFlags::PARTIAL,

);

client.operate(&write_policy, &key, &[maps::put(&create_only, "map", as_val!(2), as_val!(1))]).await?;

let result = client.operate(&write_policy, &key, &[maps::get_by_key("map", as_val!(2), MapReturnType::VALUE)]).await?;

println!("Map value: {}", result.bins["map"]);
```

```csharp
MapPolicy createOnly = new MapPolicy(

    MapOrder.UNORDERED,

    MapWriteFlags.CREATE_ONLY | MapWriteFlags.NO_FAIL | MapWriteFlags.PARTIAL);

client.Operate(null, key, MapOperation.Put(createOnly, "map", Value.Get(2), Value.Get(1)));

result = client.Operate(null, key, MapOperation.GetByKey("map", Value.Get(2), MapReturnType.VALUE));

Console.WriteLine("Map value: " + result.GetLong("map"));
```

```go
createOnly := aerospike.NewMapPolicyWithFlags(aerospike.MapOrder.UNORDERED,

  aerospike.MapWriteFlagsCreateOnly|aerospike.MapWriteFlagsNoFail|aerospike.MapWriteFlagsPartial)

_, err = client.Operate(nil, key, aerospike.MapPutOp(createOnly, "map", 2, 1))

if err != nil {

  log.Fatal(err)

}

policyResult, err := client.Operate(nil, key, aerospike.MapGetByKeyOp("map", 2, aerospike.MapReturnType.VALUE))

if err != nil {

  log.Fatal(err)

}

fmt.Println("Map value:", policyResult.Bins["map"])
```

```js
const createOnly = { writeFlags: maps.writeFlags.CREATE_ONLY | maps.writeFlags.NO_FAIL | maps.writeFlags.PARTIAL };

await client.operate(key, [maps.put('map', 2, 1, createOnly)]);

const policyResult = await client.operate(key, [maps.getByKey('map', 2, maps.returnType.VALUE)]);

console.log('Map value:', policyResult.bins.map);
```

```c
as_map_policy create_only;

as_map_policy_set_flags(&create_only, AS_MAP_UNORDERED,

    AS_MAP_WRITE_CREATE_ONLY | AS_MAP_WRITE_NO_FAIL | AS_MAP_WRITE_PARTIAL);

as_operations_inita(&ops, 1);

as_operations_map_put(&ops, "map", NULL, &create_only,

    (as_val*)as_integer_new(2), (as_val*)as_integer_new(1));

if (aerospike_key_operate(&as, &err, NULL, &key, &ops, NULL) != AEROSPIKE_OK) {

    fprintf(stderr, "Error putting the map item: %s\n", err.message);

    return 1;

}

as_operations_destroy(&ops);

as_operations_inita(&ops, 1);

as_operations_map_get_by_key(&ops, "map", NULL, (as_val*)as_integer_new(2), AS_MAP_RETURN_VALUE);

result = NULL;

if (aerospike_key_operate(&as, &err, NULL, &key, &ops, &result) != AEROSPIKE_OK) {

    fprintf(stderr, "Error reading the map value: %s\n", err.message);

    return 1;

}

printf("Map value: %lld\n", (long long)as_record_get_int64(result, "map", 0));

as_operations_destroy(&ops);

as_record_destroy(result);
```

```java
MapPolicy createOnly = new MapPolicy(

    MapOrder.UNORDERED,

    MapWriteFlags.CREATE_ONLY | MapWriteFlags.NO_FAIL | MapWriteFlags.PARTIAL);

client.operate(null, key, MapOperation.put(createOnly, "map", Value.get(2), Value.get(1)));

result = client.operate(null, key, MapOperation.getByKey("map", Value.get(2), MapReturnType.VALUE));

System.out.println("Map value: " + result.getLong("map"));
```

```python
create_only = {

    "map_write_flags": aerospike.MAP_WRITE_FLAGS_CREATE_ONLY

    | aerospike.MAP_WRITE_FLAGS_NO_FAIL

    | aerospike.MAP_WRITE_FLAGS_PARTIAL

}

client.operate(key, [map_operations.map_put("map", 2, 1, create_only)])

(_, _, result) = client.operate(key, [map_operations.map_get_by_key("map", 2, aerospike.MAP_RETURN_VALUE)])

print("Map value:", result["map"])
```

```text
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](https://aerospike.com/docs/develop/tutorials/intro/read-modify-write) tutorial, or the [transactions blog post](https://www.aerospike.com/blog/developers-understanding-aerospike-transactions/). For logic that runs in the database, use [record UDFs](https://aerospike.com/docs/database/learn/architecture/udf).

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

-   [Java SDK](#tab-panel-6855)
-   [Python SDK](#tab-panel-6856)
-   [Rust](#tab-panel-6857)
-   [C#](#tab-panel-6858)
-   [Go](#tab-panel-6859)
-   [Node.js](#tab-panel-6860)
-   [C](#tab-panel-6861)
-   [Java](#tab-panel-6862)
-   [Python](#tab-panel-6863)

```java
session.delete(key).execute();

session.delete(key2).execute();

cluster.close();
```

```python
session.delete(key).execute()

session.delete(key2).execute()

cluster.close()
```

```rust
client.delete(&write_policy, &key).await?;

client.delete(&write_policy, &key2).await?;

client.close().await?;
```

```csharp
client.Delete(null, key);

client.Delete(null, key2);

client.Close();
```

```go
for _, k := range []*aerospike.Key{key, key2} {

  if _, err := client.Delete(nil, k); err != nil {

    log.Fatal(err)

  }

}

client.Close()
```

```js
await client.remove(key);

await client.remove(key2);

client.close();
```

```c
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(&key2);

aerospike_close(&as, &err);

aerospike_destroy(&as);
```

```java
client.delete(null, key);

client.delete(null, key2);

client.close();
```

```python
client.remove(key)

client.remove(key2)

client.close()
```

## Complete program

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

-   [Java SDK](#tab-panel-6864)
-   [Python SDK](#tab-panel-6865)
-   [Rust](#tab-panel-6866)
-   [C#](#tab-panel-6867)
-   [Go](#tab-panel-6868)
-   [Node.js](#tab-panel-6869)
-   [C](#tab-panel-6870)
-   [Java](#tab-panel-6871)
-   [Python](#tab-panel-6872)

```java
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();

        }

    }

}
```

```python
import sys

from aerospike_sdk import Behavior, DataSet, HllConfig

from aerospike_sdk.exceptions import AerospikeError

from aerospike_sdk.sync import ClusterDefinition

cluster = ClusterDefinition("127.0.0.1", 3000).connect()

try:

    session = cluster.create_session(Behavior.DEFAULT)

    data_set = DataSet.of("test", "txnset")

    key = data_set.id("txnkey")

    session.upsert(key).put({

        "str": "atomic",

        "int": 8,

        "double": 6.5,

        "blob": bytes([1, 2, 3, 4, 5]),

        "list": [1],

        "map": {2: 4},

    }).execute()

    (

        session.upsert(key).touch_record()

        .bin("str").append("-operation")

        .bin("int").add(5)

        .bin("double").add(-2.25)

        .bin("list").list_append(5)

        .bin("map").on_map_key(2).add(57)

        .bin("blob").bit_set(13, 8, bytes([0xE0]))

        .bin("hll").hll_init(HllConfig.of(8))

        .bin("hll").hll_add(["a", "b", "c"], config=HllConfig.of(8))

        .execute()

    )

    after = (

        session.query(key)

        .bin("str").get()

        .bin("int").get()

        .bin("double").get()

        .bin("blob").get()

        .bin("list").list_size()

        .bin("map").on_map_key(2).get_values()

        .bin("hll").hll_get_count()

        .execute().first_or_raise().record_or_raise()

    )

    print("str:", after.bins["str"])

    print("int:", after.bins["int"])

    print("double:", after.bins["double"])

    print("Blob:", after.bins["blob"].hex())

    print("List size:", after.bins["list"])

    print("Map value:", after.bins["map"])

    print("HLL count:", after.bins["hll"])

    print("Generation:", after.generation)

    session.delete(key).execute()

except AerospikeError as e:

    print(f"Error: {e}", file=sys.stderr)

    sys.exit(1)

finally:

    cluster.close()
```

```rust
use aerospike::operations::bitwise::{self, BitPolicy};

use aerospike::operations::hll::{self, HllPolicy};

use aerospike::operations::maps::{self, MapPolicy, MapReturnType};

use aerospike::operations::string::{self, StringPolicy};

use aerospike::operations::{lists, scalar, ListPolicy};

use aerospike::{as_bin, as_key, as_list, as_map, as_val, Client, ClientPolicy, Value, 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 key = as_key!("test", "txnset", "txnkey");

    client.put(&write_policy, &key, &[

        as_bin!("str", "atomic"),

        as_bin!("int", 8),

        as_bin!("double", 6.5),

        as_bin!("blob", Value::Blob(vec![1, 2, 3, 4, 5])),

        as_bin!("list", as_list!(1)),

        as_bin!("map", as_map!(2 => 4)),

    ]).await?;

    client.operate(&write_policy, &key, &[

        scalar::touch(),

        string::append(&StringPolicy::default(), "str", "-operation"),

        scalar::add(&as_bin!("int", 5)),

        scalar::add(&as_bin!("double", -2.25)),

        lists::append(&ListPolicy::default(), "list", as_val!(5)),

        maps::increment_value(&MapPolicy::default(), "map", as_val!(2), as_val!(57)),

        bitwise::set("blob", 13, 8, Value::Blob(vec![0xE0]), &BitPolicy::default()),

        hll::init(&HllPolicy::default(), "hll", 8),

        hll::add_with_index(&HllPolicy::default(), "hll", vec![as_val!("a"), as_val!("b"), as_val!("c")], 8),

    ]).await?;

    let after = client.operate(&write_policy, &key, &[

        scalar::get_bin("str"),

        scalar::get_bin("int"),

        scalar::get_bin("double"),

        scalar::get_bin("blob"),

        lists::size("list"),

        maps::get_by_key("map", as_val!(2), MapReturnType::VALUE),

        hll::get_count("hll"),

    ]).await?;

    println!("str: {}", after.bins["str"]);

    println!("int: {}", after.bins["int"]);

    println!("double: {}", after.bins["double"]);

    let Value::Blob(bytes) = &after.bins["blob"] else {

        panic!("the blob bin is not a Blob");

    };

    println!("Blob: {}", bytes.iter().map(|b| format!("{b:02x}")).collect::<String>());

    println!("List size: {}", after.bins["list"]);

    println!("Map value: {}", after.bins["map"]);

    println!("HLL count: {}", after.bins["hll"]);

    println!("Generation: {}", after.generation);

    client.delete(&write_policy, &key).await?;

    client.close().await?;

    Ok(())

}
```

```csharp
using System;

using System.Collections.Generic;

using Aerospike.Client;

public class IntroToTransactions

{

    public static void Main()

    {

        AerospikeClient client = new AerospikeClient("127.0.0.1", 3000);

        try

        {

            Key key = new Key("test", "txnset", "txnkey");

            client.Put(null, key,

                new Bin("str", "atomic"),

                new Bin("int", 8),

                new Bin("double", 6.5),

                new Bin("blob", new byte[] { 1, 2, 3, 4, 5 }),

                new Bin("list", new List<int> { 1 }),

                new Bin("map", new Dictionary<int, int> { { 2, 4 } }));

            client.Operate(null, key,

                Operation.Touch(),

                StringOperation.Append(StringPolicy.Default, "str", "-operation"),

                Operation.Add(new Bin("int", 5)),

                Operation.Add(new Bin("double", -2.25)),

                ListOperation.Append("list", Value.Get(5)),

                MapOperation.Increment(MapPolicy.Default, "map", Value.Get(2), Value.Get(57)),

                BitOperation.Set(BitPolicy.Default, "blob", 13, 8, new byte[] { 0xE0 }),

                HLLOperation.Init(HLLPolicy.Default, "hll", 8),

                HLLOperation.Add(HLLPolicy.Default, "hll", new List<Value> { Value.Get("a"), Value.Get("b"), Value.Get("c") }, 8));

            Record after = client.Operate(null, key,

                Operation.Get("str"),

                Operation.Get("int"),

                Operation.Get("double"),

                Operation.Get("blob"),

                ListOperation.Size("list"),

                MapOperation.GetByKey("map", Value.Get(2), MapReturnType.VALUE),

                HLLOperation.GetCount("hll"));

            Console.WriteLine("str: " + after.GetString("str"));

            Console.WriteLine("int: " + after.GetLong("int"));

            Console.WriteLine("double: " + after.GetDouble("double"));

            Console.WriteLine("Blob: " + Convert.ToHexString((byte[])after.GetValue("blob")).ToLower());

            Console.WriteLine("List size: " + after.GetLong("list"));

            Console.WriteLine("Map value: " + after.GetLong("map"));

            Console.WriteLine("HLL count: " + after.GetLong("hll"));

            Console.WriteLine("Generation: " + after.generation);

            client.Delete(null, key);

        }

        finally

        {

            client.Close();

        }

    }

}
```

```go
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", "txnset", "txnkey")

  if err != nil {

    log.Fatal(err)

  }

  err = client.PutBins(nil, key,

    aerospike.NewBin("str", "atomic"),

    aerospike.NewBin("int", 8),

    aerospike.NewBin("double", 6.5),

    aerospike.NewBin("blob", []byte{1, 2, 3, 4, 5}),

    aerospike.NewBin("list", []int{1}),

    aerospike.NewBin("map", map[int]int{2: 4}))

  if err != nil {

    log.Fatal(err)

  }

  _, err = client.Operate(nil, key,

    aerospike.TouchOp(),

    aerospike.StrAppendOp(aerospike.DefaultStringPolicy, "str", "-operation"),

    aerospike.AddOp(aerospike.NewBin("int", 5)),

    aerospike.AddOp(aerospike.NewBin("double", -2.25)),

    aerospike.ListAppendOp("list", 5),

    aerospike.MapIncrementOp(aerospike.DefaultMapPolicy(), "map", 2, 57),

    aerospike.BitSetOp(aerospike.DefaultBitPolicy(), "blob", 13, 8, []byte{0xE0}),

    aerospike.HLLInitOp(aerospike.DefaultHLLPolicy(), "hll", 8, -1),

    aerospike.HLLAddOp(aerospike.DefaultHLLPolicy(), "hll",

      []aerospike.Value{aerospike.NewValue("a"), aerospike.NewValue("b"), aerospike.NewValue("c")}, 8, -1))

  if err != nil {

    log.Fatal(err)

  }

  after, err := client.Operate(nil, key,

    aerospike.GetBinOp("str"),

    aerospike.GetBinOp("int"),

    aerospike.GetBinOp("double"),

    aerospike.GetBinOp("blob"),

    aerospike.ListSizeOp("list"),

    aerospike.MapGetByKeyOp("map", 2, aerospike.MapReturnType.VALUE),

    aerospike.HLLGetCountOp("hll"))

  if err != nil {

    log.Fatal(err)

  }

  fmt.Println("str:", after.Bins["str"])

  fmt.Println("int:", after.Bins["int"])

  fmt.Println("double:", after.Bins["double"])

  fmt.Printf("Blob: %x\n", after.Bins["blob"])

  fmt.Println("List size:", after.Bins["list"])

  fmt.Println("Map value:", after.Bins["map"])

  fmt.Println("HLL count:", after.Bins["hll"])

  fmt.Println("Generation:", after.Generation)

  if _, err := client.Delete(nil, key); err != nil {

    log.Fatal(err)

  }

}
```

```js
import Aerospike from 'aerospike';

const { operations: op, strings, lists, maps, bitwise, hll } = Aerospike;

const client = await Aerospike.connect({ hosts: '127.0.0.1:3000' });

try {

    const key = new Aerospike.Key('test', 'txnset', 'txnkey');

    await client.put(key, {

        str: 'atomic',

        int: 8,

        double: 6.5,

        blob: Buffer.from([1, 2, 3, 4, 5]),

        list: [1],

        map: new Map([[2, 4]]),

    });

    await client.operate(key, [

        op.touch(),

        strings.append('str', '-operation'),

        op.incr('int', 5),

        op.incr('double', -2.25),

        lists.append('list', 5),

        maps.increment('map', 2, 57),

        bitwise.set('blob', 13, 8, Buffer.from([0xe0])),

        hll.init('hll', 8),

        hll.add('hll', ['a', 'b', 'c'], 8),

    ]);

    const after = await client.operate(key, [

        op.read('str'),

        op.read('int'),

        op.read('double'),

        op.read('blob'),

        lists.size('list'),

        maps.getByKey('map', 2, maps.returnType.VALUE),

        hll.getCount('hll'),

    ]);

    console.log('str:', after.bins.str);

    console.log('int:', after.bins.int);

    console.log('double:', after.bins.double);

    console.log('Blob:', after.bins.blob.toString('hex'));

    console.log('List size:', after.bins.list);

    console.log('Map value:', after.bins.map);

    console.log('HLL count:', after.bins.hll);

    console.log('Generation:', after.gen);

    await client.remove(key);

} finally {

    client.close();

}
```

```c
#include <stdio.h>

#include <aerospike/aerospike.h>

#include <aerospike/aerospike_key.h>

#include <aerospike/as_arraylist.h>

#include <aerospike/as_bit_operations.h>

#include <aerospike/as_bytes.h>

#include <aerospike/as_error.h>

#include <aerospike/as_hashmap.h>

#include <aerospike/as_hll_operations.h>

#include <aerospike/as_integer.h>

#include <aerospike/as_key.h>

#include <aerospike/as_list_operations.h>

#include <aerospike/as_map_operations.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 status = 1;

    as_record* after = NULL;

    as_key key;

    as_key_init_str(&key, "test", "txnset", "txnkey");

    uint8_t blob[] = {1, 2, 3, 4, 5};

    uint8_t bits[] = {0xE0};

    as_arraylist list;

    as_arraylist_inita(&list, 1);

    as_arraylist_append_int64(&list, 1);

    as_hashmap map;

    as_hashmap_init(&map, 1);

    as_hashmap_set(&map, (as_val*)as_integer_new(2), (as_val*)as_integer_new(4));

    as_record rec;

    as_record_inita(&rec, 6);

    as_record_set_str(&rec, "str", "atomic");

    as_record_set_int64(&rec, "int", 8);

    as_record_set_double(&rec, "double", 6.5);

    as_record_set_bytes(&rec, "blob", as_bytes_new_wrap(blob, sizeof(blob), false));

    as_record_set_list(&rec, "list", (as_list*)&list);

    as_record_set_map(&rec, "map", (as_map*)&map);

    as_status rc = aerospike_key_put(&as, &err, NULL, &key, &rec);

    as_record_destroy(&rec);

    if (rc != AEROSPIKE_OK) {

        fprintf(stderr, "Error writing record: %s\n", err.message);

        goto cleanup;

    }

    as_map_policy map_policy;

    as_map_policy_init(&map_policy);

    as_arraylist* values = as_arraylist_new(3, 0);

    as_arraylist_append_str(values, "a");

    as_arraylist_append_str(values, "b");

    as_arraylist_append_str(values, "c");

    as_operations write_ops;

    as_operations_inita(&write_ops, 9);

    as_operations_add_touch(&write_ops);

    as_operations_string_append(&write_ops, "str", NULL, NULL, "-operation");

    as_operations_add_incr(&write_ops, "int", 5);

    as_operations_add_incr_double(&write_ops, "double", -2.25);

    as_operations_list_append(&write_ops, "list", NULL, NULL, (as_val*)as_integer_new(5));

    as_operations_map_increment(&write_ops, "map", NULL, &map_policy,

        (as_val*)as_integer_new(2), (as_val*)as_integer_new(57));

    as_operations_bit_set(&write_ops, "blob", NULL, NULL, 13, 8, sizeof(bits), bits);

    as_operations_hll_init(&write_ops, "hll", NULL, NULL, 8);

    as_operations_hll_add(&write_ops, "hll", NULL, NULL, (as_list*)values, 8);

    rc = aerospike_key_operate(&as, &err, NULL, &key, &write_ops, NULL);

    as_operations_destroy(&write_ops);

    if (rc != AEROSPIKE_OK) {

        fprintf(stderr, "Error running the command: %s\n", err.message);

        goto cleanup;

    }

    as_operations read_ops;

    as_operations_inita(&read_ops, 7);

    as_operations_add_read(&read_ops, "str");

    as_operations_add_read(&read_ops, "int");

    as_operations_add_read(&read_ops, "double");

    as_operations_add_read(&read_ops, "blob");

    as_operations_list_size(&read_ops, "list", NULL);

    as_operations_map_get_by_key(&read_ops, "map", NULL, (as_val*)as_integer_new(2), AS_MAP_RETURN_VALUE);

    as_operations_hll_get_count(&read_ops, "hll", NULL);

    rc = aerospike_key_operate(&as, &err, NULL, &key, &read_ops, &after);

    as_operations_destroy(&read_ops);

    if (rc != AEROSPIKE_OK) {

        fprintf(stderr, "Error reading the results: %s\n", err.message);

        goto cleanup;

    }

    printf("str: %s\n", as_record_get_str(after, "str"));

    printf("int: %lld\n", (long long)as_record_get_int64(after, "int", 0));

    printf("double: %g\n", as_record_get_double(after, "double", 0));

    as_bytes* after_blob = as_record_get_bytes(after, "blob");

    const uint8_t* after_data = as_bytes_get(after_blob);

    printf("Blob: ");

    for (uint32_t i = 0; i < as_bytes_size(after_blob); i++) {

        printf("%02x", after_data[i]);

    }

    printf("\n");

    printf("List size: %lld\n", (long long)as_record_get_int64(after, "list", 0));

    printf("Map value: %lld\n", (long long)as_record_get_int64(after, "map", 0));

    printf("HLL count: %lld\n", (long long)as_record_get_int64(after, "hll", 0));

    printf("Generation: %d\n", after->gen);

    status = 0;

cleanup:

    if (after != NULL) {

        as_record_destroy(after);

    }

    aerospike_key_remove(&as, &err, NULL, &key);

    as_key_destroy(&key);

    aerospike_close(&as, &err);

    aerospike_destroy(&as);

    return status;

}
```

```java
import java.util.HexFormat;

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.Value;

import com.aerospike.client.cdt.ListOperation;

import com.aerospike.client.cdt.MapOperation;

import com.aerospike.client.cdt.MapPolicy;

import com.aerospike.client.cdt.MapReturnType;

import com.aerospike.client.operation.BitOperation;

import com.aerospike.client.operation.BitPolicy;

import com.aerospike.client.operation.HLLOperation;

import com.aerospike.client.operation.HLLPolicy;

import com.aerospike.client.operation.StringOperation;

import com.aerospike.client.operation.StringPolicy;

public class IntroToTransactions {

    public static void main(String[] args) {

        try (AerospikeClient client = new AerospikeClient("127.0.0.1", 3000)) {

            Key key = new Key("test", "txnset", "txnkey");

            client.put(null, key,

                new Bin("str", "atomic"),

                new Bin("int", 8),

                new Bin("double", 6.5),

                new Bin("blob", new byte[] {1, 2, 3, 4, 5}),

                new Bin("list", List.of(1)),

                new Bin("map", Map.of(2, 4)));

            client.operate(null, key,

                Operation.touch(),

                StringOperation.append(StringPolicy.Default, "str", "-operation"),

                Operation.add(new Bin("int", 5)),

                Operation.add(new Bin("double", -2.25)),

                ListOperation.append("list", Value.get(5)),

                MapOperation.increment(MapPolicy.Default, "map", Value.get(2), Value.get(57)),

                BitOperation.set(BitPolicy.Default, "blob", 13, 8, new byte[] {(byte) 0xE0}),

                HLLOperation.init(HLLPolicy.Default, "hll", 8),

                HLLOperation.add(HLLPolicy.Default, "hll", List.of(Value.get("a"), Value.get("b"), Value.get("c")), 8));

            Record after = client.operate(null, key,

                Operation.get("str"),

                Operation.get("int"),

                Operation.get("double"),

                Operation.get("blob"),

                ListOperation.size("list"),

                MapOperation.getByKey("map", Value.get(2), MapReturnType.VALUE),

                HLLOperation.getCount("hll"));

            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);

            client.delete(null, key);

        }

    }

}
```

```python
import sys

import aerospike

from aerospike import exception as ex

from aerospike_helpers.operations import bitwise_operations, hll_operations, list_operations, map_operations, 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", "txnset", "txnkey")

    client.put(key, {

        "str": "atomic",

        "int": 8,

        "double": 6.5,

        "blob": bytes([1, 2, 3, 4, 5]),

        "list": [1],

        "map": {2: 4},

    })

    client.operate(key, [

        operations.touch(),

        string_operations.append("str", "-operation"),

        operations.increment("int", 5),

        operations.increment("double", -2.25),

        list_operations.list_append("list", 5),

        map_operations.map_increment("map", 2, 57),

        bitwise_operations.bit_set("blob", 13, 8, 1, bytes([0xE0])),

        hll_operations.hll_init("hll", 8),

        hll_operations.hll_add("hll", ["a", "b", "c"], 8),

    ])

    (_, meta, after) = client.operate(key, [

        operations.read("str"),

        operations.read("int"),

        operations.read("double"),

        operations.read("blob"),

        list_operations.list_size("list"),

        map_operations.map_get_by_key("map", 2, aerospike.MAP_RETURN_VALUE),

        hll_operations.hll_get_count("hll"),

    ])

    print("str:", after["str"])

    print("int:", after["int"])

    print("double:", after["double"])

    print("Blob:", after["blob"].hex())

    print("List size:", after["list"])

    print("Map value:", after["map"])

    print("HLL count:", after["hll"])

    print("Generation:", meta["gen"])

    client.remove(key)

except ex.AerospikeError as e:

    print(f"Error: {e}", file=sys.stderr)

    sys.exit(1)

finally:

    client.close()
```

```text
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

-   Update a record only if no one else has changed it, with the [Read-write transactions](https://aerospike.com/docs/develop/tutorials/intro/read-modify-write) tutorial.
-   Learn more about multi-record transactions in [Transactions](https://aerospike.com/docs/database/learn/architecture/transactions).
-   Learn how the Developer SDKs chain operations in [Update records](https://aerospike.com/docs/develop/client/sdk/usage/update).
-   Learn how the other clients run multiple operations in one command: [Java](https://aerospike.com/docs/develop/client/java/usage/atomic/multi), [Python](https://aerospike.com/docs/develop/client/python/usage/atomic/multi), [Rust](https://aerospike.com/docs/develop/client/rust/usage/atomic/multi), [C#](https://aerospike.com/docs/develop/client/csharp/usage/atomic/multi), [Go](https://aerospike.com/docs/develop/client/go/usage/atomic/multi), [Node.js](https://aerospike.com/docs/develop/client/node/usage/atomic/multi), or [C](https://aerospike.com/docs/develop/client/c/usage/atomic/multi).
-   Run more of the Java tutorials, which use the legacy Java client: [Queries and UDFs](https://aerospike.com/docs/develop/tutorials/queries/query-udf-java), [Reading and updating lists](https://aerospike.com/docs/develop/tutorials/cdt/working-with-lists-java), [Modeling with lists](https://aerospike.com/docs/develop/tutorials/data-modeling/modeling-with-lists-java), and [Reading and updating maps](https://aerospike.com/docs/develop/tutorials/cdt/working-with-maps-java).
-   Process more records at once with [scans](https://aerospike.com/docs/develop/learn/queries/primary-index) and [batches](https://aerospike.com/docs/develop/learn/batch).