2
votes

I'm using redis to keep track of daily views for a subject in a message board I'm building. I have another field in the subject model that stores all time views for a subject.

I'm using a sorted set to track the subject views because it allows me to easily and quickly display the most popular subjects today.

I want to create a task that runs at midnight - iterating through the sorted set - adding the view counts for a particular subject that day to the subjects all time views. Then I want to remove the member after I've updated that subject's views.

What is an elegant way to iterate through all the members in a sorted list and update their related (by ID) active record entity?

This is how I'm adding a view for a subject:

def self.record_view(id)
  REDIS.zincrby("views", 1, id)
end

This is how I'm getting the view count for a subject:

def views
   REDIS.zscore("views", self.id).to_i
end
1

1 Answers

4
votes

You can use a ZRANGE and WITHSCORES for getting all keys and scores into the Ruby land, where you can iterate them any way you want.

REDIS.zrange('views', 0, -1, withscores: true)
# => an array, [key1, score1, key2, score2, ...]

You can also be smart and use ZRANGE with ZCARD to get data in batches.