Reputation: 2155
Is it possible (or is there another idiomatic way) to ZADD a member with a score of the highest existing score plus one?
For example:
> FLUSHDB
> ZADD key 1 one
> ZADD key * mem
> ZSCORE key mem
1) "2"
Upvotes: 0
Views: 416
Reputation: 22906
You can use zrevrange
to get the largest score, and then call zadd
to set the score to be largest + 1
. There's no built-in way to do that. However, you can write a Lua script to do the job:
local key = KEYS[1]
local field = ARGV[1]
local score = ARGV[2]
if score then
-- client specifies a score, use it
redis.call('zadd', key, score, field)
else
-- get the largest score in the sorted set
local largest = redis.call('zrevrange', key, 0, 0, 'withscores')
score = largest[2]
if score then
-- update the score
score = score + 1
else
-- the sorted set is empty, set a default score
score = 0
end
redis.call('zadd', key, score, field)
end
Try it: ./src/redis-cli --eval t.lua key , field
Upvotes: 2