散列命令
散列类型的键值其实也是一种字典解耦,其存储了字段和字段值的映射,但字段值只能是字符串,不支持其他数据类型,所以说散列类型不能嵌套其他的数据类型。一个散列类型的键可以包含最多2的32次方-1个字段。
另外提前说一声,除了散列类型,其他的数据类型同样不支持数据类型嵌套。
1、基本命令
例如现在要存储ID为1的文章,分别有title、author、time、content
则键为post:1,字段分别为title、author、time、content,值分别为“the first post”、“me”、“2014-03-04”、“This is my first post.”,存储如下
redis 127.0.0.1:> hmset post: title "the first post" author "JoJo" time // content "this is my first post"
OK
这里使用的是hmset命令,具体散列的基本赋值命令如下:
hset key field value #例如hset post:2 title “second post”
hget key field #例如hget post:2 title,获取id为2的post的title值
hmset key field value [field value ...] #这个同上,批量存值
hmget key field [field ...] #批量取值,取得列表
例:
redis 127.0.0.1:> hmget post: time author
) "2016/08/25"
) "JoJo"
hgetall key #取得key所对应的所有键值列表,这里给出个例子
redis 127.0.0.1:> hgetall post:
) "title"
) "the first post"
) "author"
) "JoJo"
) "time"
) "2016/08/25"
) "content"
) "this is my first post"
2、判断是否存在
hexists key field
如果存在返回1,否则返回0(如果键不存在也返回0)。
3、当字段不存在时赋值
hsetnx key field value
这个和hset的区别就是如果字段存在,这个命令将不执行任何操作,但是这里有一个区别就是Redis提供的这些命令都是原子操作,不会产生数据不一致问题。
例:
redis 127.0.0.1:> hexists post: time
(integer) 1 //判断是存在time字段的
redis 127.0.0.1:> hsetnx post: time //
(integer) 0 //不存在的话,设置time,存在的话返回0,值不变,原始值
redis 127.0.0.1:> hget post: time
"2016/08/25"
redis 127.0.0.1:> hsetnx post: age
(integer) 1 //不存在age字段,返回1,并设置age字段
redis 127.0.0.1:> hget post: age
""
4、增加数字
hincrby key field number
这里就和incry命令类似了。
例:
redis 127.0.0.1:> hincrby post: age
(integer)
5、删除字段
hdel key field [field ...]
删除字段,一个或多个,返回值是被删除字段的个数。
6、其他命令
hkeys key #获取字段名
hvals key #获取字段名
示例如下:
redis 127.0.0.1:> hkeys post:
) "title"
) "author"
) "time"
) "content"
) "age"
redis 127.0.0.1:> hvals post:
) "the first post"
) "JoJo"
) "2016/08/25"
) "this is my first post"
) ""
最后还有一个就是获取字段数量的命令:
hlen key
返回字段的数量
redis 127.0.0.1:> hlen post:
(integer)