Hash(哈希)
Redis hash 是一個string類型的field和value的映射表,hash特別適合用於存儲對象。
Redis 中每個 hash 可以存儲 232 - 1 鍵值對(40多億)。
使用場景 : 用戶信息
hset : 新建一個哈希表,設置成功返回1,如果已存在覆蓋舊值,返回0(值可以為''")
127.0.0.1:6379> hset yhq name yhq (integer) 1 127.0.0.1:6379> hset yhq name qhh (integer) 0
hmset: 新建一個哈希表,設置多個k-v,如果已存在會覆蓋,成功返回ok(值可以為''")
127.0.0.1:6379> hmsetqhh name yhq age 24 sex 0
OK
hsetnx : 當哈希表不存在時創建並設置且成功返回1,如果已存在無效,返回0
127.0.0.1:6379> hsetnx yhqqhh name qhh (integer) 1 127.0.0.1:6379> hsetnx yhqqhh name yhq (integer) 0
hstrlen : 獲取指定字段值的長度
127.0.0.1:6379> hmset myhash f1 HelloWorld f2 99 f3 -256 OK 127.0.0.1:6379> hstrlen myhash f1 (integer) 10 127.0.0.1:6379> hstrlen myhash f2 (integer) 2 127.0.0.1:6379> hstrlen myhash f3 (integer) 4
hget : 獲取哈希表字段的值,不存在返回nil
127.0.0.1:6379> hget yhq name "qhh" 127.0.0.1:6379> hget qhh name "yhq" 127.0.0.1:6379> hget qhh age "24" 127.0.0.1:6379> hget qhh sex "0" 127.0.0.1:6379> hget yhq id (nil)
hgetall : 獲取哈希表所有k-v,不存在返回空列表
127.0.0.1:6379> hgetall qhh 1) "name" 2) "yhq" 3) "age" 4) "24" 5) "sex" 6) "0" 127.0.0.1:6379> hgetall q (empty list or set)
hmget : 獲取一個或多個給定的值,不存在返回nil
127.0.0.1:6379> hmget qhh name age a
1) "yhq"
2) "24"
3) (nil)
hdel : 刪除一個或者多個哈希表字段,不存在忽略,返回刪除字段的個數
127.0.0.1:6379> hgetall qhh 1) "name" 2) "1" 3) "age" 4) "2" 127.0.0.1:6379> hdel qhh age a (integer) 1 127.0.0.1:6379> hgetall qhh 1) "name" 2) "1"
hexists : 查詢哈希表字段是否存在,存在返回1,不存在返回0
127.0.0.1:6379> hgetall must 1) "name" 2) "" 3) "age" 4) "1" 127.0.0.1:6379> hexists must name (integer) 1 127.0.0.1:6379> hexists must na (integer) 0
hkeys : 返回哈希表所有的k,key不存在返回空列表
127.0.0.1:6379> hkeys must 1) "name" 2) "age" 127.0.0.1:6379> hkeys must1 (empty list or set)
hvals : 返回哈希表所有k值,key不存在返回空列表
127.0.0.1:6379> hvals must 1) "" 2) "1" 127.0.0.1:6379> hvals must1 (empty list or set)
hlen : 返回哈希表字段數量,key不存在返回0
127.0.0.1:6379> hlen must (integer) 2
hincrby : 對哈希表字段進行數值增刪修改,字段串返回錯誤,如果不存在則執行創建操作
127.0.0.1:6379> hincrby yhq name 100 (integer) 100 127.0.0.1:6379> hgetall yhq 1) "name" 2) "100" 127.0.0.1:6379> hset yhq sex n (integer) 1 127.0.0.1:6379> hincrby yhq sex 100 (error) ERR hash value is not an integer 127.0.0.1:6379> hincrby yhq name -100 (integer) 0 127.0.0.1:6379> hgetall yhq 1) "name" 2) "0" 3) "sex" 4) "n"
hincrbyfloat : 對哈希表字段進行數值增刪浮點值修改,字段串返回錯誤,如果不存在則執行創建操作
127.0.0.1:6379> hincrbyfloat yhq size 1.1 "1.1" 127.0.0.1:6379> hincrbyfloat yhq name yhq (error) ERR value is not a valid float 127.0.0.1:6379> hincrbyfloat yhq size -11.11 "-10.01" 127.0.0.1:6379> hgetall yhq 1) "size" 2) "-10.01"