3

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?

Tom
  • 15,781
  • 14
  • 69
  • 111
  • 2
    A set is a non ordered data structure. Fetching items by range in a set is meaningless. There is no concept of index. Perhaps you should use a list or a sorted set? – Didier Spezia Oct 08 '12 at 18:49
  • 2
    FYI: as of [Redis 2.6.0-RC8](http://antirez.com/post/redis-2.6-rc8-out.html) there is now a `SRANDMEMBER ` command that *returns multiple random elements* that you may find useful. – deltheil Oct 08 '12 at 20:56
  • 1
    You might achieve your goal using the relatively feature-rich _sort_ command: http://redis.io/commands/sort – Ofer Zelig Oct 08 '12 at 23:11

2 Answers2

4

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
cevaris
  • 5,671
  • 2
  • 49
  • 34
2

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:

Community
  • 1
  • 1
Mahn
  • 16,261
  • 16
  • 62
  • 78