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
127.0.0.1:6379> HSET bike1 type "citybike"
127.0.0.1:6379> HSET bike1 color "blue"
#create a hash with multiple fields
127.0.0.1:6379> 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.
127.0.0.1:6379> HGET bike1 type
"citybike"
127.0.0.1:6379> HGET bike color
"blue"
127.0.0.1:6379> 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 .
127.0.0.1:6379> HINCRBY bike2 price 200 # +200
(integer) 3200
127.0.0.1:6379> 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.
127.0.0.1:6379> HGETALL bike1
1) "type"
2) "citybike"
3) "color"
4) "blue"
127.0.0.1:6379> 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.
127.0.0.1:6379> HEXISTS bike1 price
(integer) 0
127.0.0.1:6379> 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
127.0.0.1:6379> HDEL bike1 type color #delete all fields from Hash bike1
(integer) 2
127.0.0.1:6379> HLEN bike1
(integer) 0