93

I have simple redis list key => "supplier_id"

Now all I want it retrieve all value of list without actually iterating over or popping the value from list

Example to retrieve all the value from a list Now I have iterate over redis length

element = []
0.upto(redis.llen("supplier_id")-1) do |index| 
  element << redis.lindex("supplier_id",index)
 end

can this be done without the iteration perhap with better redis modelling . can anyone suggest

Viren
  • 5,812
  • 6
  • 45
  • 98
  • Can you describe what you want to do with the redis list? maybe you should use a different key type. – eyossi May 22 '12 at 13:43
  • @eyossi The idea is to create a select tag with options value been the supplier_id presented databases since retrieve of record in relational databases was expensive that y we thought of dumping all the supplier_id in redis when the are created and delete them when they are destroyed from database – Viren May 22 '12 at 14:26
  • There is official Redis documentation on Lists which explains this in more detail. More at https://redis.io/topics/data-types-intro#redis-lists – raksheetbhat Aug 12 '19 at 10:33

2 Answers2

219

To retrieve all the items of a list with Redis, you do not need to iterate and fetch each individual items. It would be really inefficient.

You just have to use the LRANGE command to retrieve all the items in one shot.

elements = redis.lrange( "supplier_id", 0, -1 )

will return all the items of the list without altering the list itself.

Didier Spezia
  • 70,911
  • 12
  • 189
  • 154
  • 3
    If by memory efficient you mean incrementally iterating on the items, it can be implemented using llen and looping on lrange calls, but it will increase the number of roundtrips, and you will loose consistency. – Didier Spezia May 17 '13 at 09:39
  • Everytime i try this i get the error "Invalid argument(s)" – Ricardo Nov 02 '14 at 17:32
  • @DidierSpezia This returns in reverse order of my addition into redis. Is there a way to get output in order of insertion? – user1692342 Apr 19 '15 at 08:53
  • 2
    If you insert with RPUSH instead of LPUSH, it will be in the same order. – Didier Spezia Apr 19 '15 at 09:56
2

I'm a bit unclear on your question but if the supplier_id is numeric, why not use a ZSET?

Add your values like so:

ZADD suppliers 1 "data for supplier 1"  
ZADD suppliers 2 "data for supplier 2"  
ZADD suppliers 3 "data for supplier 3"  

You could then remove everything up to (but not including supplier three) like so:

ZREMRANGEBYSCORE suppliers -inf 2

or

ZREMRANGEBYSCORE suppliers -inf (3

That also gives you very fast access (by supplier id) if you just want to read from it.

Hope that helps!

mkgrunder
  • 941
  • 1
  • 7
  • 13