Reputation: 787
I want to keep the viewCount of posts in Redis, While I'm not sure which of the following approaches is more performant:
For each post have a redis unique key and store the viewCount as value for it:
For example have the key viewCount856
with value 1000 which means the viewCount of post with id 856 is 1000.
Have a redis sorted set (zset) as described here and use each postId as score and the associated viewCount as value for that score. For example have a zset called viewCount
and add all the posts and their viewCount to this set having their id as score.
Any other data type that is performant for this use-case and I hadn't thought of.
I would appreciate any other suggestions that will help implementing this in the best way.
Upvotes: 1
Views: 1315
Reputation: 50052
... implementing this in the best way
There is no "best way" - it is always a tradeoff so you need to pick what's important to you. Important means how you'll be accessing the data - with approach #1 you'd only be able to fetch a single counter, whereas with #2 you'd be able to use ranges.
If you don't need ranges, I'd go with #1 and consider using Hashes to optimize memory consumption (see https://redis.io/topics/memory-optimization#using-hashes-to-abstract-a-very-memory-efficient-plain-key-value-store-on-top-of-redis for the details). That will give you constant time access.
However, if ranges are required (e.g. top-n viewed posts), a Sorted Set will do nicely. The tradeoff here is more memory and O(n*logn) access.
Upvotes: 3