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
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.

The best way to predict the future is to implement it.

2 kommenttia:

  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

  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.