使用原子操作在 Aerospike bin 中设置最小值

我需要一个 Aerospike 原子“设置最小值”的操作,其中我提供一个 bin 名称和一个数值参数,无论当前 bin 的值或参数中的值哪个更小,都将其设置并返回。

以下 Lua UDF 应该可以实现

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

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

aql> execute test.set_min('minval', 11) on test.set-min where PK=2
+---------+
| set_min |
+---------+
| 11      |
+---------+
1 行记录 (0.001 秒)

OK

aql> execute test.set_min('minval', 9) on test.set-min where PK=2
+---------+
| set_min |
+---------+
| 9       |
+---------+
1 行记录 (0.001 秒)

OK

aql> execute test.set_min('minval', 5) on test.set-min where PK=2
+---------+
| set_min |
+---------+
| 5       |
+---------+
1 行记录 (0.001 秒)

OK

aql> execute test.set_min('minval', 7) on test.set-min where PK=2
+---------+
| set_min |
+---------+
| 5       |
+---------+
1 行记录 (0.000 秒)

还有其他的方法吗?

点赞
用户582436
用户582436

在任何数据库中,用户定义的函数都比本地操作运行的更慢。Aerospike也不例外,Lua UDF的延迟会更高,而且不会像本地操作那样扩展得很好。

Aerospike的ListMap数据类型有广泛(并且不断增长)的原子操作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客户端的文档

2018-11-07 06:25:12