Skip to content

Redis Data Type : Hashes

Redis hashes are record types structured as collections of field-value pairs. You can use hashes to represent basic objects and to store groupings of counters, among other things.

Create a Hash

You can create single field Hash by using HSET and create multiple fields Hash by HMSET

#create a hash with single field> HSET bike1 type "citybike"> HSET bike1 color "blue"

#create a hash with multiple fields> HMSET bike2 type "mountainbike" color "silver" price 3000

Get a Value from a Hash

You can use HGET to retrieve value of field and use HMGET to retrieve values of multiple fields.> HGET bike1 type
"citybike"> HGET bike color
"blue"> HMGET bike2 type color price
1) "mountainbike"
2) "silver"
3) "3000"

Update Numeric Value in a Hash

You can use HINCRBY to update value of “price” field .> HINCRBY bike2 price 200      # +200
(integer) 3200> HINCRBY bike2 price -200     # -200
(integer) 3000

Get All Field-Value Pairs from a Hash

You can use HGETALL to retrieve all the field-value pairs from a specific Hash.> HGETALL  bike1
1) "type"
2) "citybike"
3) "color"
4) "blue"> HGETALL bike2
1) "type"
2) "mountainbike"
3) "color"
4) "silver"
5) "price"
6) "3000"

Check if a field exists

You can use HEXIST to check whether a field exists. If exists, it will return 1. Otherwise, it will return 0.> HEXISTS bike1 price
(integer) 0> HEXISTS bike1 color
(integer) 1

Get the Number of Fields in a Hash

You can use HLEN to find out the number of fields in a hash.

HLEN  bike2
(integer) 3

Delete fields from a Hash

You can use HDEL to delete any field in a Hash.

HDEL bike2 price                        #delete one field from  Hash bike2
(integer) 1> HDEL bike1 type  color    #delete all fields from Hash bike1
(integer) 2> HLEN bike1
(integer) 0