Redis 的 Lua 脚本,它对键的值求和 [英] Lua script for Redis which sums the values of keys
问题描述
我正在构建我的第一个 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 个值)的数据集,我想从中列出与模式匹配的所有键.例如在 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)"
(错误)ERR '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?
谢谢
推荐答案
EVAL
至少需要两个参数;脚本和您传递给脚本的键数.在这种情况下,您传递的是零键,这意味着可以按如下方式调用脚本:
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.
您需要使用 Lua 的 tonumber
函数将 GET
返回的值从字符串转换为数字.
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屋!