Search code examples
sortingredisduplicatesredis-cli

How to sort by duplicates only


I am designing a system were every song a user plays will get logged in my redis DB. I am then creating a Top Played section on the app. The app will index my DB and pull back the most played tracks (In other words, the tracks with the most duplicates!) If rihanna got played 4 times, taylor swift 1 time and U2 played lets say 2 times. I want rihanna to be on top of the list, u2 to be second and then taylor swift to be last.

My Question:

How can i sort with redis by duplicates? Or what can i do to achieve my goal?

What i tried:

I tried doing the redis-cli sort top_played alpha but of course, no luck as thats going by Alphabet.

Below is an example of the order i want.

1. Rihanna
2. U2
3. Taylor Swift

Below is my database output:

redis-cli lrange top_played 0 7
1) "u2"
2) "u2"
3) "taylor swift"
4) "rihanna"
5) "rihanna"
6) "rihanna"
7) "rihanna"

Solution

  • You need a SORTED SET, NOT a LIST, to save your data.

    With SORTED SET, you can count how many times a track has been played. Each time when a track played, you can call ZINCRBY players 1 track-name to increase the counter of the specified track. In this way, Redis sorts all tracks with the played frequency. When you want to get top N track, just issue the following command: ZREVRANGE players 0 N-1.