Redis Hash Datatype are similar in C# world as Dictionary e.g Dictionary. Just like in C# redis stores map of attributes using key value pair. One thing to note is in Redis a Hash both the field name and the value are strings. Therefore, a Hash Datatype is a mapping of a string to a string.

Memory Optimized

Redis Hashes are memory-optimized. Their optimization is based on the hash-max-ziplist-entries and hash-max-ziplist-value configurations. Internally in Redis, a Hash can be a ziplist or a hash table. So what does it mean for a ziplist? Basically it is designed to be memory efficient dually linked list and integers are stored as real integers rather than a sequence of characters.

Speed

Something to note is a hashtable in Redis has a constant time lookup, the down side is it is not memory optimized, while the ziplist is memory optimized but the lookup time are not constant. To read more on Redis Memory Optimization please view Redis documentation.

So which one is used when?

  • The ziplist is by default when the number of fields do not exceed the configuration ones in hash-max-ziplist-entries
  • The hashtable is used when a the size or any of its values exceeds

Redis Hash Datatype – Operations

  • HSET: Sets the value of a field for a key O(1).
  • HGET: Gets the value of a field for a key O(1).
  • HLEN: Gets the number of fields for the key O(1).
  • HMGET: Gets the values for the fields for a key O(N), where N is the number of fields and O (1) if N is small.
  • HMSET: Sets multiple values for respective fields for a key O(N), where N is the number of fields and O (1) if N is small.
  • HGETALL: Gets all the values and fields for a key O(1).
  • HKEYS: Gets all the fields in the Hash for the key O(1).
  • HEXISTS: Checks for the existence of a field for a key O(1).
  • HVALS: Gets all the values in the Hash for the key O(N), where N is the number of fields and O(1) if N is small.
  • HSETNX: Sets the value against the field for the key provided the field does not exist O(1).
  • HDEL: Deletes the fields for a key O (N), where N is the number of fields and O(1) if N is small.
  • HINCRBY: Increments the value (provided the value is an integer) of a field for a key O(1).
  • HINCRBYFLOAT: Increments the value if value is a float of a field for a key O(1).

C# code using Redis Hash Datatype

For the code please visit
https://github.com/taswar/RedisForNetDevelopers/tree/master/4.RedisHashes

So this covers the basic usage of Redish Hash Datatype, in the next blog post I will cover using List Datatype.

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