sgon00
sgon00

Reputation: 5777

How to get subset of SMEMBERS result? Or should I use SortedSet with the same value for both score & member?

I am new to Redis. For example, if I have the following schema:

INCR id:product
SET product:<id:product> value
SADD color:red <id:product>

(Aside: I am not sure how to express a variable in Redis. I will just use <id:product> as the primary key value. In production, I will use golang client for this job)

To query products which have red color, I can do:

SMEMBERS color:red

But the problem is I just want to display 10 of them in the first page, and then next 10 in the second page and so on. How to let Redis return only part of them by specifying offset and limit arguments?

What do redis experts normally do for this case? Return all IDs even if I just want 10 of them? Is that efficient? What if it has millions of values in the set, but I only want 10?

Edited 1

Incidentally, I use sets instead of lists and sorted sets because I will need to do SINTER jobs for other queries.

For example:

SADD type:foo <id:product>

SINTER color:red type:foo

And then I will have pagination problem again. Because I actually just want to find 10 of the intersection at a time. (eg: if the intersection returns millions of keys, but actually I just want 10 of them at a time for pagination).

Edited 2

Should I use a sorted set instead? I am not sure if this is the expert choice or not. Something like:

ZADD color:red <id:product> <id:product>
ZADD type:foo <id:product> <id:product>

ZRANGE color:red 0 9        // for the first page of red color products

ZINTERSTORE out 2 color:red type:foo AGGREGATE MIN
ZRANGE out 0 9        // for the first page of red color and type foo products
  1. I have no ideas if the above way is suggested or not.
  2. What will happen if multiple clients are creating the same out sorted set?
  3. Is that meaningful to use the same value for both score and member?

Upvotes: 0

Views: 430

Answers (1)

Kevin Christopher Henry
Kevin Christopher Henry

Reputation: 48952

  1. Using sorted sets is the standard way to do pagination in Redis.

  2. The documentation of ZINTERSTORE says that: "If destination already exists, it is overwritten."

    Therefore, you shouldn't use "out" as the destination key name. You should instead use a unique or sufficiently random key name and then delete it when you're done.

  3. I'm not sure what you mean by "meaningful". It's a fine choice if that's the order you want them to be in.

Upvotes: 2

Related Questions