Redis Sorted Sets and .NET

Redis has one data type which is meant for ordered data and it's called Sorted Sets (or ZSET). Sorted Sets are typically used for ranking boards and to keep track on points or votes. Sorted Sets consist from three parts:

  1. Key - Like all Redis values, Sorted Sets also has a key which identifies collection
  2. Score - Value/Rank which can be used in sorting
  3. Member - Actual data, for example serialized object or id of object.

Sorted Set isn't only a way to sort data. Individual scores can be increased and decreased, members can be counted using their score value and so on. However in this example I will concentrate on sorting, because it's very common need. I will store three objects into Sorted Set and fetch them in order.

For this example we will need two Nuget packages:
  1. StackExchange.Redis
  2. Newtonsoft.Json

I will use following class to demonstrate Sorted Sets:
public class MyObject
{
    public long Id { get; set; }
    public string Name { get; set; }
    public Address ObjectAdress { get; set; }
    public int Age { get; set; }
}
Next I will create three instances from MyObject class, store them into Sorted Set and fetch them in ascending order.
static void Main(string[] args)
{
   // Setup code
   var redis = ConnectionMultiplexer.Connect("localhost");
   var db = redis.GetDatabase(2);
   // Create a three objects which are stored into database
 
var firstStoredObject = new MyObject
   {
      ObjectAdress = new Address() {StreetAddress = "Evergreen 1", ZipCode = "000100"},
      Id = db.StringIncrement("UniqueIdForObject"),
      Name = "My first object",
      Age = 32
   };
 
var secondStoredObject = new MyObject
   {
      ObjectAdress = new Address() {StreetAddress = "Evergreen 2", ZipCode = "000100"},
      Id = db.StringIncrement("UniqueIdForObject"),
      Name = "My second object",
      Age = 42
   };
   

var thirdStoredObject = new MyObject    {
      ObjectAdress = new Address() {StreetAddress = "Evergreen 3", ZipCode = "000100"},
      Id = db.StringIncrement("UniqueIdForObject"),
      Name = "My third object",
      Age = 18
   };
 
// Add objects into sorted list. Use age as a sorting value
   db.SortedSetAdd("sortedObjects", JsonConvert.SerializeObject(firstStoredObject), firstStoredObject.Age);
   db.SortedSetAdd("sortedObjects", JsonConvert.SerializeObject(secondStoredObject), secondStoredObject.Age);
   db.SortedSetAdd("sortedObjects", JsonConvert.SerializeObject(thirdStoredObject), thirdStoredObject.Age);

 // Read values from database. Fetch objects in ascending order
   var redisValueSorted = db.SortedSetRangeByRank(key: "sortedObjects", start: 0, stop: -1,order: Order.Ascending);
   // Print all objects into console
   redisValueSorted.ToList().ForEach(value => Console.WriteLine(value));
 
// Wait for user to press something before closing console application
   Console.ReadKey();
   }
Execution of the program displays the results in ascending order

I think that Sorted Sets provide an easy way to solve simple sorting problems. However when you need to sort objects with multiple values or change sorting target, then things get complicated. When I need to work with sorting, I usually fetch data in chunks (pagination) and sort them in .NET.

13 comments:

  1. Great blog. All posts have something to learn. Your work nd is very good ai appreciate you and hoping for some more informative posts.keep writing.
    Web development Company in India Company | Web development Company Bangalore
    Web development Company in Bangalore | Responsive Web development

    ReplyDelete
  2. As a website design company .Web India Market offer a full-circle approach in responsive website designing and web development services. Our website designing services covers Strategic Planning, Business Intelligence, Creative Application Development, Digital Marketing, SEO services and e-commerce solutions.

    ReplyDelete
  3. Web India Market
    Web India Market offer a full-circle approach in responsive website designing and web development services. Our website designing services covers Strategic Planning, Business Intelligence, Creative Application Development, Digital Marketing, SEO services and e-commerce solutions.

    ReplyDelete

  4. Web Design Sydney: It is a great sharing...I am very much pleased with the contents you have mentioned. I wanted to thank you for this great article. .Logo Design Sydney,Logo Design in Coimbatore,Brochure Design in Coimbatore

    ReplyDelete
  5. This article was a really interesting read, information has been presented in a clear and concise manner. Thanks!
    Website Development services Bangalore
    Web Design Services in Bangalore
    Top SEO Services in Bangalore

    ReplyDelete

  6. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Online Training from India. or learn thru ASP.NET Essential Training Online . Nowadays Dot Net has tons of job opportunities on various vertical industry.
    JavaScript Online Training from India

    ReplyDelete
  7. Spark interact web design sydney is recruiting. check out the great new positions and apply online now

    ReplyDelete
  8. Spark Interact Custom web design in Sydney with 12+ years experience in Web development & WordPress. With High quality Website Design & Affordable prices . Call us
    website design service provider in Sydney Australia

    ReplyDelete
  9. I am happy to find this post Very useful for me, as it contains lot of information. I Always prefer to read The Quality and glad I found this thing in you post. ThanksWeb Design Kuala Lumpur

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete