Create
Jump to the Code block for a combined complete example.
Create a document record
The following command uses the Aerospike Admin (asadm) to create an integer index on the sandbox
namespace, ufodata
set, and occurred
bin. This is the recommended way to create a secondary index.
asadm -e 'enable; manage sindex create numeric occurred_idx ns sandbox set ufodata bin occurred'
Setup
Import the necessary helpers, create a client connection, and create a key.
import aerospikefrom aerospike_helpers.operations import map_operations
import pprintimport json
# set aerospike host configconfig = {"hosts": [("localhost", 3000)]}
# create the aerospike client and connectclient = aerospike.client(config).connect()
# aerospike namespace, set, and key_id to be used for the aerospike keynamespace = "test"set = "table1"key_id = 5
# define aerospike keykey = (namespace, set, key_id)
Create a JSON document
Prepare the JSON document to be sent to Aerospike.
# example JSON stringemployee ='{"id":"09", "name": "Nitin", "department":"Finance"}'
# Convert string to Python dictemployee_dict = json.loads(employee)pprint.pprint(employee_dict)
# set an aerospike bin with the bin name "employee" and# put the JSON document in as a mapbins = { "employee": employee_dict}
Write
Write the document to Aerospike.
# Create the write policywrite_policy = {"key": aerospike.POLICY_KEY_SEND}
# Write the record to Aerospiketry: client.put(key=key, bins=bins, policy=write_policy)
(key_, meta, bins) = client.get(key=key) print("Create succeeded\nKey: ", key[2], "\nRecord:") pprint.pprint(bins)
except aerospike.exception.AerospikeError as e: print(f"Create failed\nError: {e.msg} [{e.code}]")
Code block
Expand this section for a single code block to create a document record.
import aerospikefrom aerospike_helpers.operations import map_operations
import pprintimport json
# set aerospike host configconfig = {"hosts": [("localhost", 3000)]}
# create the aerospike client and connectclient = aerospike.client(config).connect()
# aerospike namespace, set, and key_id to be used for the aerospike keynamespace = "test"set = "table1"key_id = 5
# define aerospike keykey = (namespace, set, key_id)
# example JSON stringemployee ='{"id":"09", "name": "Nitin", "department":"Finance"}'
# Convert string to Python dictemployee_dict = json.loads(employee)pprint.pprint(employee_dict)
# set an aerospike bin with the bin name "employee" and# put the JSON document in as a mapbins = { "employee": employee_dict}
# Create the write policywrite_policy = {"key": aerospike.POLICY_KEY_SEND}
# Write the record to Aerospiketry: client.put(key=key, bins=bins, policy=write_policy)
(key_, meta, bins) = client.get(key=key) print("Create succeeded\nKey: ", key[2], "\nRecord:") pprint.pprint(bins)
except aerospike.exception.AerospikeError as e: print(f"Create failed\nError: {e.msg} [{e.code}]")