Batched commands
Jump to the Code block for a combined complete example.
Batched commands 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.
import aerospikefrom aerospike_helpers import expressions as expfrom aerospike_helpers.operations import expression_operations, map_operations, operationsfrom aerospike_helpers.batch import records as br
# Define host configurationconfig = { 'hosts': [ ('127.0.0.1', 3000) ]}# Establishes a connection to the serverclient = aerospike.client(config).connect()The record structure:
Occurred: IntegerReported: IntegerPosted: IntegerReport: Map{ shape: List, summary: String, city: String, state: String, duration: String}Location: GeoJSONPolicies
Policies are defined for the batch parent policy as well as batch read, batch write, batch delete, and batch UDF operations. Filter Expressions can be defined within each type of batch operation policy and the batch parent policy, along with other operation specific policies.
# An example that will always return trueexpr = exp.GT(2, 1).compile()
# Create a new batch policybatch_policy = {'expressions': expr}
# Create the batch write policybatch_write_policy = {'expressions': expr}Requests
Exists
The following example creates an array of ten keys and checks for their existence in the database.
# Create batch of keyskeys = []for i in range(4995,5006): batch_key = ('sandbox', 'ufodata', i) keys.append(batch_key)
# Check if records existbrs = client.batch_read(keys, bins=[])
# Access the recordsfor 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 serverclient.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.
# Create batch of keyskeys = []for i in range(1,11): batch_key = ('sandbox', 'ufodata', i) keys.append(batch_key)
# Read each whole recordbrs = client.batch_read(keys);
# Or specify bins# brs = client.batch_read(keys, bins=["report", "location"]);
# Access the recordsfor br in brs.batch_records: (key, meta, bins) = br.record # Do something print('Record: ', bins)
# Close the connection to the serverclient.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.
# Create batch of keyskeys = []for i in range(1,11): batch_key = ('sandbox', 'ufodata', i) keys.append(batch_key)
# Create map key listmapKeys = ['city', 'state']
# Create operationsops = [ map_operations.map_get_by_key_list('report', mapKeys, aerospike.MAP_RETURN_VALUE)]
# Get 'city' and 'state' from report map for each recordbrs = client.batch_operate(keys, ops)
# Access the recordsfor br in brs.batch_records: (key, meta, bins) = br.record # Do something print('Record: ', bins)
# Close the connection to the serverclient.close()Read/write operations
The following example creates an array of ten keys and
- Defines an Operation Expression that compares the
occurredbin value against the provided value,20211231, and verifies thepostedbin exists to determine the boolean value of the newrecentkey being added to thereportmap. - Returns the
reportbin.
# Create batch of keyskeys = []for i in range(1,11): batch_key = ('sandbox', 'ufodata', i) keys.append(batch_key)
# Define Operation Expressionsexpr = exp.MapPut(None, None, 'recent', exp.And( exp.GT(exp.IntBin('occurred'), 20211231), exp.BinExists('posted') ), exp.MapBin('report')).compile()
# Create operationsops = [ expression_operations.expression_write('report', expr, aerospike.EXP_WRITE_DEFAULT), operations.read('report')]
# Execute the write operation and return the report binbatchRecords = client.batch_operate(keys, ops)
# Access the recordsfor batchRecord in batchRecords.batch_records: (key, meta, bins) = batchRecord.record # Do something print('Record: ', bins)
# Close the connection to the serverclient.close()Delete operations
The following example deletes the records from the database.
# Create batch of keyskeys = []for i in range(1,11): batch_key = ('sandbox', 'ufodata', i) keys.append(batch_key)
# Delete records passing null to use the default BatchDeletePolicybatch_records = client.batch_remove(keys)
# Close the connection to the serverclient.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
- uses the
ops1array that combines the Operation Expression. - uses
exp1which compares theoccurredbin value against the provided value,20211231and verifies thepostedbin exists to determine the boolean value of the newrecentkey being added to thereportmap. - returns the
reportbin.
The record with user defined key 4001
- uses the
ops2array which contains a read Operation Expression that gets the length of theshapelist from thereportmap and returns the value in a synthetic bin namednumShapes.
The record with user defined key 4002
- uses the
ops3array which combines a write operation that updates thepostedbin value, with a map operation that updates thecityvalue in thereportmap. - returns both the
postedandreportbins.
The record with user defined key 4003 is deleted from the database.
# Define Operation Expressionsexpr1 = 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 operationsops1 = [ 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 processbatch_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 batchclient.batch_write(batch_records)
# Access the resultsfor 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 serverclient.close()Code block
Expand this section for a single code block to execute a batch read/write operation
import aerospikefrom aerospike_helpers import expressions as expfrom aerospike_helpers.operations import expression_operations, map_operations, operationsfrom aerospike_helpers.batch import records as br
# Define host configurationconfig = { 'hosts': [ ('127.0.0.1', 3000) ]}# Establishes a connection to the serverclient = aerospike.client(config).connect()
# An example that will always return trueexpr = exp.GT(2, 1).compile()
# Create a new batch policybatch_policy = {'expressions': expr}
# Create the batch write policybatch_write_policy = {'expressions': expr}
# Create batch of keyskeys = []for i in range(1,11): batch_key = ('sandbox', 'ufodata', i) keys.append(batch_key)
# Define Operation Expressionsexpr = exp.MapPut(None, None, 'recent', exp.And( exp.GT(exp.IntBin('occurred'), 20211231), exp.BinExists('posted') ), exp.MapBin('report')).compile()
# Create operationsops = [ expression_operations.expression_write('report', expr, aerospike.EXP_WRITE_DEFAULT), operations.read('report')]
# Execute the write operation and return the report binbatchRecords = client.batch_operate(keys, ops)
# Access the recordsfor batchRecord in batchRecords.batch_records: (key, meta, bins) = batchRecord.record # Do something print('Record: ', bins)
# Close the connection to the serverclient.close()