---
title: "Batched commands"
description: "Master Aerospike Java client batched commands for efficient batch reads, writes, deletes, and multi-operation requests."
---

# Batched commands

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

Jump to the [Code block](#code-block) for a combined complete example.

[Batched commands](https://aerospike.com/docs/develop/learn/batch) execute against multiple records issued as a single request. Batch reads support `get`, `exists`, `getHeader`, and `operate` requests. Batch writes, introduced in Aerospike 6.0.0, allow write requests against any keys, including updates, deletes, UDFs, and multi-operation `operate` commands.

## Setup

The following examples will use the setup and record structure below to illustrate batch operations in an Aerospike database.

```java
import com.aerospike.client.AerospikeClient;

import com.aerospike.client.BatchDelete;

import com.aerospike.client.BatchRead;

import com.aerospike.client.BatchRecord;

import com.aerospike.client.BatchResults;

import com.aerospike.client.BatchWrite;

import com.aerospike.client.Bin;

import com.aerospike.client.Key;

import com.aerospike.client.Operation;

import com.aerospike.client.Record;

import com.aerospike.client.Value;

import com.aerospike.client.cdt.MapOperation;

import com.aerospike.client.cdt.MapPolicy;

import com.aerospike.client.cdt.MapReturnType;

import com.aerospike.client.exp.Exp;

import com.aerospike.client.exp.ExpOperation;

import com.aerospike.client.exp.ExpReadFlags;

import com.aerospike.client.exp.ExpWriteFlags;

import com.aerospike.client.exp.Expression;

import com.aerospike.client.exp.ListExp;

import com.aerospike.client.exp.MapExp;

import com.aerospike.client.policy.BatchPolicy;

import com.aerospike.client.policy.BatchWritePolicy;

import java.util.Arrays;

import java.util.List;

// Establishes a connection to the server

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

The record structure:

```asciidoc
Occurred: Integer

Reported: Integer

Posted: Integer

Report: Map

{

    shape: List,

    summary: String,

    city: String,

    state: String,

    duration: String

}

Location: GeoJSON
```

## Policies

Policies are defined for the batch parent policy as well as batch read, batch write, batch delete, and batch UDF operations. [Filter Expressions](https://aerospike.com/docs/develop/client/java/usage/atomic/expressions) can be defined within each type of batch operation policy and the batch parent policy, along with other operation specific policies.

```java
// Create a new batch policy

BatchPolicy batchPolicy = new BatchPolicy();

batchPolicy.filterExp = Exp.build(

    // An example that will always return true

    Exp.gt(Exp.val(2), Exp.val(1))

);

// Create the batch write policy

BatchWritePolicy batchWritePolicy = new BatchWritePolicy();

batchWritePolicy.filterExp = Exp.build(

    // An example that will always return true

    Exp.gt(Exp.val(2), Exp.val(1))

);
```

## Requests

### Exists

The following example creates an array of ten keys and checks for their existence in the database.

```java
// Create batch of keys

Key[] keys = new Key[10];

for (int i = 0; i < 10; i++) {

    keys[i] = new Key("sandbox", "ufodata", (i + 4995));

}

// Check if records exist

boolean[] exists = client.exists(batchPolicy, keys);

for (int i = 0; i < exists.length; i++){

    if(!exists[i]){

        // Do something

        System.out.format("Key: %s does not exist\\n", keys[i].userKey);

    }

}

// Close the connection to the server

client.close();
```

### Read records

The following example creates an array of ten keys and reads the records from the database; returning either the whole record or the specified `report` and `location` bins.

```java
// Create batch of keys

Key[] keys = new Key[10];

for (int i = 0; i < 10; i++) {

    keys[i] = new Key("sandbox", "ufodata", (i + 1));

}

// Read each whole record

Record[] records = client.get(batchPolicy, keys);

// Or specifiy bins

// Record[] records = client.get(batchPolicy, keys, "report", "location");

// Access the records

for (Record record : records){

    if(record != null){

        // Do something

        System.out.format("Record: %s\\n", record.bins);

    }

}

// Close the connection to the server

client.close();
```

### Read commands

The following example creates an array of ten keys and accesses the `city` and `state` map keys to return their respective values from the `report` bin, for each record.

```java
// Create batch of keys

Key[] keys = new Key[10];

for (int i = 0; i < 10; i++) {

    keys[i] = new Key("sandbox", "ufodata", (i + 1));

}

// Create map key list

List<Value> mapKeys = Arrays.asList(Value.get("city"), Value.get("state"));

// Get 'city' and 'state' from report map for each record

BatchResults batchResult = client.operate(batchPolicy, batchWritePolicy, keys,

    MapOperation.getByKeyList("report", mapKeys, MapReturnType.VALUE)

);

// Access the records

for (BatchRecord batchRecord : batchResult.records){

    Record record = batchRecord.record;

    if(record != null){

        // Do something

        System.out.format("Record: %s\\n", record.bins);

    }

}

// Close the connection to the server

client.close();
```

### Read/write commands

The following example creates an array of ten keys and

1.  Defines an [Operation Expression](https://aerospike.com/docs/develop/client/java/usage/atomic/expressions#operation-expressions) that compares the `occurred` bin value against the provided value, `20211231`, and verifies the `posted` bin exists to determine the boolean value of the new `recent` key being added to the `report` map.
2.  Returns the `report` bin.

```java
// Create batch of keys

Key[] keys = new Key[10];

for (int i = 0; i < 10; i++) {

    keys[i] = new Key("sandbox", "ufodata", (i + 1));

}

// Define Operation Expressions

Expression exp = Exp.build(

    MapExp.put(MapPolicy.Default, Exp.val("recent"),

        Exp.and(

            Exp.gt(Exp.intBin("occurred"), Exp.val(20211231)),

            Exp.binExists("posted")

        ),

        Exp.mapBin("report")

    )

);

// Execute the write operation and return the report bin

BatchResults batchResult = client.operate(batchPolicy, batchWritePolicy, keys,

    ExpOperation.write("report", exp, ExpWriteFlags.DEFAULT),

    Operation.get("report")

);

// Access the records

for (BatchRecord batchRecord : batchResult.records){

    Record record = batchRecord.record;

    if(record != null){

        // Do something

        System.out.format("Record: %s\\n", record.bins);

    }

}

// Close the connection to the server

client.close();
```

### Deletes

The following example deletes the records from the database.

```java
// Create batch of keys

Key[] keys = new Key[10];

for (int i = 0; i < 10; i++) {

    keys[i] = new Key("sandbox", "ufodata", (i + 1));

}

// Delete records passing null to use the default BatchDeletePolicy

BatchResults batchResults = client.delete(batchPolicy, null, keys);

// Close the connection to the server

client.close();
```

### Complex batched commands

The following example creates a list of four batch records that each use a differing set of operations.

#### The record with user defined key `4000`

1.  uses the `ops1` array that combines the [Operation Expression](https://aerospike.com/docs/develop/client/java/usage/atomic/expressions#operation-expressions).
2.  uses `exp1` which compares the `occurred` bin value against the provided value, `20211231` and verifies the `posted` bin exists to determine the boolean value of the new `recent` key being added to the `report` map.
3.  returns the `report` bin.

#### The record with user defined key `4001`

1.  uses the `ops2` array which contains a read [Operation Expression](https://aerospike.com/docs/develop/client/java/usage/atomic/expressions#operation-expressions) that gets the length of the `shape` list from the `report` map and returns the value in a computed bin named `numShapes`.

#### The record with user defined key `4002`

1.  uses the `ops3` array which combines a write operation that updates the `posted` bin value, with a map operation that updates the `city` value in the `report` map.
2.  returns both the `posted` and `report` bins.

#### The record with user defined key `4003` is deleted from the database.

```java
// Define Operation Expressions

Expression exp1 = Exp.build(

    MapExp.put(MapPolicy.Default, Exp.val("recent"),

        Exp.and(

            Exp.gt(Exp.intBin("occurred"), Exp.val(20211231)),

            Exp.binExists("posted")

        ),

        Exp.mapBin("report")

    )

);

Expression exp2 = Exp.build(

    ListExp.size(

        MapExp.getByKey(MapReturnType.VALUE, Exp.Type.LIST, Exp.val("shape"), Exp.mapBin("report"))

    )

);

// Define operations

Operation[] ops1 = Operation.array(

    ExpOperation.write("report", exp1, ExpWriteFlags.DEFAULT),

    Operation.get("report")

);

Operation[] ops2 = Operation.array(ExpOperation.read("numShapes", exp2, ExpReadFlags.DEFAULT));

Operation[] ops3 = Operation.array(

    Operation.put(new Bin("posted", 20201108)),

    MapOperation.put(MapPolicy.Default, "report", Value.get("city"), Value.get("Cedarville")),

    Operation.get("posted"),

    Operation.get("report")

);

// Create list of batch records to process

List<BatchRecord> batchRecordList = new ArrayList<BatchRecord>();

batchRecordList.add(new BatchWrite(new Key("sandbox", "ufodata", 4000), ops1));

batchRecordList.add(new BatchRead(new Key("sandbox", "ufodata", 4001), ops2));

batchRecordList.add(new BatchWrite(new Key("sandbox", "ufodata", 4002), ops3));

batchRecordList.add(new BatchDelete(new Key("sandbox", "ufodata", 4003)));

// Proccess the batch

client.operate(batchPolicy, batchRecordList);

// Access the results

for (BatchRecord batchRecord : batchRecordList) {

    Record record = batchRecord.record;

    if (record != null) {

        // Do something

        System.out.format("Record: %s\\n", record.bins);

    }

}

// Close the connection to the server

client.close();
```

## Code block

Expand this section for a single code block to execute a batch read/write operation

```java
import com.aerospike.client.AerospikeClient;

import com.aerospike.client.BatchDelete;

import com.aerospike.client.BatchRead;

import com.aerospike.client.BatchRecord;

import com.aerospike.client.BatchResults;

import com.aerospike.client.BatchWrite;

import com.aerospike.client.Bin;

import com.aerospike.client.Key;

import com.aerospike.client.Operation;

import com.aerospike.client.Record;

import com.aerospike.client.Value;

import com.aerospike.client.cdt.MapOperation;

import com.aerospike.client.cdt.MapPolicy;

import com.aerospike.client.cdt.MapReturnType;

import com.aerospike.client.exp.Exp;

import com.aerospike.client.exp.ExpOperation;

import com.aerospike.client.exp.ExpReadFlags;

import com.aerospike.client.exp.ExpWriteFlags;

import com.aerospike.client.exp.Expression;

import com.aerospike.client.exp.ListExp;

import com.aerospike.client.exp.MapExp;

import com.aerospike.client.policy.BatchPolicy;

import com.aerospike.client.policy.BatchWritePolicy;

import java.util.Arrays;

import java.util.List;

// Establishes a connection to the server

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

// Create a new batch policy

BatchPolicy batchPolicy = new BatchPolicy();

batchPolicy.filterExp = Exp.build(

    // An example that will always return true

    Exp.gt(Exp.val(2), Exp.val(1))

);

// Create the batch write policy

BatchWritePolicy batchWritePolicy = new BatchWritePolicy();

batchWritePolicy.filterExp = Exp.build(

    // An example that will always return true

    Exp.gt(Exp.val(2), Exp.val(1))

);

// Create batch of keys

Key[] keys = new Key[10];

for (int i = 0; i < 10; i++) {

    keys[i] = new Key("sandbox", "ufodata", (i + 1));

}

// Define Operation Expressions

Expression exp = Exp.build(

    MapExp.put(MapPolicy.Default, Exp.val("recent"),

        Exp.and(

            Exp.gt(Exp.intBin("occurred"), Exp.val(20211231)),

            Exp.binExists("posted")

        ),

        Exp.mapBin("report")

    )

);

// Execute the write operation and return the report bin

BatchResults batchResult = client.operate(batchPolicy, batchWritePolicy, keys,

    ExpOperation.write("report", exp, ExpWriteFlags.DEFAULT),

    Operation.get("report")

);

// Access the records

for (BatchRecord batchRecord : batchResult.records){

    Record record = batchRecord.record;

    if(record != null){

        // Do something

        System.out.format("Record: %s\\n", record.bins);

    }

}

// Close the connection to the server

client.close();
```