Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy a redis sorted set to a set

Tags:

redis

How do I copy a sorted set in redis to a regular, unsorted set? Is there a redis command that can do this? I can manually iterate through the sorted set and manually insert in the unsorted set, but it seems like there might be a better way to do this.

like image 800
Scotty Allen Avatar asked Jan 12 '13 20:01

Scotty Allen


1 Answers

I don't think there is any command to do this directly.

But you can write simple lua script to do it on server instead downloading the sorted sets content to client and then pushing it back to new set.

Redis commands:

SCRIPT LOAD "for i,v in ipairs(redis.call('zrange', KEYS[1], 0, -1)) do redis.call('sadd', KEYS[2], v) end"
ZADD zset 1 first
ZADD zset 2 second
ZADD zset 3 third
EVALSHA dd1c22a22108d758b93c26eb92d1ef2933cec314 2 zset set
SMEMBERS set

Result:

"dd1c22a22108d758b93c26eb92d1ef2933cec314"
(integer) 0
(integer) 0
(integer) 0
(nil)
1) "second"
2) "first"
3) "third"

SCRIPT LOAD defines the script and returns its sha hash, EVALSHA than executes. Arguments are 2 to indicate that 2 key names follows, first is sorted set to copy from, second is set to copy to.

like image 61
m6k Avatar answered Sep 27 '22 21:09

m6k