X

Redis for .NET Developers – Redis Sorted Sets Datatype

Redis

Redis Sorted Sets are similar to Sets, with unique feature of values stored in Set called scores. The score is used in order to take the sorted set ordered, from the smallest to the greatest score. Just like in Sets, members are unique but scores can be repeated. Sorted Sets are ideal for storing index data in Redis, or using some of the Sorted Set commands to find out how many users have authenticated to a system, or top users using the system etc.

Redis Sorted Sets Datatype – Operations

  • ZADD: Adds or updates one or more members to a Sorted Set O(log (N))
  • ZRANGE: Gets the specified range by rank of elements in the Sorted Set O(log (N) +M).
  • ZRANGEBYSCORE: Gets elements from the Sorted Sets within the range by score given values are in ascending order O(log (N) +M)
  • ZREVRANGEBYSCORE: Gets elements from the Sorted Sets within the score given O(log (N) +M)
  • ZREVRANK: The rank of the member in the Sorted Set O (log (N))
  • ZREVRANGE: Returns the specified range of elements in the Sorted Set O(log (N) + M)
  • ZREM: Removes the specified members in the Sorted Set O(M*log (N))
  • ZREMRANGEBYRANK: Removes the members in a Sorted Set within the given indexes O(log (N) * M)
  • ZREMRANGEBYSCORE: Removes the members in a Sorted Set within the given scores O(log (N) * M)
  • ZCARD: Gets the number of members in a Sorted Set O(1)
  • ZCOUNT: Gets the number of members in a Sorted Set within the score boundaries O(log (N) * M)
  • ZINCRBY: Increases the score of an element in the Sorted Set O(log (N))
  • ZINTERSTORE: Calculates the common elements in the Sorted Sets given by the specified keys, and stores the result in destination Sorted Set O(N*K) + O (M*log (M))
  • ZRANK: Gets the index of the element in the Sorted Set O(log (N))
  • ZSCORE: Returns the score of the member O(1)
  • ZUNIONSTORE: Computes the union of keys in the given Sorted Set and stores the result in the resultant Sorted Set O(N) + O(M log (M))

