Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redis get range from a Set?

Tags:

redis

nosql

In Redis is it possible to get a range of items from a Set?

I only notice SMEMBERS which gives you all the members. http://redis.io/commands#set

For example, if I have to use SMEMBERS in millions of items everytime, I just want 10 of them from index 33,456 to 33,466.

SMEMBERS will have to generate a full list of millions of items everytime I ask for 10 of them. Isn't that a performance killer? Or is it okay because Redis is fast and meant to be used that way?

like image 749
Tom Avatar asked Apr 01 '26 08:04

Tom


2 Answers

You cannot get range in set because it is unordered, hence no indexing. You can however get all members of the set using SMEMBERS

In redis-cli

SMEMBERS my_set

Also, ZRange might help you using Sorted Sets in redis

In redis-cli

ZRANGE your_key 33455 33465
like image 67
cevaris Avatar answered Apr 02 '26 22:04

cevaris


No, it is not possible, because the concept of an index does not exist in the Set data type. In fact, SMEMBERS does not guarantee you a specific order; most likely the order of the elements will be random every time you call it. Think of Sets as unordered collections of things: great if you need to store a bunch of ids that share something in common, but definitively not the data type to use if you need to implement pagination. Perhaps you are looking for Lists or Sorted Sets instead?

I recommend reading the following to understand the available data types in redis and when to use each:

  • Data types documentation
  • What are the underlying data structures used for Redis?
like image 37
Mahn Avatar answered Apr 02 '26 23:04

Mahn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!