在Aerospike仓中设置最小值的原子操作



我需要Aerospike的原子"set minimum"操作,其中我给出一个bin名称和一个数字参数,并且设置并返回bin或参数的当前值(以较低者为准(。

以下Lua UDF应能在中工作

测试.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

使用参数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)

有别的办法吗?

在任何数据库中,用户定义函数的运行速度都比本机操作慢。这与Aerospike没有什么不同,在Aerospike中,Lua UDF将具有更高的延迟,并且不会像本地操作那样扩展。

Aerospike的List和Map数据类型具有广泛(且不断增长(的原子操作API。这些操作可以组合成一个多操作事务(使用operate((方法(。

我们可以利用有序列表来执行与上面的UDF相同的原子操作,从而运行得更快、扩展得更好。

set_min.py

from __future__ import print_function
import aerospike
from aerospike import exception as e
from aerospike_helpers.operations import list_operations as lh
import pprint
import sys
def set_min(bin_name, val):
list_policy = {
"list_order": aerospike.LIST_ORDERED,
"write_flags": (aerospike.LIST_WRITE_ADD_UNIQUE |
aerospike.LIST_WRITE_PARTIAL |
aerospike.LIST_WRITE_NO_FAIL)
}
ops = [
lh.list_append(bin_name, val, list_policy),
lh.list_remove_by_rank_range(bin_name, 0, aerospike.LIST_RETURN_NONE,
1, True),
lh.list_get_by_rank(bin_name, 0, aerospike.LIST_RETURN_VALUE)
]
return ops
config = {'hosts': [('172.16.39.132', 3000)]}
client = aerospike.client(config).connect()
pp = pprint.PrettyPrinter(indent=2)
key = ('test', 'set-min', 1)
key, meta, bins = client.operate(key, set_min('minval', 11))
pp.pprint(bins['minval'])
key, meta, bins = client.operate(key, set_min('minval', 9))
pp.pprint(bins['minval'])
key, meta, bins = client.operate(key, set_min('minval', 5))
pp.pprint(bins['minval'])
key, meta, bins = client.operate(key, set_min('minval', 7))
pp.pprint(bins['minval'])
client.close()

使用参数11、9、5、7运行:

11
9
5
5
  1. 使用有序列表,会向列表中添加一个唯一值,如果该值已经存在,则正常失败。该列表应现在有一两个元素
  2. 该列表被修剪为只包含排名最低的元素
  3. 返回排名最低的元素(应仅为列表中的一个(

这三个操作在记录锁下原子性地发生。

有关参考,请参阅Python客户端的文档。

最新更新