哈希命令——Redis学习笔记

Redis的哈希值是字符串字段和字符串值之间的映射

1:HSET key field value
设置哈希字段的字符串值

1
2
3
4
5
127.0.0.1:6379> hset table_user id 001
(integer) 1
127.0.0.1:6379> hgetall table_user
1) "id"
2) "001"

2:HMSET key field1 value1 [field2 value2 ]
设置哈希字段的多个值

1
2
3
4
5
6
7
8
9
127.0.0.1:6379> hmset table_user id 001 name 'shiwuhao' age 23
OK
127.0.0.1:6379> hgetall table_user
1) "id"
2) "001"
3) "name"
4) "shiwuhao"
5) "age"
6) "23"

3:HGET key field
获取存储在指定的键散列字段的值

1
2
127.0.0.1:6379> hget table_user id
"001"

4:HGETALL key
让所有的字段和值在指定的键存储在一个哈希

1
2
3
4
5
6
7
127.0.0.1:6379> hgetall table_user
1) "id"
2) "001"
3) "name"
4) "shiwuhao"
5) "age"
6) "23"

5:HDEL key field [field2]
删除一个或多个哈希字段

1
2
3
4
5
127.0.0.1:6379> hdel table_user id age
(integer) 2
127.0.0.1:6379> hgetall table_user
1) "name"
2) "shiwuhao"

6:HEXISTS key field
判断一个哈希字段是否存在

1
2
3
4
5
6
7
127.0.0.1:6379> hgetall table_user
1) "name"
2) "shiwuhao"
127.0.0.1:6379> hexists table_user name
(integer) 1
127.0.0.1:6379> hexists table_user id
(integer) 0

7:HINCRBY key field increment
由给定数量增加的哈希字段的整数值

1
2
3
4
5
6
7
8
9
10
11
127.0.0.1:6379> hset table_user age 23
(integer) 1
127.0.0.1:6379> hgetall table_user
1) "name"
2) "shiwuhao"
3) "age"
4) "23"
127.0.0.1:6379> hincrby table_user age 5
(integer) 28
127.0.0.1:6379> hincrby table_user age 5
(integer) 33

8:HINCRBYFLOAT key field increment
由给定的递增量哈希字段的浮点值

1
2
3
4
5
6
7
8
9
10
11
12
13
127.0.0.1:6379> hset table_user price 500.20
(integer) 1
127.0.0.1:6379> hgetall table_user
1) "name"
2) "shiwuhao"
3) "age"
4) "33"
5) "price"
6) "500.20"
127.0.0.1:6379> hincrbyfloat table_user price .30
"500.5"
127.0.0.1:6379> hincrbyfloat table_user price .40
"500.89999999999999999"

9:HKEYS key
获取某个哈希的所有字段

1
2
3
4
127.0.0.1:6379> hkeys table_user
1) "name"
2) "age"
3) "price"

10:HLEN key
获取哈希字段数

1
2
127.0.0.1:6379> hlen table_user
(integer) 3

11:HMGET key field1 [field2]
获得所有给定的哈希字段的值

1
2
3
4
127.0.0.1:6379> hmget table_user name age price
1) "shiwuhao"
2) "33"
3) "500.89999999999999999"

12:HSETNX key field value
设置哈希字段的值,仅当该字段不存在的时候

1
2
3
4
127.0.0.1:6379> hsetnx table_user name 123
(integer) 0
127.0.0.1:6379> hsetnx table_user id 001
(integer) 1

13:HVALS key
获取在哈希中的所有值

1
2
3
4
5
127.0.0.1:6379> hvals table_user
1) "shiwuhao"
2) "33"
3) "500.89999999999999999"
4) "001"