Rebe
Rebe

Reputation: 175

Redis modeling for sorting strings by count

I have been storing and incrementing download counters like this:

INCRBY downloads:<filename> 1

But now I want to get downloads:* sorted by value so I can display a top downloads list.

I get the feeling I can probably store this better. I fooled around with:

ZINCRBY downloads 1 <filename>
ZREVRANGEBYSCORE downloads +inf -inf

Which does seem to give me the sorted list I want (most downloads to least) but it only returns the <filename>. It appears I would have to query the counts separately.

Basically, in SQL terms, if i may:

select filename, count(*) from downloads

How can I structure my Redis data to make that query possible/easy?

Upvotes: 1

Views: 223

Answers (1)

antirez
antirez

Reputation: 18514

You can get the top films with ZREVRANGE z 0 -1 WITHSCORES instead, that will also return the scores.

Also this allows you to easily to get the "TOP N" films using "N-1" instead of "-1" in the above command.

Upvotes: 4

Related Questions