Map集合,以键值对key-map
存储的时候也是一个Map集合,本质和String类型没有太大区别,还是一个简单的key-value!
1、命令
Redis中Hash的命令都以‘S’开头!!
!
老样子,启动客户端进行测试
HSET
:hset key field [field value …]
HGET
:hget key field
HGETALL
:hgetall key
HKEYS
:hkeys key
HVALS
:hvals key
127.0.0.1:6379> flushdb # 清除当前数据库
OK
127.0.0.1:6379> hset myhash field1 hi # set 一个 key-value
(integer) 1
127.0.0.1:6379> hset myhash name oldfe age 9 # 也可以同时set 多个 key-value
(integer) 2
127.0.0.1:6379> hget myhash name # 获取一个字段值name
"oldfe"
127.0.0.1:6379> hget myhash age
"9"
127.0.0.1:6379> hgetall myhash #获取全部的字段和值,以key-value显示
1) "field1" # key
2) "hi" # value
3) "name" # key
4) "oldfe" # value
5) "age" # key
6) "9" # value
127.0.0.1:6379> hkeys myhash # 获取全部的字段 keys
1) "field1"
2) "name"
3) "age"
127.0.0.1:6379> hvals myhash #获取全部的字段值 values
1) "hi"
2) "oldfe"
3) "9"
HEXISTS
:hexists key field
HLEN
:hlenkey
127.0.0.1:6379> flushdb # 清除当前数据库
OK
127.0.0.1:6379> hset hash k1 v1 k2 v2 k3 v3 # 同时 set 多个字段和值
(integer) 3
127.0.0.1:6379> hkeys hash # 获取所有的key
1) "k1"
2) "k2"
3) "k3"
127.0.0.1:6379> hlen hash # 获取字段个数
(integer) 3
127.0.0.1:6379> hexists hash k2 # 判断字段是否存在,存在返回1
(integer) 1
127.0.0.1:6379> hexists hash k4 # 不存在返回0
(integer) 0
HINCRBY
:hincrby key field increment
HDEL
:del key field [ field …]
127.0.0.1:6379> hset myHash name old age 9 city china
(integer) 3
127.0.0.1:6379> hgetall myHash
1) "name"
2) "old"
3) "age"
4) "9"
5) "city"
6) "china"
127.0.0.1:6379> hdel myHash city name # 可以同时删除一个或多个字段
(integer) 2
127.0.0.1:6379> hgetall myHash
1) "age"
2) "9"
127.0.0.1:6379> hincrby myHash age 20 # 指定字段相加 20
(integer) 29
127.0.0.1:6379> hincrby myHash age -8 # 指定字段相加 -8
(integer) 21
127.0.0.1:6379> hget myHash age
"21"
HINCRBY
:hincrby key field increment
HDEL
:del key field [ field …]
HSETNX
:hsetnx key field value
127.0.0.1:6379> hset myHash name old age 9 city china
(integer) 3
127.0.0.1:6379> hgetall myHash
1) "name"
2) "old"
3) "age"
4) "9"
5) "city"
6) "china"
127.0.0.1:6379> hdel myHash city name # 可以同时删除一个或多个字段
(integer) 2
127.0.0.1:6379> hgetall myHash
1) "age"
2) "9"
127.0.0.1:6379> hincrby myHash age 20 # 指定字段相加 20
(integer) 29
127.0.0.1:6379> hincrby myHash age -8 # 指定字段相加 -8
(integer) 21
127.0.0.1:6379> hgetall myHash
1) "age"
2) "21"
127.0.0.1:6379> hsetnx myHash age strValue # 字段如果存在不能设置
(integer) 0
127.0.0.1:6379> hsetnx myHash name bigshuaige # 字段如果不存在可以设置
(integer) 1
127.0.0.1:6379> hgetall myHash
1) "age"
2) "21"
3) "name"
4) "bigshuaige"
2、总结!!!
Hash变更的数据,尤其是用户信息之类的,经常变动的信息!Hash更适合对象的存储!String更加适合字符串的存储!
图片来自redis中文网: