Redis的Lua脚本,用于对键的值求和 [英] Lua script for Redis which sums the values of keys

查看:495
本文介绍了Redis的Lua脚本,用于对键的值求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建我的第一个Redis服务器端脚本(用于调试的 ),而我缺乏Lua的经验使我感到非常困惑。

I am building out my first Redis server side script (for debugging) and my lack of Lua experience has me quite stuck.

本质上来说,我有一个K / V对(包含〜1000个值)的数据集,我想从中列出所有与模式匹配的KEYS。例如在redis-cli中:

Essentially have a dataset of K/V pairs (containing ~1000 values) from which I want to list all the KEYS that match a pattern. For example in redis-cli:

> KEYS "carlos:*"
1) "carlos:1"
2) "carlos:2"
3) "carlos:3"
4) "carlos:4"

基于上面的输出,我想通过执行Lua脚本来返回这些键的总和。目前,我的 sum.lua

Based on the above output I want to return the sum of those keys by executing a Lua script. Currently I have the following on my sum.lua

local sum = 0
local matches = redis.call('KEYS', 'carlos:*')

for unpack(matches)
   sum = sum + redis.call('GET', matches)
end

return sum

脚本可能不正确,甚至尝试 redis.call('KEYS','carlos:*')本身也会产生以下错误

While the above script is likely incorrect, trying even redis.call('KEYS', 'carlos:*') by itself produces the following error


root @ carlos:〜#redis-cli EVAL $(cat sum.lua)

root@carlos:~# redis-cli EVAL "$(cat sum.lua)"

(错误)错误'eval'命令的参数数量错误

(error) ERR wrong number of arguments for 'eval' command

我尝试了多次语法迭代,但无济于事。有任何想法吗?

I have tried a number of iterations of my syntax to no avail. Any ideas?

谢谢

推荐答案


  1. EVAL 至少需要两个论点脚本以及传递给脚本的键数。在这种情况下,您要传递零键,这意味着可以按以下方式调用脚本:

  1. EVAL requires a minimum of two arguments; the script and the number of keys you are passing to the script. In this case, you are passing zero keys, meaning the script can be invoked as follows:

redis-cli EVAL "$(cat sum.lua)" 0

或:

redis-cli --eval sum.lua


  • 用于遍历 KEYS 返回的值的循环结构不正确;我已经为您修复了它。

  • Your loop structure for iterating over the values returned from KEYS was incorrect; I have fixed it for you.

    您需要将 GET 返回的值转换为字符串使用Lua的 tonumber 函数转换为数字。

    You need to convert the value returned from GET from a string to a number using Lua's tonumber function.

    完成上述更改后,以下脚本将为您工作:

    With the above changes made, the following script should work for you:

    local sum = 0
    local matches = redis.call('KEYS', 'carlos:*')
    
    for _,key in ipairs(matches) do
        local val = redis.call('GET', key)
        sum = sum + tonumber(val)
    end
    
    return sum
    

    这篇关于Redis的Lua脚本,用于对键的值求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