🌙 Hash类型
Hash 类型,也叫散列,其value是一个无序字典,类似于HashMap结构。
String结构是将对象序列化为JSON字符串存储,当需要修改对象某个字段时很不方便:
KEY | VALUE |
---|---|
demo:user:1 | {"id": 1, "name": "JEEK", "age": 18} |
demo:product:1 | {"id": 1, "name": "redis", "price": 199} |
Hash结构可以讲对象中的每个字段独立存储,可以针对单个字段做CRUD:
KEY | FIELD | VALUE |
---|---|---|
demo:user:1 | id | 1 |
name | JEEK | |
age | 18 | |
demo:product:1 | id | 1 |
name | redis | |
price | 199 |
Hash常见命令有:
HSET key field value
: 添加或者修改hash类型key的field的值HGET key field
: 获取一个hash类型key的field的值HMSET
: 批量添加多个hash类型key的field的值HMGET
: 批量获取多个hash类型的key中的所有的field和valueHKEYS
: 获取一个hash类型的key中的所有的fieldHVALS
: 获取一个hash类型key的所有的valueHINCRBY
: 让一个hash类型的key的字段值自增并制定步长HSETNX
: 添加一个hash类型的key的field值,前提是这个field不存在,否则不执行
127.0.0.1:6379> HMSET user:jeek name jeek age 18
"ok"
127.0.0.1:6379> hget user:jeek name
"jeek"
127.0.0.1:6379> HGETALL user:jeek
1) "name"
2) "jeek"
3) "age"
4) "18"
127.0.0.1:6379> help @HASH
HDEL key field [field ...]
summary: Delete one or more hash fields
since: 2.0.0
HEXISTS key field
summary: Determine if a hash field exists
since: 2.0.0
HGET key field
summary: Get the value of a hash field
since: 2.0.0
HGETALL key
summary: Get all the fields and values in a hash
since: 2.0.0
HINCRBY key field increment
summary: Increment the integer value of a hash field by the given number
since: 2.0.0
HINCRBYFLOAT key field increment
summary: Increment the float value of a hash field by the given amount
since: 2.6.0
HKEYS key
summary: Get all the fields in a hash
since: 2.0.0
HLEN key
summary: Get the number of fields in a hash
since: 2.0.0
HMGET key field [field ...]
summary: Get the values of all the given hash fields
since: 2.0.0
HMSET key field value [field value ...]
summary: Set multiple hash fields to multiple values
since: 2.0.0
HSCAN key cursor [MATCH pattern] [COUNT count]
summary: Incrementally iterate hash fields and associated values
since: 2.8.0
HSET key field value
summary: Set the string value of a hash field
since: 2.0.0
HSETNX key field value
summary: Set the value of a hash field, only if the field does not exist
since: 2.0.0
HSTRLEN key field
summary: Get the length of the value of a hash field
since: 3.2.0
HVALS key
summary: Get all the values in a hash
since: 2.0.0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73