
---
title: "Batched commands"
description: "Guide to Aerospike Python client batched commands, including batch reads, writes, and complex 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.

```python
import aerospike

from aerospike_helpers import expressions as exp

from aerospike_helpers.operations import expression_operations, map_operations, operations

from aerospike_helpers.batch import records as br

# Define host configuration

config = {

    'hosts': [ ('127.0.0.1', 3000) ]

}

# Establishes a connection to the server

client = aerospike.client(config)
```

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/python/usage/atomic/expressions) can be defined within each type of batch operation policy and the batch parent policy, along with other operation specific policies.

```python
# An example that will always return true

expr = exp.GT(2, 1).compile()

# Create a new batch policy

batch_policy = {'expressions': expr}

# Create the batch write policy

batch_write_policy = {'expressions': expr}
```

## Requests

### Exists

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

```python
# Create batch of keys

keys = []

for i in range(4995,5006):

    batch_key = ('sandbox', 'ufodata', i)

    keys.append(batch_key)

# Check if records exist

brs = client.batch_read(keys, bins=[])

# Access the records

for br in brs.batch_records:

    if br.result == 2: # "Record not found" error code

        print('Key: ', br.key, ' does not exist')

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

```python
# Create batch of keys

keys = []

for i in range(1,11):

    batch_key = ('sandbox', 'ufodata', i)

    keys.append(batch_key)

# Read each whole record

brs = client.batch_read(keys);

# Or specify bins

# brs = client.batch_read(keys, bins=["report", "location"]);

# Access the records

for br in brs.batch_records:

    (key, meta, bins) = br.record

    # Do something

    print('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.

```python
# Create batch of keys

keys = []

for i in range(1,11):

    batch_key = ('sandbox', 'ufodata', i)

    keys.append(batch_key)

# Create map key list

mapKeys = ['city', 'state']

# Create operations

ops = [

    map_operations.map_get_by_key_list('report', mapKeys, aerospike.MAP_RETURN_VALUE)

]

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

brs = client.batch_operate(keys, ops)

# Access the records

for br in brs.batch_records:

    (key, meta, bins) = br.record

    # Do something

    print('Record: ', bins)

# Close the connection to the server

client.close()
```

### Read/write operations

The following example creates an array of ten keys and

1.  Defines an [Operation Expression](https://aerospike.com/docs/develop/client/python/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.

```python
# Create batch of keys

keys = []

for i in range(1,11):

    batch_key = ('sandbox', 'ufodata', i)

    keys.append(batch_key)

# Define Operation Expressions

expr = exp.MapPut(None, None, 'recent',

    exp.And(

        exp.GT(exp.IntBin('occurred'), 20211231),

        exp.BinExists('posted')

    ),

    exp.MapBin('report')).compile()

# Create operations

ops = [

    expression_operations.expression_write('report', expr, aerospike.EXP_WRITE_DEFAULT),

    operations.read('report')

]

# Execute the write operation and return the report bin

batchRecords = client.batch_operate(keys, ops)

# Access the records

for batchRecord in batchRecords.batch_records:

    (key, meta, bins) = batchRecord.record

    # Do something

    print('Record: ', bins)

# Close the connection to the server

client.close()
```

### Delete operations

The following example deletes the records from the database.

```python
# Create batch of keys

keys = []

for i in range(1,11):

    batch_key = ('sandbox', 'ufodata', i)

    keys.append(batch_key)

# Delete records passing null to use the default BatchDeletePolicy

batch_records = client.batch_remove(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/python/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/python/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.

```python
# Define Operation Expressions

expr1 = exp.MapPut(None, None, 'recent',

    exp.And(

        exp.GT(exp.IntBin('occurred'), 20211231),

        exp.BinExists('posted')

    ),

    exp.MapBin('report')).compile()

expr2 = exp.ListSize(

    None,

    exp.MapGetByKey(None, aerospike.MAP_RETURN_VALUE, exp.ResultType.LIST, 'shape', exp.MapBin('report'))).compile()

# Define operations

ops1 = [

    expression_operations.expression_write('report', expr1, aerospike.EXP_WRITE_DEFAULT),

    operations.read('report')

]

ops2 = [

    expression_operations.expression_read('numShapes', expr2, aerospike.EXP_READ_DEFAULT)

]

ops3 = [

    operations.write('posted', 20201108),

    map_operations.map_put('report', 'city', 'Cedarville'),

    operations.read('posted'),

    operations.read('report')

]

# Create list of batch records to process

batch_records = br.BatchRecords(

    [

        br.Write(key=('sandbox', 'ufodata', 4000), ops=ops1),

        br.Read(key=('sandbox', 'ufodata', 4001), ops=ops2),

        br.Write(key=('sandbox', 'ufodata', 4002), ops=ops3),

        br.Remove(key=('sandbox', 'ufodata', 4003))

    ]

)

# Proccess the batch

client.batch_write(batch_records)

# Access the results

for batch_record in batch_records.batch_records:

    if not batch_record.record == None:

        (key, meta, bins) = batch_record.record

        # Do something

        print('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

```python
import aerospike

from aerospike_helpers import expressions as exp

from aerospike_helpers.operations import expression_operations, map_operations, operations

from aerospike_helpers.batch import records as br

# Define host configuration

config = {

    'hosts': [ ('127.0.0.1', 3000) ]

}

# Establishes a connection to the server

client = aerospike.client(config)

# An example that will always return true

expr = exp.GT(2, 1).compile()

# Create a new batch policy

batch_policy = {'expressions': expr}

# Create the batch write policy

batch_write_policy = {'expressions': expr}

# Create batch of keys

keys = []

for i in range(1,11):

    batch_key = ('sandbox', 'ufodata', i)

    keys.append(batch_key)

# Define Operation Expressions

expr = exp.MapPut(None, None, 'recent',

    exp.And(

        exp.GT(exp.IntBin('occurred'), 20211231),

        exp.BinExists('posted')

    ),

    exp.MapBin('report')).compile()

# Create operations

ops = [

    expression_operations.expression_write('report', expr, aerospike.EXP_WRITE_DEFAULT),

    operations.read('report')

]

# Execute the write operation and return the report bin

batchRecords = client.batch_operate(keys, ops)

# Access the records

for batchRecord in batchRecords.batch_records:

    (key, meta, bins) = batchRecord.record

    # Do something

    print('Record: ', bins)

# Close the connection to the server

client.close()
```