---
title: "Batch operations"
description: "Batch read, write, upsert, and delete operations with the Aerospike Developer SDK in Java and Python."
---

# Batch operations

> For the complete documentation index see: [llms.txt](https://aerospike.com/docs/llms.txt)
> 
> All documentation pages available in markdown.

## Applies to

-   Aerospike Developer SDK (Java 21+ and Python 3.11+)
-   Aerospike Database 8.2.0 or later, unless a section states otherwise

::: code examples
Examples assume a connected `session` from [Connect to Aerospike](https://aerospike.com/docs/develop/client/sdk/connect). Each usage guide lists shared imports in a tabbed block near the top of the page; snippet blocks add imports only for types not already shown. The first code block in each section includes dataset setup; later blocks in that section reuse those values. When a page includes a **Complete example** section, that block is fully self-contained.
:::

Learn how to perform multiple database operations efficiently in a single network request. Batch operations reduce latency and improve throughput when working with multiple records.

Except where noted, snippets on this page use the imports below. A snippet lists additional `import` lines only when it needs a type not shown here. When this page includes a **Complete example** section, that block is fully self-contained with every import required to run it.

-   [Java](#tab-panel-5368)
-   [Python](#tab-panel-5369)

```java
import com.aerospike.client.sdk.DataSet;

import com.aerospike.client.sdk.ErrorStrategy;

import com.aerospike.client.sdk.IdValuesRowBuilder;

import com.aerospike.client.sdk.Record;

import com.aerospike.client.sdk.RecordResult;

import com.aerospike.client.sdk.RecordStream;

import java.util.List;
```

```python
import time

from aerospike_sdk import DataSet, ErrorStrategy
```

## Why use batch operations?

| Approach | 100 Records | Network Roundtrips |
| --- | --- | --- |
| Individual operations | ~100ms+ | 100 |
| Batch operation | ~5-10ms | 1 |

Batch operations send multiple requests in a single network call, as well as sending requests to multiple servers concurrently, dramatically reducing latency.

## Two kinds of batch

Batch commands come in two shapes, and which one you need depends on whether every key gets the same thing.

**One operation applied to many keys.** Pass a key list to the ordinary command and it runs once against every key in the list. The operation and its arguments are identical for all of them. This covers reads, deletes, existence checks, touches, UDF calls, and writes where every record gets the same bin values.

| Command | What it does to every key in the list |
| --- | --- |
| `query(keys)` | Reads the records |
| `exists(keys)` | Reports whether each record exists |
| `delete(keys)` | Deletes the records |
| `touch(keys)` | Resets the time to expiration |
| `insert(keys)` / `update(keys)` / `upsert(keys)` / `replace(keys)` | Applies the same bin values to each record |
| `executeUdf(keys)` | Runs the same function with the same arguments |

**A different payload per key.** When each record needs its own values, name the data set instead of a key list and supply one row per key. This is the batch-write shape, and it is what the legacy clients called a batch write.

-   [Java](#tab-panel-5370)
-   [Python](#tab-panel-5371)

```java
DataSet users = DataSet.of("test", "users");

// One operation, many keys: every record gets tier="gold".

session.upsert(users.ids("user-1", "user-2", "user-3"))

    .bin("tier").setTo("gold")

    .execute();

// A different payload per key, still one request.

session.upsert(users)

    .bins("name", "score")

    .id("user-1").values("Alice", 10)

    .id("user-2").values("Bob",   20)

    .id("user-3").values("Carol", 30)

    .execute();
```

```python
users = DataSet.of("test", "users")

# One operation, many keys: every record gets tier="gold".

await session.upsert(users.ids("user-1", "user-2", "user-3")).put({"tier": "gold"}).execute()

# A different payload per key, still one request.

await (

    session.upsert(users)

    .bins("name", "score")

    .row("user-1", "Alice", 10)

    .row("user-2", "Bob", 20)

    .row("user-3", "Carol", 30)

    .execute()

)
```

> 📖 **API reference**: [`Session.upsert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.upsert) | [`DataSetWriteBuilder.bins()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/row-write.html#aerospike%5Fsdk.aio.operations.query.DataSetWriteBuilder.bins) | [`RowWriteBuilder.row()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/row-write.html#aerospike%5Fsdk.aio.operations.query.RowWriteBuilder.row) | [`RowWriteBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/row-write.html#aerospike%5Fsdk.aio.operations.query.RowWriteBuilder.execute)

## Batch read

Read multiple records in one request:

-   [Java](#tab-panel-5372)
-   [Python](#tab-panel-5373)

```java
DataSet users = DataSet.of("test", "users");

RecordStream result = session.query(users.ids("user-1", "user-2", "user-3"))

    .execute();

// Get all records

List<Record> records = new java.util.ArrayList<>();

result.forEach(rr -> {

    if (rr.isOk()) {

        records.add(rr.recordOrThrow());

    }

});

for (Record record : records) {

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

}

// Or access by index

Record first = records.get(0);  // user-1

Record second = records.get(1); // user-2
```

> 📖 **API reference**: [`DataSet.of(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#of%28java.lang.String%2Cjava.lang.String%29) | [`DataSet.ids(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#ids%28java.lang.String...%29) | [`Session.query(List)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#query%28java.util.List%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29) | [`RecordStream.forEach(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordStream.html#forEach%28java.util.function.Consumer%29) | [`RecordResult.isOk()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#isOk%28%29) | [`RecordResult.recordOrThrow()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#recordOrThrow%28%29) | [`Record.getString(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Record.html#getString%28java.lang.String%29)

```python
users = DataSet.of("test", "users")

stream = await session.query(users.ids("user-1", "user-2", "user-3")).execute()

# Get all records

records = []

async for rr in stream:

    if rr.is_ok:

        records.append(rr.record_or_raise())

stream.close()

for record in records:

    print(f"Name: {record.bins['name']}")

# Or access by index

first = records[0]   # user-1

second = records[1]  # user-2
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`DataSet.ids()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.ids) | [`Session.query()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.query) | [`QueryBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.execute) | [`RecordResult.is_ok`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.is%5Fok) | [`RecordResult.record_or_raise()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.record%5For%5Fraise) | [`RecordStream.close()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-stream.html#aerospike%5Fsdk.record%5Fstream.RecordStream.close)

## Batch write

Create or update multiple records:

-   [Java](#tab-panel-5374)
-   [Python](#tab-panel-5375)

```java
DataSet users = DataSet.of("test", "users");

session.insert(users)

    .bins("name", "email")

    .id("user-1").values("Alice", "alice@example.com")

    .id("user-2").values("Bob", "bob@example.com")

    .id("user-3").values("Carol", "carol@example.com")

    .execute();
```

> 📖 **API reference**: [`Session.insert(DataSet)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#insert%28com.aerospike.client.sdk.DataSet%29) | [`OperationObjectBuilder.bins(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/OperationObjectBuilder.html#bins%28java.lang.String%2Cjava.lang.String...%29) | [`IdValuesBuilder.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesBuilder.html#id%28java.lang.String%29) | [`IdValuesRowBuilder.values(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesRowBuilder.html#values%28java.lang.Object...%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29)

::: integer keys
`DataSet.id()` and `DataSet.ids()` have `int` and `long` overloads as well as `String` and `byte[]`. Pass the number directly when you need integer keys (such as `users.id(42)`), not `users.id("42")`. Integer and string keys are distinct in Aerospike. A read with an integer key does not find a record written with a string key, and a read with a string key does not find a record written with an integer key.

```java
// String key           → Aerospike key type: String

users.id("42");

// Integer key          → Aerospike key type: Integer

users.id(42);

// Several integer keys in one call

List<Key> keys = users.ids(1, 2, 3);

RecordStream result = session.query(keys).execute();
```

> 📖 **API reference**: [`DataSet.id(int)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#id%28int%29) | [`DataSet.id(long)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#id%28long%29) | [`DataSet.ids(int...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#ids%28int...%29) | [`DataSet.ids(long...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#ids%28long...%29)
:::

```python
users = DataSet.of("test", "users")

await (

    session.insert(users)

    .bins("name", "email")

    .row("user-1", "Alice", "alice@example.com")

    .row("user-2", "Bob", "bob@example.com")

    .row("user-3", "Carol", "carol@example.com")

    .execute()

)
```

> 📖 **API reference**: [`Session.insert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.insert) | [`DataSetWriteBuilder.bins()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/row-write.html#aerospike%5Fsdk.aio.operations.query.DataSetWriteBuilder.bins) | [`RowWriteBuilder.row()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/row-write.html#aerospike%5Fsdk.aio.operations.query.RowWriteBuilder.row) | [`RowWriteBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/row-write.html#aerospike%5Fsdk.aio.operations.query.RowWriteBuilder.execute)

`bins(...)` fixes the column schema once; each `row(id, *values)` supplies one record’s ID and values in that order, and chains back to itself so more rows can follow.

::: integer keys
`DataSet.id()` accepts any Python value, string or integer. Pass an `int` directly when you need integer keys (such as `users.id(42)`), not `users.id(str(42))`. Integer and string keys are distinct in Aerospike, so reads using integer keys will not find records written with string keys and vice versa.

```python
# String key           → Aerospike key type: String

users.id("42")

# Integer key          → Aerospike key type: Integer

users.id(42)
```

When looping over a numeric range, pass the integer directly:

```python
await (

    session.upsert(users)

    .bins("name")

    .rows((i, f"User {i}") for i in range(1, 101))

    .execute()

)
```
:::

## Batch upsert

Insert or update multiple records:

-   [Java](#tab-panel-5376)
-   [Python](#tab-panel-5377)

```java
DataSet users = DataSet.of("test", "users");

session

    .upsert(users.ids("user-1","user-2"))

        .bin("status").setTo("active")

        .bin("balance").add(500)

    .upsert(users.id("user-3"))

        .bin("status").setTo("inactive")

    .execute();
```

> 📖 **API reference**: [`DataSet.ids(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#ids%28java.lang.String...%29) | [`DataSet.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#id%28java.lang.String%29) | [`ChainableQueryBuilder.bin(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#bin%28java.lang.String%29) | [`BinBuilder.add(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/BinBuilder.html#add%28int%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29)

```python
users = DataSet.of("test", "users")

stream = await (

    session

    .upsert(users.ids("user-1", "user-2"))

        .bin("status").set_to("active")

        .bin("balance").add(500)

    .upsert(users.id("user-3"))

        .bin("status").set_to("inactive")

    .execute()

)

stream.close()
```

> 📖 **API reference**: [`DataSet.ids()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.ids) | [`DataSet.id()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.id) | [`Session.upsert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.upsert) | [`WriteSegmentBuilder.bin()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.bin) | [`WriteSegmentBuilder.upsert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.upsert) | [`WriteSegmentBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.execute)

This chains two separate `upsert(...)` calls onto one builder. It is the same “one op for many keys, then another op for a different key” shape as [Mixed batch operations](#mixed-batch-operations) below, not the `bins(...).row(...)` tabular shape, since every key in each group shares the same bin operations.

## Batch delete

Delete multiple records:

-   [Java](#tab-panel-5378)
-   [Python](#tab-panel-5379)

```java
DataSet users = DataSet.of("test", "users");

RecordStream result = session.delete(users.ids("user-1", "user-2", "user-3"))

    .execute();

// Check which deletes succeeded

int i = 0;

while (result.hasNext()) {

    RecordResult rr = result.next();

    System.out.println("Record " + i++ + " deleted: " + rr.asBoolean());

}

result.close();
```

> 📖 **API reference**: [`DataSet.ids(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#ids%28java.lang.String...%29) | [`Session.delete(List)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#delete%28java.util.List%29) | [`Session.delete(Key)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#delete%28com.aerospike.client.sdk.Key%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29) | [`RecordStream.hasNext()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordStream.html#hasNext%28%29) | [`RecordStream.next()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordStream.html#next%28%29) | [`RecordStream.close()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordStream.html#close%28%29)

```python
users = DataSet.of("test", "users")

stream = await session.delete(users.ids("user-1", "user-2", "user-3")).execute()

# Check which deletes succeeded

async for rr in stream:

    print(f"Record {rr.index} deleted: {rr.as_bool()}")

stream.close()
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`DataSet.ids()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.ids) | [`Session.delete()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.delete) | [`WriteSegmentBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.execute) | [`RecordResult.index`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.index) | [`RecordResult.as_bool()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.as%5Fbool) | [`RecordStream.close()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-stream.html#aerospike%5Fsdk.record%5Fstream.RecordStream.close)

## Batch exists

Check whether several records exist, without reading their bins:

-   [Java](#tab-panel-5380)
-   [Python](#tab-panel-5381)

```java
DataSet users = DataSet.of("test", "users");

RecordStream result = session.exists(users.ids("user-1", "user-2", "user-3")).execute();

while (result.hasNext()) {

    RecordResult rr = result.next();

    System.out.println(rr.getKey().userKey + " exists: " + rr.asBoolean());

}

result.close();
```

```python
users = DataSet.of("test", "users")

stream = await session.exists(users.ids("user-1", "user-2", "user-3")).execute()

async for rr in stream:

    print(f"{rr.key.value} exists: {rr.as_bool()}")

stream.close()
```

::: a missing record produces no row
By default, a batch `exists` returns a row only for keys that are present (a single-key `exists` always returns its row). Ask about three keys where one is missing and you get two rows, both `true` — not three rows with one `false`. Match each row by its own key rather than by its index, and treat any key absent from the results as a record that does not exist. To get a `false` row for every missing key instead, call `includeMissingKeys()` in Java or `include_missing_keys()` in Python before `execute()`.
:::

## Batch touch

Reset the time to expiration on several records at once, without changing their bins:

-   [Java](#tab-panel-5382)
-   [Python](#tab-panel-5383)

```java
DataSet users = DataSet.of("test", "users");

session.touch(users.ids("user-1", "user-2", "user-3")).execute();
```

```python
users = DataSet.of("test", "users")

await session.touch(users.ids("user-1", "user-2", "user-3")).execute()
```

Touch cannot create a record, because the server deletes empty records. The command fails for any key that does not exist. See [Set time-to-live (TTL)](https://aerospike.com/docs/develop/client/sdk/usage/create#set-time-to-live-ttl) for how the expiration is derived.

## Mixed batch operations

Combine different operation types in one call. Note that the operations on each key are performed asynchronously across the nodes in the cluster, and hence the returned results may not be in the same order as the commands. Each returned item exposes a key and an index — `getKey()` and `getIndex()` in Java, the `key` and `index` attributes in Python (`row.key`, `row.index`). `key` is the unique key of the record and `index` is the zero-based index of the command in the original list.

-   [Java](#tab-panel-5384)
-   [Python](#tab-panel-5385)

```java
DataSet users = DataSet.of("test", "users");

RecordStream stream = session

    .query(users.ids("user-1", "user-2"))

    .upsert(users.id("user-3"))

        .bin("status").setTo("active")

    .delete(users.id("user-4"))

    .execute();

stream.forEach(result -> {

    switch (result.getIndex()) {

        case 0 -> handleUser1(result);

        case 1 -> handleUser2(result);

        case 2 -> System.out.println("Upsert: " + (result.isOk() ? "ok" : result.getMessage()));

        case 3 -> System.out.println("Delete: " + (result.isOk() ? "ok" : result.getMessage()));

    }

});
```

> 📖 **API reference**: [`DataSet.ids(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#ids%28java.lang.String...%29) | [`DataSet.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#id%28java.lang.String%29) | [`ChainableQueryBuilder.bin(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#bin%28java.lang.String%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29) | [`RecordStream.forEach(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordStream.html#forEach%28java.util.function.Consumer%29) | [`RecordResult.isOk()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#isOk%28%29)

```python
users = DataSet.of("test", "users")

stream = await (

    session.query(users.ids("user-1", "user-2"))

    .upsert(users.id("user-3")).bin("status").set_to("active")

    .delete(users.id("user-4"))

    .execute()

)

async for row in stream:

    match row.index:

        case 0: handle_user1(row)

        case 1: handle_user2(row)

        case 2: print(f"Upsert: {'ok' if row.is_ok else row.to_exception()}")

        case 3: print(f"Delete: {'ok' if row.is_ok else row.to_exception()}")

stream.close()
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`DataSet.id()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.id) | [`DataSet.ids()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.ids) | [`Session.query()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.query) | [`RecordResult.index`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.index) | [`RecordResult.is_ok`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.is%5Fok) | [`RecordStream.close()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-stream.html#aerospike%5Fsdk.record%5Fstream.RecordStream.close)

## Batch with selected bins

Read only specific bins in batch:

-   [Java](#tab-panel-5386)
-   [Python](#tab-panel-5387)

```java
DataSet users = DataSet.of("test", "users");

RecordStream result = session.query(users.ids("user-1", "user-2", "user-3"))

    .readingOnlyBins("name", "email")

    .execute();
```

> 📖 **API reference**: [`DataSet.ids(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#ids%28java.lang.String...%29) | [`Session.query(List)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#query%28java.util.List%29) | [`ChainableQueryBuilder.readingOnlyBins(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#readingOnlyBins%28java.lang.String...%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29)

```python
users = DataSet.of("test", "users")

stream = await (

    session.query(users.ids("user-1", "user-2", "user-3"))

    .bins(["name", "email"])

    .execute()

)
```

> 📖 **API reference**: [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`DataSet.ids()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.ids) | [`Session.query()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.query) | [`QueryBuilder.bins()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.bins) | [`QueryBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/query.html#aerospike%5Fsdk.aio.operations.query.QueryBuilder.execute)

## Handle partial failures

Some operations in a batch may fail while others succeed:

-   [Java](#tab-panel-5388)
-   [Python](#tab-panel-5389)

```java
DataSet users = DataSet.of("test", "users");

RecordStream result = session

    .update(users.ids("user-1", "nonexistent", "user-3"))

    .bin("lastSeen").setTo(System.currentTimeMillis())

    .execute(ErrorStrategy.IN_STREAM);  // Place errors in the RecordStream

result.forEach(rr -> {

    String keyId = rr.getKey().userKey.toString();

    if (!rr.isOk()) {

        System.out.println(keyId + " failed: " + rr.getMessage());

    } else {

        System.out.println(keyId + ": updated");

    }

});
```

> 📖 **API reference**: [`DataSet.ids(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#ids%28java.lang.String...%29) | [`ChainableQueryBuilder.bin(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#bin%28java.lang.String%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29) | [`RecordStream.forEach(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordStream.html#forEach%28java.util.function.Consumer%29) | [`RecordResult.isOk()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#isOk%28%29) | [`ErrorStrategy`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ErrorStrategy.html) | [`ErrorStrategy.IN_STREAM`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ErrorStrategy.html#IN_STREAM)

```python
import time

users = DataSet.of("test", "users")

stream = await (

    session.update(users.ids("user-1", "nonexistent", "user-3"))

    .bin("lastSeen").set_to(int(time.time() * 1000))

    .execute(on_error=ErrorStrategy.IN_STREAM)  # Place errors in the RecordStream

)

async for rr in stream:

    key_id = rr.key.value

    if not rr.is_ok:

        print(f"{key_id} failed: {rr.to_exception()}")

    else:

        print(f"{key_id}: updated")

stream.close()
```

> 📖 **API reference**: [`DataSet.ids()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.ids) | [`Session.update()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.update) | [`WriteSegmentBuilder.bin()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.bin) | [`WriteSegmentBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.execute) | [`ErrorStrategy`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/error-strategy.html#aerospike%5Fsdk.error%5Fstrategy.ErrorStrategy) | [`RecordResult.is_ok`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.is%5Fok) | [`RecordResult.to_exception()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.to%5Fexception) | [`RecordStream.close()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-stream.html#aerospike%5Fsdk.record%5Fstream.RecordStream.close)

`ErrorStrategy.IN_STREAM` is already the default for batch commands. It’s shown explicitly here to match the Java tab; omitting `on_error` behaves the same way. `ErrorStrategy` is importable from `aerospike_sdk.error_strategy`.

## Dynamic batch building

Build batches programmatically:

-   [Java](#tab-panel-5390)
-   [Python](#tab-panel-5391)

```java
DataSet users = DataSet.of("test", "users");

IdValuesRowBuilder rows = session.upsert(users)

    .bins("name", "score")

    .id("user-1").values("User 1", 10);

for (int id = 2; id <= 50; id++) {

    rows.id("user-" + id).values("User " + id, id * 10);

}

rows.execute();
```

> 📖 **API reference**: [`DataSet.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#id%28java.lang.String%29) | [`Session.upsert(DataSet)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#upsert%28com.aerospike.client.sdk.DataSet%29) | [`OperationObjectBuilder.bins(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/OperationObjectBuilder.html#bins%28java.lang.String%2Cjava.lang.String...%29) | [`IdValuesBuilder.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesBuilder.html#id%28java.lang.String%29) | [`IdValuesRowBuilder.values(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesRowBuilder.html#values%28java.lang.Object...%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29)

```python
users = DataSet.of("test", "users")

rows = (

    session.upsert(users)

    .bins("name", "score")

    .row("user-1", "User 1", 10)

)

for id in range(2, 51):

    rows.row(f"user-{id}", f"User {id}", id * 10)

await rows.execute()
```

> 📖 **API reference**: [`Session.upsert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.upsert) | [`DataSetWriteBuilder.bins()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/row-write.html#aerospike%5Fsdk.aio.operations.query.DataSetWriteBuilder.bins) | [`RowWriteBuilder.row()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/row-write.html#aerospike%5Fsdk.aio.operations.query.RowWriteBuilder.row) | [`RowWriteBuilder.execute()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/row-write.html#aerospike%5Fsdk.aio.operations.query.RowWriteBuilder.execute)

`row(...)` returns the same builder, so it chains into a loop just like the Java `IdValuesRowBuilder`. Call `.execute()` once, after every row has been added.

## Complete example

This example is self-contained—it lists every import needed to run standalone.

-   [Java](#tab-panel-5392)
-   [Python](#tab-panel-5393)

```java
import com.aerospike.client.sdk.Cluster;

import com.aerospike.client.sdk.ClusterDefinition;

import com.aerospike.client.sdk.DataSet;

import com.aerospike.client.sdk.Record;

import com.aerospike.client.sdk.RecordResult;

import com.aerospike.client.sdk.RecordStream;

import com.aerospike.client.sdk.Session;

import com.aerospike.client.sdk.policy.Behavior;

public class BatchOperationsExample {

    public static void main(String[] args) {

        try (Cluster cluster = new ClusterDefinition("localhost", 3000).connect()) {

            Session session = cluster.createSession(Behavior.DEFAULT);

            DataSet users = DataSet.of("test", "users");

            String key1 = "batch-example-1";

            String key2 = "batch-example-2";

            String key3 = "batch-example-3";

            // Cleanup so the example is repeatable.

            session.delete(users.ids(key1, key2, key3)).execute().close();

            // Batch insert

            session.insert(users)

                .bins("name", "age")

                .id(key1).values("Alice", 28)

                .id(key2).values("Bob", 35)

                .id(key3).values("Carol", 22)

                .execute();

            System.out.println("Batch insert complete");

            // Batch read

            try (RecordStream readStream = session.query(users.ids(key1, key2, key3)).execute()) {

                readStream.forEach(result -> {

                    Record record = result.recordOrThrow();

                    System.out.println("  - " + record.getString("name"));

                });

            }

            // Batch update

            session

                .upsert(users.id(key1), users.id(key2))

                    .bin("status").setTo("active")

                .upsert(users.id(key3))

                    .bin("status").setTo("inactive")

                .execute().close();

            System.out.println("\nBatch update complete");

            // Batch delete

            session.delete(users.ids(key1, key2, key3))

                .execute().close();

            System.out.println("Batch delete complete");

        }

    }

}
```

> 📖 **API reference**: [`ClusterDefinition(String,int)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ClusterDefinition.html#%3Cinit%3E%28java.lang.String%2Cint%29) | [`ClusterDefinition.connect()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ClusterDefinition.html#connect%28%29) | [`Cluster.createSession(Behavior)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Cluster.html#createSession%28com.aerospike.client.sdk.policy.Behavior%29) | [`Cluster.close()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Cluster.html#close%28%29) | [`DataSet.of(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#of%28java.lang.String%2Cjava.lang.String%29) | [`DataSet.ids(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/DataSet.html#ids%28java.lang.String...%29) | [`Session.insert(DataSet)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#insert%28com.aerospike.client.sdk.DataSet%29) | [`Session.delete(List)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#delete%28java.util.List%29) | [`Session.delete(Key)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#delete%28com.aerospike.client.sdk.Key%29) | [`Session.query(List)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Session.html#query%28java.util.List%29) | [`OperationObjectBuilder.bins(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/OperationObjectBuilder.html#bins%28java.lang.String%2Cjava.lang.String...%29) | [`IdValuesBuilder.id(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesBuilder.html#id%28java.lang.String%29) | [`IdValuesRowBuilder.values(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/IdValuesRowBuilder.html#values%28java.lang.Object...%29) | [`ChainableQueryBuilder.bin(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#bin%28java.lang.String%29) | [`ChainableQueryBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableQueryBuilder.html#execute%28%29) | [`ChainableNoBinsBuilder.execute()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/ChainableNoBinsBuilder.html#execute%28%29) | [`RecordStream.forEach(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordStream.html#forEach%28java.util.function.Consumer%29) | [`RecordStream.close()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordStream.html#close%28%29) | [`RecordResult.recordOrThrow()`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/RecordResult.html#recordOrThrow%28%29) | [`Record.getString(...)`](https://javadoc.io/doc/com.aerospike/aerospike-client-sdk/latest/com/aerospike/client/sdk/Record.html#getString%28java.lang.String%29)

```python
import asyncio

from aerospike_sdk import Behavior, ClusterDefinition, DataSet

async def main():

    async with ClusterDefinition("localhost", 3000).connect() as cluster:

        session = cluster.create_session(Behavior.DEFAULT)

        users = DataSet.of("test", "users")

        key1 = "batch-example-1"

        key2 = "batch-example-2"

        key3 = "batch-example-3"

        # Cleanup so the example is repeatable.

        stream = await session.delete(users.ids(key1, key2, key3)).execute()

        stream.close()

        # Batch insert

        stream = await (

            session.insert(users)

            .bins("name", "age")

            .row(key1, "Alice", 28)

            .row(key2, "Bob", 35)

            .row(key3, "Carol", 22)

            .execute()

        )

        stream.close()

        print("Batch insert complete")

        # Batch read

        stream = await session.query(users.ids(key1, key2, key3)).execute()

        async for result in stream:

            record = result.record_or_raise()

            print(f"  - {record.bins['name']}")

        stream.close()

        # Batch update

        stream = await (

            session

            .upsert(users.id(key1), users.id(key2))

                .bin("status").set_to("active")

            .upsert(users.id(key3))

                .bin("status").set_to("inactive")

            .execute()

        )

        stream.close()

        print("\nBatch update complete")

        # Batch delete

        stream = await session.delete(users.ids(key1, key2, key3)).execute()

        stream.close()

        print("Batch delete complete")

if __name__ == "__main__":

    asyncio.run(main())
```

> 📖 **API reference**: [`ClusterDefinition`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/cluster-definition.html#aerospike%5Fsdk.aio.cluster%5Fdefinition.ClusterDefinition) | [`Cluster.create_session()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/cluster.html#aerospike%5Fsdk.aio.cluster.Cluster.create%5Fsession) | [`DataSet.of()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.of) | [`DataSet.ids()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.ids) | [`DataSet.id()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/dataset.html#aerospike%5Fsdk.dataset.DataSet.id) | [`Session.insert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.insert) | [`Session.upsert()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.upsert) | [`Session.delete()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.delete) | [`Session.query()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/session.html#aerospike%5Fsdk.aio.session.Session.query) | [`DataSetWriteBuilder.bins()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/row-write.html#aerospike%5Fsdk.aio.operations.query.DataSetWriteBuilder.bins) | [`RowWriteBuilder.row()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/row-write.html#aerospike%5Fsdk.aio.operations.query.RowWriteBuilder.row) | [`WriteSegmentBuilder.bin()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/write-segment.html#aerospike%5Fsdk.aio.operations.query.WriteSegmentBuilder.bin) | [`RecordResult.record_or_raise()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-result.html#aerospike%5Fsdk.record%5Fresult.RecordResult.record%5For%5Fraise) | [`RecordStream.close()`](https://aerospike-python-sdk.readthedocs.io/en/latest/api/record-stream.html#aerospike%5Fsdk.record%5Fstream.RecordStream.close)

## API reference summary

| Java | Python | Description |
| --- | --- | --- |
| `session.query(dataSet.ids(...))` | `await session.query(data_set.ids(...)).execute()` | Batch-read multiple record IDs |
| `session.insert(dataSet)` + repeated `.id().values()` | `session.insert(data_set).bins(...)` + repeated `.row(...)` | Batch insert with one request |
| `session.upsert(dataSet)` + repeated `.id().values()` | `session.upsert(data_set).bins(...)` + repeated `.row(...)` | Batch upsert with one request |
| `session.delete(dataSet.ids(...))` | `await session.delete(data_set.ids(...)).execute()` | Batch delete multiple IDs |
| `.readingOnlyBins(...)` (varargs) | `.bins(...)` (varargs or a list) | Select projected bins for batch reads |
| `RecordStream` / `forEach` | `RecordStream` / `async for` | Iterate per-record results |

## Next steps

Async Operations

Non-blocking operations for high throughput.

[Async Operations →](https://aerospike.com/docs/develop/client/sdk/usage/async)

Query Records

Find records with DSL queries.

[Query Records →](https://aerospike.com/docs/develop/client/sdk/usage/query)

Behaviors

Configure batch timeouts and retries.

[Behaviors →](https://aerospike.com/docs/develop/client/sdk/concepts/behaviors)