hash(哈希)
hset key field value
hget key field
hgetall info
hmget key field1 field2 …
hincrby key field number
专门用于结构化的数据信息。对应的就是map/结构体
结构:
键key:{ 域field: 值value, 域field: 值value, 域field: 值value, }
(1)设置指定键的属性/域
设置指定键的单个属性
hset key field value
设置键 user_1
的属性name
为xiaoming
127.0.0.1:6379> hset user_1 name xiaoming # user_1没有会自动创建 (integer) 1 127.0.0.1:6379> hset user_1 name xiaohei # user_1中重复的属性会被修改 (integer) 0 127.0.0.1:6379> hset user_1 age 16 # user_1中不存在的属性会被新增 (integer) 1 127.0.0.1:6379> hset user:1 name xiaohui # user:1会在redis界面操作中以:作为目录分隔符 (integer) 1 127.0.0.1:6379> hset user:1 age 15 (integer) 1 127.0.0.1:6379> hset user:2 name xiaohong age 16 # 一次性添加或修改多个属性
(2)获取指定键的域/属性的值
获取指定键所有的域/属性
hkeys key
获取键user的所有域/属性
127.0.0.1:6379> hkeys user:2 1) "name" 2) "age" 127.0.0.1:6379> hkeys user:3 1) "name" 2) "age" 3) "sex"
获取指定键的单个域/属性的值
hget key field
获取键user:3
属性name
的值
127.0.0.1:6379> hget user:3 name "xiaohong"
获取指定键的多个域/属性的值
hmget key field1 field2 ...
获取键user:2
属性name
、age
的值
127.0.0.1:6379> hmget user:2 name age 1) "xiaohong" 2) "16"
获取指定键的所有值
hvals key
获取指定键的所有域值对
127.0.0.1:6379> hvals user:3 1) "xiaohong" 2) "17" 3) "1"
(3)获取hash的所有域值对
127.0.0.1:6379> hset user:1 name xiaoming age 16 sex 1 (integer) 3 127.0.0.1:6379> hgetall user:1 1) "name" 2) "xiaoming" 3) "age" 4) "16" 5) "sex" 6) "1"
(4)删除指定键的域/属性
hdel key field1 field2 ...
删除键user:3
的属性sex/age/name
,当键中的hash数据没有任何属性,则当前键会被redis删除
hdel user:3 sex age name
(5)判断指定属性/域是否存在于当前键对应的hash中
hexists key field
判断user:2中是否存在age属性
127.0.0.1:6379> hexists user:3 age (integer) 0 127.0.0.1:6379> hexists user:2 age (integer) 1 127.0.0.1:6379>
(6)属性值自增自减
hincrby key field number
给user:2的age属性在原值基础上+/-10,然后在age现有值的基础上-2
# 按指定数值自增 127.0.0.1:6379> hincrby user:2 age 10 (integer) 77 127.0.0.1:6379> hincrby user:2 age 10 (integer) 87 # 按指定数值自减 127.0.0.1:6379> hincrby user:2 age -10 (integer) 77 127.0.0.1:6379> hincrby user:2 age -10
127.0.0.1:6379> hset info name rain (integer) 1 127.0.0.1:6379> hget info name "rain" 127.0.0.1:6379> hset info name lz age 21 (integer) 0 127.0.0.1:6379> hget info name "lz" 127.0.0.1:6379> hset info name root age 25 (integer) 0 127.0.0.1:6379> hget info name "root" 127.0.0.1:6379> hgetall info 1) "name" 2) "root" 3) "age" 4) "25" 127.0.0.1:6379> hmget info name age 1) "root" 2) "25" 127.0.0.1:6379> hdel info age (integer) 1 127.0.0.1:6379> hgetall info 1) "name" 2) "root" 127.0.0.1:6379> hexists info name (integer) 1 127.0.0.1:6379> hexists info age (integer) 0 127.0.0.1:6379> hset info age 21 (integer) 1 127.0.0.1:6379> hgetall info 1) "name" 2) "root" 3) "age" 4) "21" 127.0.0.1:6379> hincrby info age 5 (integer) 26 127.0.0.1:6379> hget info age "26" 127.0.0.1:6379> 127.0.0.1:6379> hget info age "26" 127.0.0.1:6379> hkeys info 1) "name" 2) "age" 127.0.0.1:6379> hvals info 1) "root" 2) "26" 127.0.0.1:6379>