Narek
Narek

Reputation: 39871

Redis - How to store the result of zrange query as another ordered set

For example I create a sorted set with this command:

zadd key1 1 u1 2 u2 3 u3

Now I to query last 2 items and store under other key, say key2. I know that I need to query like this:

zrange key1 -2 -1

but I don't know how to store the result with key2. Sorry for noob question, I am new to Redis, just 2 hours :)

Upvotes: 2

Views: 1776

Answers (2)

feketegy
feketegy

Reputation: 721

ZRANGESTORE was added to Redis 6.2

Upvotes: 0

Itamar Haber
Itamar Haber

Reputation: 49942

While Redis does not have a built-in command to do that, you can get away easily and safely with a Lua script. This one is a just a little extra tricky because the reply from ZRANGE needs swapping between the pairs of member-score to be used as input for ZADD.

local src, dst = KEYS[1], KEYS[2]
local from, to = ARGV[1], ARGV[2]

local payload = redis.call('ZRANGE', src, from, to, 'WITHSCORES')

for i = 1, #payload/2 do
  payload[2*i-1], payload[2*i] = payload[2*i], payload[2*i-1]
end

return redis.call('ZADD', dst, unpack(payload))

For details on how to use Lua in Redis see the EVAL commmand.

Upvotes: 3

Related Questions