散列命令
散列类型的键值其实也是一种字典解耦,其存储了字段和字段值的映射,但字段值只能是字符串,不支持其他数据类型,所以说散列类型不能嵌套其他的数据类型。一个散列类型的键可以包含最多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:6379> hmset post:1 title "the first post" author "JoJo" time 2016/08/25 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:6379> hmget post:1 time author 1) "2016/08/25" 2) "JoJo"
hgetall key #取得key所对应的所有键值列表,这里给出个例子
redis 127.0.0.1:6379> hgetall post:1 1) "title" 2) "the first post" 3) "author" 4) "JoJo" 5) "time" 6) "2016/08/25" 7) "content" 8) "this is my first post"
2、判断是否存在
hexists key field
如果存在返回1,否则返回0(如果键不存在也返回0)。
3、当字段不存在时赋值
hsetnx key field value
这个和hset的区别就是如果字段存在,这个命令将不执行任何操作,但是这里有一个区别就是Redis提供的这些命令都是原子操作,不会产生数据不一致问题。
例:
redis 127.0.0.1:6379> hexists post:1 time (integer) 1 //判断是存在time字段的 redis 127.0.0.1:6379> hsetnx post:1 time 2016/08/26 (integer) 0 //不存在的话,设置time,存在的话返回0,值不变,原始值 redis 127.0.0.1:6379> hget post:1 time "2016/08/25" redis 127.0.0.1:6379> hsetnx post:1 age 23 (integer) 1 //不存在age字段,返回1,并设置age字段 redis 127.0.0.1:6379> hget post:1 age "23"
4、增加数字
hincrby key field number
这里就和incry命令类似了。
例:
redis 127.0.0.1:6379> hincrby post:1 age 2 (integer) 25
5、删除字段
hdel key field [field ...]
删除字段,一个或多个,返回值是被删除字段的个数。
6、其他命令
hkeys key #获取字段名
hvals key #获取字段名
示例如下:
redis 127.0.0.1:6379> hkeys post:1 1) "title" 2) "author" 3) "time" 4) "content" 5) "age" redis 127.0.0.1:6379> hvals post:1 1) "the first post" 2) "JoJo" 3) "2016/08/25" 4) "this is my first post" 5) "25"
最后还有一个就是获取字段数量的命令:
hlen key
返回字段的数量
redis 127.0.0.1:6379> hlen post:1 (integer) 5