how to pop multiple items from list

2,881 views
Skip to first unread message

Tony Wang

unread,
Jun 25, 2017, 2:35:25 PM6/25/17
to Redis DB
Hi all

Is it possible to pop multiple items from a Redis list? I know that spop could do it with set. 

In my case, I have a producer server and a Redis server, a local machine as a consumer. Because of poor network between local consumer and Redis server, the consuming speed with rpop seems much slower than producing. 15-30 minutes slower in one hour. So I curious if I could get multiple items within one connection from Redis list, or is there any other better solution to speed up?


Thanks !

Joshua Scott

unread,
Jun 26, 2017, 1:29:56 PM6/26/17
to Redis DB
You can use LRANGE and LREM inside a MULTI/EXEC to atomically return and remove a certain number of elements from a list.
https://redis.io/commands/lrange
https://redis.io/commands/lrem
https://redis.io/commands/multi

127.0.0.1:6379> RPUSH mylist a b c d
(integer) 4
127.0.0.1:6379> LRANGE mylist 0 -1
1) "a"
2) "b"
3) "c"
4) "d"
OK
127.0.0.1:6379> LRANGE mylist 0 1
QUEUED
127.0.0.1:6379> LTRIM mylist 2 -1
QUEUED
1) 1) "a"
   2) "b"
2) OK
127.0.0.1:6379> LRANGE mylist 0 -1
1) "c"
2) "d"

Itamar Haber

unread,
Jun 26, 2017, 1:53:28 PM6/26/17
to Redis DB
...or use Lua :)

$ cat lpopn.lua
local key = KEYS[1]
local n = tonumber(ARGV[1])

local rep = {}
local ele = 1

while n > 0 and ele do
  ele = redis.call('LPOP', key)
  n = n - 1
  if ele then
    rep[#rep+1] = ele
  end
end

return rep
$ redis-cli lpush l a b c d e
(integer) 5
$ redis-cli --eval lpopn.lua l , 2
1) "e"
2) "d"
$ redis-cli --eval lpopn.lua l , 4
1) "c"
2) "b"
3) "a"

--
You received this message because you are subscribed to the Google Groups "Redis DB" group.
To unsubscribe from this group and stop receiving emails from it, send an email to redis-db+unsubscribe@googlegroups.com.
To post to this group, send email to redi...@googlegroups.com.
Visit this group at https://groups.google.com/group/redis-db.
For more options, visit https://groups.google.com/d/optout.



--

Itamar Haber | Chief OSS Education Officer
Redis Labs ~/redis

Mobile: +972 (54) 567 9692
Twitter: @itamarhaber
Skype: itamar.haber

Reply all
Reply to author
Forward
0 new messages