目錄
一、Hash 哈希
1.2 常用命令
1.2.1 HSET
1.2.2 HGET
1.2.3 HEXISTS
1.2.4 HDEL
1.2.5 HKEYS
1.2.6 HVALS
1.2.7 HGETALL
1.2.8 HMGET
1.2.9 HLEN
1.2.10 HSETNX
1.2.11 HINCRBY
1.2.12 HINCRBYFLOAT
1.3 內部編碼
一、Hash 哈希
1.2 常用命令
1.2.1 HSET
HSET key field value [field value ...]
redis> HSET myhash field1 "Hello"
(integer) 1
redis> HGET myhash field1
"Hello"
1.2.2 HGET
HGET key field
1.2.3 HEXISTS
HEXISTS key field
redis> HSET myhash field1 "foo"
(integer) 1
redis> HEXISTS myhash field1
(integer) 1
redis> HEXISTS myhash field2
(integer) 0
1.2.4 HDEL
HDEL key field [field ...]
redis> HSET myhash field1 "foo"
(integer) 1
redis> HDEL myhash field1
(integer) 1
redis> HDEL myhash field2
(integer) 0
1.2.5 HKEYS
HKEYS key
redis> HSET myhash field1 "Hello"
(integer) 1
redis> HSET myhash field2 "World"
(integer) 1
redis> HKEYS myhash
1) "field1"
2) "field2
1.2.6 HVALS
HVALS key
redis> HSET myhash field1 "Hello"
(integer) 1
redis> HSET myhash field2 "World"
(integer) 1
redis> HVALS myhash
1) "Hello"
2) "World"
1.2.7 HGETALL
HGETALL key
redis> HSET myhash field1 "Hello"
(integer) 1
redis> HSET myhash field2 "World"
(integer) 1
redis> HGETALL myhash
1) "field1"
2) "Hello"
3) "field2"
4) "World"
1.2.8 HMGET
HMGET key field [field ...]
redis> HSET myhash field1 "Hello"
(integer) 1
redis> HSET myhash field2 "World"
(integer) 1
redis> HMGET myhash field1 field2 nofield
1) "Hello"
2) "World"
3) (nil)
1.2.9 HLEN
HLEN key
redis> HSET myhash field1 "Hello"
(integer) 1
redis> HSET myhash field2 "World"
(integer) 1
redis> HLEN myhash
(integer) 2
1.2.10 HSETNX
HSETNX key field value
redis> HSETNX myhash field "Hello"
(integer) 1
redis> HSETNX myhash field "World"
(integer) 0
redis> HGET myhash field
"Hello"
1.2.11 HINCRBY
HINCRBY key field increment
redis> HSET myhash field 5
(integer) 1
redis> HINCRBY myhash field 1
(integer) 6
redis> HINCRBY myhash field -1
(integer) 5
redis> HINCRBY myhash field -10
(integer) -5
1.2.12 HINCRBYFLOAT
1.3 內部編碼
哈希的內部編碼有兩種:
ziplist(壓縮列表) :當哈希類型元素個數小于?hash-max-ziplist-entries 配置(默認 512 個)、 同時所有值都小于?hash-max-ziplist-value 配置(默認 64 字節)時,Redis 會使用?ziplist 作為哈希的內部實現,ziplist 使用更加緊湊的結構實現多個元素的連續存儲,所以在節省內存方面比hashtable 更加優秀。
hashtable(哈希表) :當哈希類型無法滿足?ziplist 的條件時,Redis 會使用?hashtable 作為哈希的內部實現,因為此時 ziplist 的讀寫效率會下降,而?hashtable 的讀寫時間復雜度為 O(1)。
下?的示例演示了哈希類型的內部編碼,以及響應的變化。
當field的數量比較少且沒有大的value時,內部編碼為ziplist:
127.0.0.1:6379> hmset hashkey f1 v1 f2 v2
OK
127.0.0.1:6379> object encoding hashkey
"ziplist"
當有value大于64個字節時,內部編碼為hashtable:
127.0.0.1:6379> hset hashkey f3 "one string is bigger than 64 bytes ... 省略..."
OK
127.0.0.1:6379> object encoding hashkey
"hashtable"