使用Python操作Aerospike
使用Python操作Aerospike数据库需要使用aerospike模块,可以使用pip安装:
pip install aerospike
以下是一个完整的Python代码样例,演示了如何连接到Aerospike数据库并进行数据插入、查询、修改和删除操作:
python
import aerospike
# 连接到Aerospike数据库
config = {
'hosts': [('127.0.0.1', 3000)]
}
client = aerospike.client(config).connect()
# 插入数据
key = ('test', 'demo', '1')
data = {
'name': 'John Doe',
'age': 30,
'gender': 'male'
}
client.put(key, data)
# 查询数据
(key, metadata, record) = client.get(key)
print(record)
# 修改数据
updated_data = {
'name': 'Jane Smith',
'age': 35,
'gender': 'female'
}
client.put(key, updated_data)
# 再次查询数据
(key, metadata, record) = client.get(key)
print(record)
# 删除数据
client.remove(key)
# 关闭连接
client.close()
上述代码首先创建了一个Aerospike客户端连接到本地数据库。然后,使用`put`方法插入数据到名为`test`,集合为`demo`,键为`1`的记录中。
接下来,使用`get`方法查询到插入的数据,并打印在控制台上。
然后,修改数据中的一些字段,并使用`put`方法更新数据库中的记录。
再次查询数据,可以看到数据已经被更新。
最后,使用`remove`方法删除之前插入的记录。
最后,关闭Aerospike客户端连接。