chenkehao 发表于 2016-12-19 08:34:09

Redis学习笔记(四)——Redis常用命令入门——散列类型

三、散列命令

散列类型的键值其实也是一种字典解耦,其存储了字段和字段值的映射,但自断值只能是字符串,不支持其他数据类型,所以说散列类型不能嵌套其他的数据类型。一个散列类型的键可以包含最多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>hmset post:1 title "the first post" author me time 2014-03-04 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  #这个同上,批量存值
hmget key field                      #批量取值,取得列表
hgetall key                  #取得key所对应的所有键值列表,这里给出个例子



redis>hgetall post:1
1) "title"
2) "the first post"
3) "author"
4) "me"
5) "time"
6) "2014-03-04"
7) "content"
8) "This is my first post."




本文原创与本人个人博客,更多内容请关注http://irfen.me 
2、判断是否存在
hexists key field
如果存在返回1,否则返回0(如果键不存在也返回0)。
3、当字段不存在时赋值
hsetnx key field value
这个和hset的区别就是如果字段存在,这个命令将不执行任何操作,但是这里有一个区别就是Redis提供的这些命令都是原子操作,不会产生数据不一致问题。
4、增加数字
hincrby key field number
这里就和incry命令类似了。
5、删除字段
hdel key field
删除字段,一个或多个,返回值是被删除字段的个数。
6、其他命令
hkeys key    #获取字段名
hvals key    #获取字段名
示例如下:



redis>hkeys post:1
1) "title"
2) "author"
3) "time"
4) "content"
redis>hvals post:1
1) "the first post"
2) "me"
3) "2014-03-04"
4) "This is my first post."




最后还有一个就是获取字段数量的命令:
hlen key
返回字段的数量
 
本文原创与本人个人博客,更多内容请关注http://irfen.me
页: [1]
查看完整版本: Redis学习笔记(四)——Redis常用命令入门——散列类型