Is there any way to pop all list items from redis list at once?
Asked Answered
A

4

5

I want to pop all list items from redis list at once.

I don't want to call lpop or rpop method by when the list is empty because it seems to be inefficient sending requests multi-time to redis-server.

I also know that I can get all lists with lrange method but not popping items.

Could you suggest me?

I just want to pop and get items in a list by one request to redis-server.

Appressed answered 28/12, 2015 at 12:40 Comment(0)
S
5

As Itamar Haber said, use lrange and del. In pipe mode it will be done as a single command.

LRANGE key 0 -1
DEL key
Slade answered 28/12, 2015 at 16:55 Comment(3)
This seems to create a race condition when other processes are pushing to the list. e.g. the list gets an item added in between redis executing LRANGE and DEL by another application/process.Abuse
No, if these commands sent in PIPE mode. Or you can use MULTI & EXEC.Slade
Redis pipelining is not atomic.Appressed
C
5

Redis doesn't have an POPALL command, but with an embedded Lua script you can easily do that like this for example:

local reply = redis.call('LRANGE', KEYS[1], 0, -1)
redis.call('DEL', KEYS[1])
return reply
Corkage answered 28/12, 2015 at 14:13 Comment(0)
S
5

As Itamar Haber said, use lrange and del. In pipe mode it will be done as a single command.

LRANGE key 0 -1
DEL key
Slade answered 28/12, 2015 at 16:55 Comment(3)
This seems to create a race condition when other processes are pushing to the list. e.g. the list gets an item added in between redis executing LRANGE and DEL by another application/process.Abuse
No, if these commands sent in PIPE mode. Or you can use MULTI & EXEC.Slade
Redis pipelining is not atomic.Appressed
T
1

What about

RENAME key key_processing
LRANGE key_processing 0 -1
DEL key_processing

This way we pop all the items and still maintain the original key "empty" but anyone can write/push a new element to the key list (for future processing)

Tharpe answered 22/7, 2022 at 16:2 Comment(0)
N
1

As of redis 6.2.0, you can lpop 'count' from key.

LPOP KEY N

This will pop N elements from KEY. You can use LLEN to count the length of list

LLEN KEY

Using redis pipeline and combining these two commands will pop all elements in a single command.

Northwesterly answered 21/2, 2023 at 13:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.