Aerospike, how to replace a record


#1

Hello, Im using the python client to communicate with aerospike. I can get and put a record, but I dont know how to replace a record … everytime I change the dict returned from the .get function and put it on aerospike, the record will not be modified … at the moment it extend only the my record …

Who can give me an example …

best, Leo


#2

In the Python client, the dict is used as a means to easily define a set of bins to send to the server to store. By default, a write to a record (put) does not completely replace a record, instead the key-value pairs of the dict will either create, modify, remove (by using None value) or add the defined bins in the dict to an existing record. By default, the bins not defined in the dict will remain intact.

The behavior can be modified by defining the existence policy, which is a policy that dictates how the write operation should behave if a record exists. The default policy is AS_POLICY_EXISTS_IGNORE=1, which is a create or update policy. For the behavior you want is defined as either AS_POLICY_EXISTS_REPLACE = 4 or AS_POLICY_EXISTS_CREATE_OR_REPLACE = 5. These and other policy values values are defined in the C client header file aerospike/as_policy.h.

To set the policy for an operation, you can simply create a dict containing the policy field names which mirror the policy struct in the C api. For this case, the field name is exists. Unfortunately, the values can only be numeric, as we do not have symbols representing them in Python. So, you will need to use 4 or 5`.

In the Python client, you can set the policy as follows:

# 5 = create or replace, as defined in the C client API
policy = { 'exists': 5 } 

# update
client.put(keyt, bins, policy=policy)

Here is a more detailed example you can try:

import aerospike

# configuration
config = {
    'hosts': [('localhost',3000)]
}

# connect
client = aerospike.client(config).connect()

# create a key tuple
keyt = ("test", "demo", "something")

# write a new record 
# the follow will use the default existence policy of "create or update"
client.put(keyt, {'foo': 100})

# read the record
(k, m, b) = client.get(keyt)

print(b)
#> {'foo': 100}

# update the existing record
# the default policy will leave previous 'foo' bin intact, and add the 'bar' bin.
client.put(keyt, {'bar': 100})

# read the record
(k, m, b) = client.get(keyt)

# update the existing record
# the default policy will update the 'foo' bin, and leave the 'bar' bin intact.
client.put(keyt, {'foo': 200})

# read the record
(k, m, b) = client.get(keyt)

print(b)
#> {'foo': 200, 'bar': 100}

# Instead of updating the record, we want to replace it,
# so we change the existence policy to 4 (5 will work too).
client.put(keyt, {'baz': 100}, policy={'exists': 5})

# read the record
(k, m, b) = client.get(keyt)

print(b)
#> {'baz': 100}