概述
我们知道Redis是采用字典结构以键值对的形式存储数据,而散列类型的键值也是一种字典结构,其存储了字段和字段值的映射,但是字段值必须是字符串,不支持其它数据类型,换句话说,散列类型不能嵌套其他数据类型。同时除了散列类型,Redis的其它数据类型同样不支持数据类型嵌套。集合类型的每个元素都只能是字符串,不能是另一个集合或散列表等。
散列类型适合存储对象:使用对象类别和ID构成键名,使用字段表示属性,字段值存储属性值。
键 字段 字段值
color 白色
car:2 name 奥迪
price 90万
基本命令
1.赋值与取值
HSET key field value
HGET key field
HMSET key field value [field value ...]
HMGET key field [field ...]
HGETALL key
下面简单的赋值
127.0.0.1:6379> hset car price 500
(integer) 1
127.0.0.1:6379> hset car name bmw
(integer) 0
127.0.0.1:6379> hget car name
"bmw"
hset这个命令这里是不区分插入和更新操作.当我们执行的是插入操作的时候hset命令会返回1,当执行的是更新操作的时候hset会返回0。如果键不存在是,hset命令会自动建立它。
这里要区分hset和set,hset前面有个h代表的是hash也就是散列,set是只针对字符串来操作,这里我们不能互相使用其它的命令。
我也可以使用HMSET命令一次性写多个操作
127.0.0.1:6379> hmset car:1 price 4000 name ferry color 红
OK
127.0.0.1:6379> hmget car:1 price name color
1) "4000"
2) "ferry"
3) "\xe7\xba\xa2"
127.0.0.1:6379> hgetall car:1
1) "price"
2) "4000"
3) "name"
4) "ferry"
5) "color"
6) "\xe7\xba\xa2"
2.判断字段是否存在
hexists key field
存在返回1,不存在返回0。
127.0.0.1:6379> hexists car kind
(integer) 0
127.0.0.1:6379> hset car kind yueye
(integer) 1
127.0.0.1:6379> hexists car kind
(integer) 1
3.当字段不存在时赋值
hsetnx key field value
当字段存在的时候不会做事如果不存在会给字段赋值。
127.0.0.1:6379> hexists car width
(integer) 0
127.0.0.1:6379> hsetnx car width 50
(integer) 1
127.0.0.1:6379> hexists car width
(integer) 1
4.增加数字
hincrby key field increment
在字符串中incr是字符串类型的自增这里是散列类型的增加。
127.0.0.1:6379> hincrby book price 100
(integer) 100
127.0.0.1:6379> hincrby book price 100
(integer) 200
5.删除字段
hdel key field [field ...]
返回的是所删除的条数
127.0.0.1:6379> hdel book price
(integer) 1
127.0.0.1:6379> hdel book price
(integer) 0
实践操作
我们可以利用散列存储什么值?
我觉得存储一个东西的所有属性是比较符合的,在散列中存储某种东西的所有属性数据更加直观,也更容易维护。
命令扩展
1.只获取字段名或字段值
hkeys key
hvals key
可以看看下面的例子:
127.0.0.1:6379> hkeys car
1) "name"
2) "model"
3) "price"
4) "kind"
5) "width"
127.0.0.1:6379> hvals car
1) "bmw"
2) "c200"
3) "500"
4) "yueye"
5) "50"
2.获取键中字段的数量:
HLEN key
127.0.0.1:6379> hlen car
(integer) 5