I need an atomic 'set minimum' operation for Aerospike, where I give a bin name and a numeric argument, and whichever is lower, the current value of the bin or the argument, is set and returned.
The following Lua UDF should work
test.lua
function set_min(rec, bin_name, value)
if aerospike:exists(rec) then
local min = rec[bin_name]
if min > value then
rec[bin_name] = value
aerospike:update(rec)
end
else
rec[bin_name] = value
aerospike:create(rec)
end
return rec[bin_name]
end
Run with the arguments 11, 9, 5, 7:
aql> execute test.set_min('minval', 11) on test.set-min where PK=2
+---------+
| set_min |
+---------+
| 11 |
+---------+
1 row in set (0.001 secs)
OK
aql> execute test.set_min('minval', 9) on test.set-min where PK=2
+---------+
| set_min |
+---------+
| 9 |
+---------+
1 row in set (0.001 secs)
OK
aql> execute test.set_min('minval', 5) on test.set-min where PK=2
+---------+
| set_min |
+---------+
| 5 |
+---------+
1 row in set (0.001 secs)
OK
aql> execute test.set_min('minval', 7) on test.set-min where PK=2
+---------+
| set_min |
+---------+
| 5 |
+---------+
1 row in set (0.000 secs)
Is there another way to do this?