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