Redis,如何使用ZINCRBY增加zset的所有分数? [英] Redis, how to increase all scores of a zset with ZINCRBY?

查看:101
本文介绍了Redis,如何使用ZINCRBY增加zset的所有分数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用一个命令增加 zset 的所有分数?这就是我想做的:

Is there a way to increment all scores of a zset with one command? This is what I would like to do:

ZADD myzset 1 "first"
ZADD myzset 2 "second"
ZINCRBY myzset 2 "*"
ZRANGE myzset 0 -1 WITHSCORES
1) "first"
2) "3"
3) "second"
4) "4"

但是,ZINCRBY myzset 2 "*" 不能那样工作.

but, ZINCRBY myzset 2 "*" does not work like that.

推荐答案

没有命令,ZINCRBY 一次只能增加 1 个成员.所以如果你想以原子和快速的方式完成这个,你需要做一个 Lua 脚本.应该看起来像这样(首先你得到排序集合的所有成员,然后遍历它们并增加分数):

There is no command for that, ZINCRBY can only increment for 1 member at a time. So if you want to accomplish this in an atomic and fast way you need to do a Lua script. Which should look something like this (first you get all members of the sorted set and then iterate through them and increment the score):

local zsetMembers = redis.call('zrange', KEYS[1], '0', '-1') 
for k,member in pairs(zsetMembers) do 
  redis.call('zincrby', KEYS[1], 1, member) 
end

您可以使用 EVAL 命令将此脚本推送到 Redis.

And you can push this script to Redis with the EVAL command.

这篇关于Redis,如何使用ZINCRBY增加zset的所有分数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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