Simple Put-Get Example
For an interactive Jupyter notebook experience:
A simple example of put
and get
calls in Aerospike.
Prerequisites
- Aerospike database running locally
- Python
- Aerospike Python client
Visit the Aerospike notebooks repo for additional details and the Docker container.
Import the module
import aerospike
Configure the client
This configuration is for Aerospike running on port 3000 of localhost which is the default. If your environment is different (Aerospike server running on a different host or different port, etc) you can use different configuration arguments.
config = {
'hosts': [ ('127.0.0.1', 3000) ]
}
Create a client and connect it to the cluster
try:
client = aerospike.client(config).connect()
except:
import sys
print("failed to connect to the cluster with", config['hosts'])
sys.exit(1)
Records are addressable via a tuple of (namespace, set, key)
These three components form the key. set
is optional. For a detailed description of
the data model, see the Data Model
overview.
key = ('test', 'demo', 'foo')
Writing a record
Aerospike is schemaless. You can create and modify records without any other
setup. The following example writes a record with two bins, name
and age
,
using the key defined above.
try:
# Write a record
client.put(key, {
'name': 'John Doe',
'age': 32
})
except Exception as e:
import sys
print("error: {0}".format(e), file=sys.stderr)
Reading a record
The following example retrieves the same record.
(key, metadata, record) = client.get(key)
Display result
The following example prints data from the same record, including:
- The contents of the record's bins.
- The components of the key which are: namespace, the set, a user key (by default there is no user key), and a hash which is the internal representation of the key.
- The metadata with the time to live (TTL) and the record's generation.
Lastly it is important to clean up the client we created at the beginning.
print("record contents are", record)
print("key components are", key)
print("metadata is", metadata)
# Close the connection to the Aerospike cluster
client.close()