Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


What are hashes in Redis ?

Siddharth Singh

Redis Hash is a data structure available in Redis that stores the mapping of keys to values. Here, both the key and the value are strings.

  • The key-value pairs are unordered.
  • Keys are unique and no duplicates are allowed.

Conceptually, it is similar to HashMap in Java and Dictionary in C#. It is implemented as a Hash table and handles collisions by Chaining.

A Redis Hash can store up to 4 billion key value pairs.

If the value is Integer, Redis hash allows you to atomically increment or decrement the value.

It is a highly performant data structure and supports adding a key, removing a key, and checking membership of key in constant time or O(1).

Let’s create a Redis Hash for a shopping cart object named Shopping_cart:111 using the HSET command:

> HSET shopping_cart:111 Product "Shoes" price 100 Quantity 10

To view all the key-values pairs in the Hash, we can use the HGETALL command:

> HGETALL shopping_cart:111
1) "Product"
2) "Shoes"
3) "price"
4) "100"
5) "Quantity"
6) "10"
Visual Representation of Redis Hash

To view an individual key, the HGET command is used. For example, if we only want to view the name of the product we can use the command below:

> HGET shopping_cart:111 Product

The HDEL command is used to delete an individual key-value pair:

> HDEL shopping_cart:111 Product
(integer) 1

> HGETALL shopping_cart:111
1) "price"
2) "100"
3) "Quantity"
4) "10"

If the hash size is small (it has few elements with small values), then Redis encodes it in memory, in special way, that makes it very memory efficient.

Some other useful commands are:

Command Short Description
HEXISTS checks whether or not a hash key exists.
HINCRBY Increments the integer value of a hash field.
HINCRBYFLOAT Increments the float value of a hash Key by the given amount.
HKEYS Gets all the keys in a hash.
HLEN Gets the number of keys in the hash.
HVALS Gets all values in the hash.

Redis Hashes, as a collection of key-value pairs, are used to store objects such as users, cart, session, visitors, etc. in a performant and memory efficient way.



View all Courses

Keep Exploring