Redis Hash Datatype for .NET developers

Redis Hash Datatype are similar to Dictionary in C#. Redis Hash datatype is a mapping of key as string and value as a string. Redis hashes are memory optimized.

var hashKey = “hashKey”;
  HashEntry[] redisMerchantDetails= {
    new HashEntry(“Name”, “Ravindra Naik”),
    new HashEntry(“Age”, 26),
    new HashEntry(“Profession”, “Software Engineer”)
  };
  redis.HashSet(hashKey, redisMerchantDetails);
  if (redis.HashExists(hashKey, “Age”))
  {
    var age= redis.HashGet(hashKey, “Age”); //Age is 26
  }
  var allHash = redis.HashGetAll(hashKey);
  //get all the items
  foreach (var item in allHash)
  {
    //output
    //key: Name, value: Ravindra Naik
    //key: Age , value: 26
    //key: Profession, value: Software Engineer
    Console.WriteLine(string.Format(“key : {0}, value : {1}”, item.Name, item.Value));
  }
  //get all the values
  var values = redis.HashValues(hashKey);
  foreach (var val in values)
  {
    Console.WriteLine(val); //result =Ravindra Naik, 26, Software Engineer
  }
  //get all the keys
  var keys = redis.HashKeys(hashKey);
  foreach (var k in keys)
  {
    Console.WriteLine(k); //result = Name, Age, Profession
  }
  var len = redis.HashLength(hashKey);  //result of len is 3
            
  if (redis.HashExists(hashKey, “Age”))
  {
    var age= redis.HashIncrement(hashKey, “Age”, 1); //year now becomes 27
    var age2= redis.HashDecrement(hashKey, “Age”, 1.5); //year now becomes 25.5
  }
  • Here is how you can save, retrieve, update, increment and decrement the value.
  • HashExists takes O(1) for checking the existence of a field, HashGetAll takes O(n) to get all n values of hash key and O(1) if n is small.

 

Thanks for dropping by !!! Feel free to comment to this post or you can also drop me an email at naik899@gmail.com.

Leave a Reply

Your email address will not be published. Required fields are marked *