Having made up my mind to use Weather Express as a playground, the next thing I decided to add was a page which lists the top 5 most searched cities. This is a very easy functionality to achieve using Redis.
I used Sorted Sets to achieve this using ZINCRBY to increment the weight for a member for each hit. The beauty of this command is that it defaults the weight to 0 if the member isn’t present initially. So there is no need to check for the presence of a member before incrementing its weight. The equivalent command is:
>ZINCRBY most-visited 1 CITY_NAME #Increment by 1
While fetching the result, I used the ZREVRANGEBYSCORE feature to fetch the results. This fetches the members in the decreasing order of their scores.
>ZREVRANGEBYSCORE most-visited +inf -inf limit 0 4 withscores # 0 is offset and 5 is the number of results to fetch
I loved the elegance with which Redis was able to solve this problem. You can see the code at work here.