I want to fetch bin of type list from aerospike database and update list(add and remove some elements from list) then then update bin in aerospike db in single for given key. I have multiple thread that can fetch and update same key from multiple place so i want to do above operation in single transaction.
aerospike java client version: **3.2.0**** **java version: 1.8
If you are doing simple list manipulations, you can use ListOperation
:
https://www.aerospike.com/apidocs/java/com/aerospike/client/cdt/ListOperation.html
If ListOperation
doesn't have the operations you need to make, or you need to make multiple operations in one atomic transaction, using UDFs is your best choice.
During UDF execution, the record is locked. Whether it is a full lock or a write lock, I'm not sure, but either case should serve your atomicity needs just fine. Do all your list operations, then persist the changes to database in one aerospike:create(rec)
or aerospike:update(rec)
call.
Example: most_recent_10_list.lua
function append(rec, value)
-- Get list from database record. Create one if it doesn't exist.
local my_list = rec["my_list_bin"]
if my_list == nil then
my_list = list()
end
-- Add value to list
list.append(my_list, value)
-- Keep only the 10 most-recent values in the list
local new_list_size = list.size(my_list)
if list.size(new_list_size >= 10) then
my_list = list.drop(my_list, new_list_size - 10)
end
-- Save changes to database
rec["my_list_bin"] = my_list
if not aerospike:exists(rec) then
aerospike:create(rec)
else
aerospike:update(rec)
end
end