Redis- Hashes data type

  • Redis hashes is powerful and simple datatype.
  • Hashes are similar to json 
  • Having Field:value mapping (field:value)
  • A hash can contains > 4 billion elements.
  • Used to store the object properties like student (rollno, name, class..etc)

1. How to create a data with hashes data type

Create hash stored data key value: HSET <key> <field1> "<value1>" <field2>  "<value2>" <field3> "<value3>"...
Get data with hash datatype key   : HGET <key> <field>
Get data with hash datatype key  for all data of the object: HGET <key> <field>
Check the type of datatype: TYPE<key>
Check the length of hash stored key data type: TYPE<key>

pawan@LAPTOP-SG31RIME:/mnt/d/PAWAN$ redis-cli
127.0.0.1:6379> HSET student rollno 1 name "ABC" class 5
(integer) 3
127.0.0.1:6379> HGET student rollno
"1"
127.0.0.1:6379> HGET student name
"ABC"
127.0.0.1:6379> HGET student class
"5"
127.0.0.1:6379> HGETALL student
1) "rollno"
2) "1"
3) "name"
4) "ABC"
5) "class"
6) "5"
127.0.0.1:6379> hset student age 12
(integer) 1
127.0.0.1:6379> HGETALL student
1) "rollno"
2) "1"
3) "name"
4) "ABC"
5) "class"
6) "5"
7) "age"
8) "12"
127.0.0.1:6379> HSET student class 6
(integer) 0
127.0.0.1:6379> HGETALL student
1) "rollno"
2) "1"
3) "name"
4) "ABC"
5) "class"
6) "6"
7) "age"
8) "12"
127.0.0.1:6379>
127.0.0.1:6379> type student
hash
127.0.0.1:6379> HLEN student
(integer) 4


2. How get specific field value in Hash datatype key and How to delete specific field from key.

HMGET <key> <field1> <field2>
HDEL <key> <field1>

127.0.0.1:6379> hmget student name class
1) "ABC"
2) "6"
127.0.0.1:6379> HDEL student age
(integer) 1
127.0.0.1:6379>
127.0.0.1:6379> HGETALL student
1) "rollno"
2) "1"
3) "name"
4) "ABC"
5) "class"
6) "6"
127.0.0.1:6379>

3. How to check if field exists in Hash key and How to check all field name in key.
HEXISTS <key> <field1> 
HKEYS <key>
HVALS <key>

pawan@LAPTOP-SG31RIME:/mnt/d/PAWAN$ redis-cli
127.0.0.1:6379>
127.0.0.1:6379>
127.0.0.1:6379> HGETALL student
1) "rollno"
2) "1"
3) "name"
4) "ABC"
5) "class"
6) "6"
127.0.0.1:6379> HEXISTS student class     //int1 define its exist
(integer) 1
127.0.0.1:6379> HEXISTS student newclass  //int0 define its not exist
(integer) 0
127.0.0.1:6379>
127.0.0.1:6379> HKEYS student
1) "rollno"
2) "name"
3) "class"
127.0.0.1:6379>
127.0.0.1:6379>
127.0.0.1:6379> HVALS student
1) "1"
2) "ABC"
3) "6"


4. Increase the value in hashkey
HINCRBY <key> <field> <value>

127.0.0.1:6379> HVALS student
1) "1"
2) "ABC"
3) "6"
127.0.0.1:6379> HINCRBY student class 1
(integer) 7
127.0.0.1:6379> HVALS student
1) "1"
2) "ABC"
3) "7"
127.0.0.1:6379>