Lua script to return efficient dictionary from Redis HGETALL call

断了今生、忘了曾经 提交于 2019-12-19 08:43:06

问题


I need to use Redis HMGET from a Lua script and extract specific values in following code. But redis.call('HMGET', table_key, hkey1, hkey2, ...) return a flat array of {hkey1, val1, hkey2, val2, ...}

To extract values by key I wrote:

local function flat_map_get(flat_map, hash_key)
    local i = 1
    while flat_map[i] do
        if flat_map[i] == hash_key then
            return flat_map[i+1]
        end
        i = i+2
    end
end

Of course, as usage grow, multiple calls to this function presented major performance drop.

What is an efficient way to read values from the flat array returned by HMGET? Or otherwise, to convert the returned value into a proper key-value table?


回答1:


After some profiling and tests, we found the following function to have good performance and use it to get a proper table.

This save the need to call a getter function for each hash key retrieval.

local function hgetall(hash_key)
    local flat_map = redis.call('HGETALL', hash_key)
    local result = {}
    for i = 1, #flat_map, 2 do
        result[flat_map[i]] = flat_map[i + 1]
    end
    return result
end


来源:https://stackoverflow.com/questions/34313598/lua-script-to-return-efficient-dictionary-from-redis-hgetall-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!