Redis Hash类型是一个string类型的field和value的映射表。其添加、删除操作的时间复杂度都是O(1)类型。特别适合于存储对象。相比较将对象的每个字段都存储成单个的string类型,将一个对象存储为hash类型会占用更少的内存,并且存取整个对象也会很方便。
1.hset ##设置field为指定值,如果hash key不存在则创建
redis 127.0.0.1:6379> hset user:001 username hzsunpeng
(integer) 1
2.hget ##获取指定hash的filed的值
redis 127.0.0.1:6379> hset user:001 username hzsunpeng
(integer) 1
redis 127.0.0.1:6379> hget user:001 username
"hzsunpeng"
3.hsetnx ##设置hash的field为指定值,如果hash key不存在则创建,如果存在则返回0,设置失败
redis 127.0.0.1:6379> hsetnx user:001 username hzsunpeng_new
(integer) 0
由于user:001已经存在username,所有设置失败,返回0
4.hmset ##批量设置hash的field值,下面设置user:002这个hash的多个field
redis 127.0.0.1:6379> hmset user:002 username hzsunpeng password 12345 age 25 sex 1 phonenum 12345678
OK
redis 127.0.0.1:6379> hget user:002 username
"hzsunpeng"
redis 127.0.0.1:6379> hget user:002 password
"12345"
redis 127.0.0.1:6379> hget user:002 age
"25"
redis 127.0.0.1:6379> hget user:002 sex
"1"
redis 127.0.0.1:6379> hget user:002 phonenum
"12345678"
hmget **批量获取hash的多个field
redis 127.0.0.1:6379> hmget user:002 username age sex phonenum
1) "hzsunpeng"
2) "25"
3) "1"
4) "12345678"
5.hincrby **为指定的hash表的field增加值,返回增加后的值
redis 127.0.0.1:6379> hincrby user:002 age 5
(integer) 30
redis 127.0.0.1:6379> hget user:002 age
"30"
6.hexists **hash中某个field是否存在
redis 127.0.0.1:6379> hexists user:002 username
(integer) 1
redis 127.0.0.1:6379> hexists user:002 age
(integer) 1
redis 127.0.0.1:6379> hexists user:002 password
(integer) 1
redis 127.0.0.1:6379> hexists user:002 sex
(integer) 1
redis 127.0.0.1:6379> hexists user:002 address
(integer) 0
7.hlen **统计指定hash的field的数量
redis 127.0.0.1:6379> hlen user:002
(integer) 5
8.hdel **删除指定hdel的field,删除成功返回1
redis 127.0.0.1:6379> hget user:002 age
"30"
redis 127.0.0.1:6379> hdel user:002 age
(integer) 1
redis 127.0.0.1:6379> hget user:002 age
(nil)
9.hkeys **指定hash的所有的field的名称,只返回field,没有值
redis 127.0.0.1:6379> hkeys user:002
1) "username"
2) "password"
3) "sex"
4) "phonenum"
10.hvals **返回指定hash的所有的field的value值,只返回值
redis 127.0.0.1:6379> hvals user:002
1) "hzsunpeng"
2) "12345"
3) "1"
4) "12345678"
11.hgetall **获取某个hash的所有field和其对应的值
redis 127.0.0.1:6379> hgetall user:002
1) "username"
2) "hzsunpeng"
3) "password"
4) "12345"
5) "sex"
6) "1"
7) "phonenum"
8) "12345678"
Redis的hashes类型对于存储对象来说很方便,也是五种基本数据类型中比较重要的