Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy values from one list into another in Redis?

Tags:

redis

I have a Redis list with some values

LRANGE LIST 0 -1
> 1
> 2
> 3

And I want to RPUSH these values into another list. How can this be done? I've tried to do it with MULTI and EXEC, but with no results.

like image 866
amb Avatar asked Feb 21 '13 09:02

amb


2 Answers

A server-side Lua script is more convenient that a WATCH/MULTI/EXEC block to implement this kind of operation.

Here is an example of a script with takes two lists (source and destination) as parameters, and two integers defining a range in the source list. It then pushes the corresponding items to the destination list.

> rpush foo 1 2 3 4
(integer) 4
> rpush bar x
(integer) 1
> eval "local res = redis.call( 'lrange', KEYS[1], ARGV[1], ARGV[2] ); return redis.call( 'rpush', KEYS[2], unpack(res) ); "  2  foo bar 0 -1
(integer) 5
> lrange bar 0 -1
1) "x"
2) "1"
3) "2"
4) "3"
5) "4"
like image 80
Didier Spezia Avatar answered Oct 01 '22 09:10

Didier Spezia


if you want to move the key to a new key, you can use RENAME command , the only will change the key name RENAME COMMAND

like image 31
Bartolome Serapio Avatar answered Oct 01 '22 11:10

Bartolome Serapio