2

Given I have a list stored in a key "A", how can I duplicate that list in a different key "B"?

I know that for non list values, I can "get", and then "set". But for lists when I try to get it, I see the WRONGTYPE operation error.

Hommer Smith
  • 26,772
  • 56
  • 167
  • 296
  • similar question: https://stackoverflow.com/questions/14998281/how-to-copy-values-from-one-list-into-another-in-redis – kai Nov 02 '20 at 08:20

3 Answers3

4

Redis enables 5 different data structures, such as:

  • Key values
  • Strings
  • Hashs
  • Lists
  • Sets

Each of the data structure has its own commands.

In order to get the current list you should use the LRANGE command.

The prefix L referes to the List data structure.

(Redis Set data structure has a related command to range by using SETRANGE)

If you read the Redis LRANGE documentation you will understand how to use it.

Here is the brief code you may use:

LRANGE mylist 0 -1

Where mylist is the list you get the values from.

The offsets start and stop are zero-based indexes, with 0 being the first element of the list (the head of the list), 1 being the next element and so on.

-1 is used to describe the last element in the list.

Now you should use the LPUSH or RPUSH depends on the list side you wish to insert the old elements into the new list.

Rotem
  • 1,381
  • 1
  • 11
  • 23
2

You should use LRANGE to get all elements of the first list, then use LPUSH or RPUSH to put these elements into the second list.

for_stack
  • 21,012
  • 4
  • 35
  • 48
1

Another way to duplicate a key's value, regardless the data structure, is to DUMP it and then RESTORE it into the new key. In most cases this approach is also the quickest.

Itamar Haber
  • 47,336
  • 7
  • 91
  • 117