Search code examples
data-structuresredisredis-cli

Redis - data structure to insert string one by one and remove all at once


I am new to Redis and found that there are various data structures supported in Redis and based on requirement we can choose any one of them. My requirement is to insert strings one by one to a list(key-list) and wants to retrieve(and remove) all at once. And also I want to do this very frequently, so trying to find an optimal way. Which data structure/way will be better for this? Thank you in advance

P.S: I don't want to remove the key when retrieving, I just need to retrieve and empty the list.


Solution

  • Sounds like you should use a List. Add to the list with either LPUSH or RPUSH, then retrieve everything with LRANGE and DEL the key.

    P.S. A key in Redis, such as one storing the List, can't be empty. Once you remove all of the list's members, the key itself no longer exists hence you can just delete it instead of trying to empty it.

    Updated with an answer to the OP's comment: not really, there are no free lunches and regardless the method you'll have to do O(N) reads and deletes. There are cases where performing just one iteration is preferable, e.g. to reduce network communication, but this isn't one of them.

    Any way, the closest you can get in terms of functionality to a combination of both is with Lua. Note, however, that this will not necessarily perform better then LRANGE & DEL:

    $ cat popall.lua 
    local r={}
    local e=redis.call('LPOP', KEYS[1])
    while e do
        r[#r+1]=e
        e=redis.call('LPOP', KEYS[1])
    end
    return r
    $ redis-cli LPUSH list 1 2 3 4 5 6 7 8 9
    (integer) 9
    $ redis-cli --eval popall.lua list
    1) "9"
    2) "8"
    3) "7"
    4) "6"
    5) "5"
    6) "4"
    7) "3"
    8) "2"
    9) "1"
    $ redis-cli EXISTS list
    (integer) 0