Search code examples
listredisprefix

Redis get list items and append prefix


I have a list of Strings in redis -

LPUSH keys 1 2 3 4

And reading is pretty easy -

LRANGE keys 0 3

1) "4"
2) "3"
3) "2"
4) "1"

How can I read from list where each value has some specified string prepended to it? In above scenario I want my output as -

1) "Key:4"
2) "Key:3"
3) "Key:2"
4) "Key:1"

Solution

  • You will need to use lua - https://redis.io/commands/eval

    You can search for lua documentation and modify the code below according your needs.

    Here is an example:

    127.0.0.1:6379> LPUSH keys 1 2 3 4
    (integer) 4
    127.0.0.1:6379> LRANGE keys 0 3
    1) "4"
    2) "3"
    3) "2"
    4) "1"
    127.0.0.1:6379> EVAL 'local res = {} local ttt=redis.call("LRANGE", "keys", "0", "10") for k, v in pairs(ttt) do table.insert(res, "Key:" .. v) end return res' 0
    1) "Key:4"
    2) "Key:3"
    3) "Key:2"
    4) "Key:1"