C# code using Redis Sorted Set Datatype

  class Program
    {
        static void Main(string[] args)
        {
            var redis = RedisStore.RedisCache;

            RedisKey topHackerKeys = "hackers";
            RedisKey alphaKey = "alphaKey";
            RedisKey destinationKey = "destKey";
            RedisKey intersectKey = "intersectKey";


            redis.KeyDelete(topHackerKeys, CommandFlags.FireAndForget);
            redis.KeyDelete(alphaKey, CommandFlags.FireAndForget);
            redis.KeyDelete(intersectKey, CommandFlags.FireAndForget);
            redis.KeyDelete(destinationKey, CommandFlags.FireAndForget);

            //According to http://www.arkhitech.com/12-greatest-programmers-of-all-time/
            var topProgrammers = new[] {
                "Dennis Ritchie",
                "Linus Torvalds",
                "Bjarne Stroustrup",
                "Tim Berners-Lee",
                "Brian Kernighan",
                "Donald Knuth",
                "Ken Thompson",
                "Guido van Rossum",
                "James Gosling",
                "Bill Gates",
                "Niklaus Wirth",
                "Ada Lovelace"
            };

            //add 12 items to the sorted set
            for (int i = 0, j = 1; i < topProgrammers.Length; i++, j++)
                redis.SortedSetAdd(topHackerKeys, topProgrammers[i], j);

            var members = redis.SortedSetScan(topHackerKeys);

            Console.WriteLine(string.Join(",\n", members)); 
            /* output 
             * Dennis Ritchie: 1, 
             * Linus Torvalds: 2,
             * Bjarne Stroustrup: 3,
             * Tim Berners-Lee: 4,
             * Brian Kernighan: 5,
             * Donald Knuth: 6,
             * Ken Thompson: 7,
             * Guido van Rossum: 8,
             * James Gosling: 9,
             * Bill Gates: 10,
             * Niklaus Wirth: 11,
             * Ada Lovelace: 12
            */


            Console.WriteLine(redis.SortedSetLength(topHackerKeys)); //output 12

            var byRanks = redis.SortedSetRangeByRank(topHackerKeys);
            Console.WriteLine(string.Join(",\n", byRanks));
            /* output 
            * Dennis Ritchie, 
            * Linus Torvalds,
            * Bjarne Stroustrup,
            * Tim Berners-Lee,
            * Brian Kernighan,
            * Donald Knuth,
            * Ken Thompson,
            * Guido van Rossum,
            * James Gosling,
            * Bill Gates,
            * Niklaus Wirth,
            * Ada Lovelace
           */


            Console.WriteLine(redis.SortedSetRank(topHackerKeys, "Linus Torvalds")); //output 1


            var byScore = redis.SortedSetRangeByScore(topHackerKeys, 1, topProgrammers.Length,Exclude.None, Order.Descending);
            Console.WriteLine(string.Join(",\n", byScore));
            /*output
             * Ada Lovelace,
             * Niklaus Wirth,
             * Bill Gates,
             * James Gosling,
             * Guido van Rossum,
             * Ken Thompson,
             * Donald Knuth,
             * Brian Kernighan,
             * Tim Berners-Lee,
             * Bjarne Stroustrup,
             * Linus Torvalds,
             * Dennis Ritchie
             */

            redis.SortedSetIncrement(topHackerKeys, "Linus Torvalds", 100);

            Console.WriteLine(redis.SortedSetScore(topHackerKeys, "Linus Torvalds")); //output 102, since it was 2 to being with

            redis.SortedSetDecrement(topHackerKeys, "Linus Torvalds", 100);

            Console.WriteLine(redis.SortedSetScore(topHackerKeys, "Linus Torvalds")); //output 2 back to original value

            redis.SortedSetAdd(alphaKey, "a", 1);
            redis.SortedSetAdd(alphaKey, "b", 1);
            redis.SortedSetAdd(alphaKey, "c", 1);

            redis.SortedSetCombineAndStore(SetOperation.Union, destinationKey, topHackerKeys, alphaKey);

            members = redis.SortedSetScan(destinationKey);
            Console.WriteLine("**********UNION**************");
            Console.WriteLine(string.Join(",\n", members));
            /* output
             * Dennis Ritchie: 1,
             * a: 1,
             * b: 1,
             * c: 1,
             * Linus Torvalds: 2,
             * Bjarne Stroustrup: 3,
             * Tim Berners-Lee: 4,
             * Brian Kernighan: 5,
             * Donald Knuth: 6,
             * Ken Thompson: 7,
             * Guido van Rossum: 8,
             * James Gosling: 9,
             * Bill Gates: 10,
             * Niklaus Wirth: 11,
             * Ada Lovelace: 12
             */
            
            redis.SortedSetCombineAndStore(SetOperation.Intersect, intersectKey, topHackerKeys, destinationKey);
            members = redis.SortedSetScan(intersectKey);

            //note it double the key scores
            Console.WriteLine("**********INTERSECT**************");
            Console.WriteLine(string.Join(",\n", members));
            /*output
             * Dennis Ritchie: 2,
             * Linus Torvalds: 4,
             * Bjarne Stroustrup: 6,
             * Tim Berners-Lee: 8,
             * Brian Kernighan: 10,
             * Donald Knuth: 12,
             * Ken Thompson: 14,
             * Guido van Rossum: 16,
             * James Gosling: 18,
             * Bill Gates: 20,
             * Niklaus Wirth: 22,
             * Ada Lovelace: 24
             */

            members = redis.SortedSetRangeByScoreWithScores(topHackerKeys, 2, 4);
            Console.WriteLine("**********RANGE BY SCORE WITH SCORES**************");
            Console.WriteLine(string.Join(",\n", members));
            /*output
             * Linus Torvalds: 2,
             * Bjarne Stroustrup: 3,
             * Tim Berners-Lee: 4
             */


            redis.SortedSetRemove(alphaKey, "a");
            members = redis.SortedSetScan(alphaKey);
            Console.WriteLine("**********REMOVE**************");
            Console.WriteLine(string.Join(",\n", members));
            /*output
             * b: 1,
             * c: 1
             */

            redis.SortedSetRemoveRangeByScore(destinationKey, 0, 11);
            members = redis.SortedSetScan(destinationKey);
            Console.WriteLine("**********REMOVE BY SCORE**************");
            Console.WriteLine(string.Join(",\n", members));
            /* output
             * Ada Lovelace: 12
             */
                        

            Console.ReadKey();
        }    
    }
  

So this covers the basic usage of Redish Sorted Sets Datatype, in the next blog post I will cover using Hyperloglog Datatype.

For the code please visit
https://github.com/taswar/RedisForNetDevelopers/tree/master/5.RedisList/RedisList

For previous Redis topics

  1. Intro to Redis for .NET Developers
  2. Redis for .NET Developer – Connecting with C#
  3. Redis for .NET Developer – String Datatype
  4. Redis for .NET Developer – String Datatype part 2
  5. Redis for .NET Developer - Hash Datatype
  6. Redis for .NET Developer - List Datatype
  7. Redis for .NET Developer - Redis Sets Datatype
Categories: C# Redis
Taswar Bhatti:
Related Post