Reputation: 7023
I have an use case in my website wherein i am required to store user specific day to day statistics in the form like
user:1 {field1: value, field2: value, field3: value}
The above representation goes for n users Currently I have implemented it using sorted sets with fields representing value of the sorted set and value representing score. I am also setting a per day expiry on these keys.
Considering the overhead of individual key creation and expiry when number of users turn out to be large, i am thinking of an alternate representation like below using hashes considering its advantages like the following
Map of field1 <user_id, value>
Map of field2 <user_id, value>
Map of field3 <user_id, value>
Also a map for expiry <user_id, last_updated_time>
I am confused whether to persist with the existing implementation or implement the use-case with hashes. Can someone please help?
Upvotes: 2
Views: 5104
Reputation: 5981
If you don't need to sort the fields by value, using a sorted set is probably not the best solution for your problem. Using a hash for storing a user field values is definitely more idiomatic.
hmset user:1 field1 value1 field2 value2 field3 value3
A sorted set could be used to store the expiry dates. The key is the user id, the value the unix timestamp of the expiration date. For user:1 the expiration date will be set to 1234567890 by a command like:
zadd expirations 1 1234567890
It would allow you to get the list of expired keys for the current time in one operation, using ZRANGEBYSCORE
UPDATE
You could use simple keys to store your data:
SET user:1:field1 value1
SET user:1:field2 value2
SET user:1:field3 value3
It would allow you to let Redis taking care of expiration: EXPIRE user:1:field1 EXPIRE user:1:field2 EXPIRE user:1:field3
Redis algorithm for deleting expired keys wont introduce any noticeable delay. It's certainly better to use it than implementing your own. Look at EXPIRE documentation if you need more details.
You could also use EXPIREAT if you want to specify the expiration date instead of a duration.
Upvotes: 5