如何在Redis中统计包含特定值的HASH列表数量
统计Redis中指定字段值的哈希数量
现有以下Redis哈希键及字段设置:
HMSET myhash1 type Car company BMW HMSET myhash2 type Car company Benz HMSET myhash3 type Car company BMW HMSET myhash4 type Car company Honda HMSET myhash5 type Car company BMW HMSET myhash6 type Car company Toyota HMSET myhash7 type Car company Benz
需要统计其中company字段值为BMW的哈希键数量,预期结果为3。
方法1:SCAN遍历+命令行统计(适合快速验证)
利用SCAN安全遍历所有匹配的键(避免KEYS命令的阻塞问题),结合管道和grep统计结果:
redis-cli --scan --pattern "myhash*" | while read key; do redis-cli HGET "$key" company; done | grep -c BMW
执行后直接输出统计结果3。
方法2:Lua脚本统计(高效,适合生产环境)
通过Lua脚本在Redis服务器端完成遍历和统计,减少网络交互开销:
local count = 0 local cursor = "0" repeat local scan_result = redis.call("SCAN", cursor, "MATCH", "myhash*") cursor = scan_result[1] local keys = scan_result[2] for _, key in ipairs(keys) do local company_val = redis.call("HGET", key, "company") if company_val == "BMW" then count = count + 1 end end until cursor == "0" return count
将上述脚本保存为count_bmw_hashes.lua,执行命令:
redis-cli EVAL "$(cat count_bmw_hashes.lua)" 0
或者直接在Redis客户端内执行脚本字符串:
EVAL "local count = 0 local cursor = '0' repeat local scan_result = redis.call('SCAN', cursor, 'MATCH', 'myhash*') cursor = scan_result[1] local keys = scan_result[2] for _, key in ipairs(keys) do local company_val = redis.call('HGET', key, 'company') if company_val == 'BMW' then count = count +1 end end until cursor == '0' return count" 0
执行后返回统计结果3。
内容的提问来源于stack exchange,提问作者Hamed Kamrava
相关产品推荐
相关产品推荐

