Hello, World! in Python with Aerospike.
This notebook requires that Aerospike datbase is running.
!asd >& /dev/null
!pgrep -x asd >/dev/null && echo "Aerospike database is running!" || echo "**Aerospike database is not running!**"
Aerospike database is running!
Import the client library.
import aerospike
print("Client module imported")
Client module imported
The configuration is for Aerospike database running on port 3000 of localhost (IP 127.0.0.1) which is the default. Modify config if your environment is different (Aerospike database running on a different host or different port).
config = {
'hosts': [ ('127.0.0.1', 3000) ]
}
print("Configuring with seed host:", config['hosts'])
Configuring with seed host: [('127.0.0.1', 3000)]
try:
client = aerospike.client(config).connect()
except:
import sys
print("Failed to connect to the cluster with", config['hosts'])
sys.exit(1)
print("Connected to the cluster")
Connected to the cluster
The three components namespace, set, and userkey (with set being optional) form the Primary Key (PK) or simply key, of the record. The key serves as a handle to the record, and using it, a record can be read or written. For a detailed description of the data model see the Data Model overview
key = ('test', 'demo', 'foo')
print('Working with record key ', key)
Working with record key ('test', 'demo', 'foo')
Aerospike is schema-less and records may be written without any other setup. Here the bins or fields: name, age and greeting, are being written to a record with the key as defined above.
try:
# Write a record
client.put(key, {
'name': 'John Doe',
'age': 32,
'greeting': 'Hello, World!'
})
except Exception as e:
import sys
print("error: {0}".format(e), file=sys.stderr)
sys.exit(1)
print('Successfully written the record')
Successfully written the record
The record may be retrieved using the same key.
(key, metadata, record) = client.get(key)
print('Read back the record')
Read back the record
Print the record that was just retrieved. We are also printing:
print("Record contents are", record)
print("Key's components are", key)
print("Metadata is", metadata)
Record contents are {'name': 'John Doe', 'age': 32, 'gpa': 4.3, 'greeting': 'Hello, World!'} Key's components are ('test', 'demo', None, bytearray(b'\xf5~\xc1\x835\xf7\x10\x0c\x04X\xf8\xa6D\xbc\xbcvm\x93G\x1e')) Metadata is {'ttl': 2592000, 'gen': 2}
Finally close the client we created at the beginning.
# Close the connection to the Aerospike cluster
client.close()
print('Connection closed.')
Connection closed.
Visit Aerospike notebooks repo to run additional Aerospike notebooks. To run a different notebook, download the notebook from the repo to your local machine, and then click on File->Open, and select Upload.