1. 程式人生 > 資料庫 >Redis五種資料型別

Redis五種資料型別

Redis支援五種資料型別:string(字串),hash(雜湊),list(列表),set(集合)及zset(sorted set:有序集合)

1.String

string 是 redis 最基本的型別,你可以理解成與Map中的一模一樣的資料型別,一個 key 對應一個value。string 型別是二進位制安全的。意思是 redis 的 string 可以包含任何資料。比如jpg圖片或者序列化的物件。string 型別是 Redis 最基本的資料型別,string 型別的值最大能儲存 512MB。

1. 賦值
SET key value
127.0.0.1:6379> set test 123
OK
2. 取值
賦值與取值:
GET key
127.0.0.1:6379> get test
"123“
當鍵不存在時返回空結果。
3. 取值時同時對key進行賦值操作。
GETSET key value
4. 刪除
Del key
127.0.0.1:6379> del test
(integer) 1
5. 數值加一
INCR key
當儲存的字串是整數時,Redis提供了一個實用的命令INCR,其作用是讓當前鍵值遞增,並返回遞增後的值。127.0.0.1:6379> incr num
(integer) 1
127.0.0.1:6379> incr num
(integer) 2
127.0.0.1:6379> incr num
(integer) 3
6. 增加指定的整數
INCRBY key increment
示例:
127.0.0.1:6379> incrby num 2
(integer) 5
127.0.0.1:6379> incrby num 2
(integer) 7
127.0.0.1:6379> incrby num 2
(integer) 9
7. 數值減一
DECR key

2.Hash

hash叫雜湊型別,它提供了欄位和欄位值的對映。欄位值只能是字串型別,不支援雜湊型別、集合型別等其它型別。相當於一個key對應一個map。

1. 建立hash並新增值
HSET [key] [field] [value]
例如:127.0.0.1:6379> hset hash1 field1 abc
(integer) 1
2. 從hash中取值
HGET [key] [field]
例如:127.0.0.1:6379> hget hash1 field1
"abc"
3. 從hash中刪除
HDEL [key] [field]
例如:127.0.0.1:6379> hdel hash1 field1
(integer) 1
4. 判斷filed是否存在
HEXISTS [key] [field]
如果存在返回“1”,如果不存在返回“0”
127.0.0.1:6379> hexists hash1 field1
(integer) 0
5. 取hash中的內容
從hash中取field的列表:
hkeys [key]
從hash中取value的列表
hvals [key]
從hash中取field和value的列表
hgetall [key]

3.List

Redis列表是簡單的字串列表,按照插入順序排序。你可以新增一個元素到列表的頭部(左邊)或者尾部(右邊)一個列表最多可以包含 2 ^32 - 1個元素 (4294967295, 每個列表超過40億個元素)。

1. 新增元素
左邊新增:lpush [key] [element...]
右邊新增:rpush [key] [element...]
2. 取元素
左邊取元素:lpop [key]
右邊去元素:rpop [key]
3. 檢視列表中元素
lrange [key] [start] [end]
需要設定列表中起始的元素的索引和結束元素的索引,如果結束元素的索引是-1則代表取到列表結尾。
4. 檢視列表的長度
llen [key]

4.Set

Redis 的 Set 是 String 型別的無序集合。集合成員是唯一的,這就意味著集合中不能出現重複的資料。Redis 中集合是通過雜湊表實現的,所以新增,刪除,查詢的複雜度都是 O(1)。集合中最大的成員數為 2 ^32 - 1 (4294967295, 每個集合可儲存40多億個成員)。

新增元素
1. sadd [key] [member...]
2. 刪除元素
刪除指定元素:srem [key] [member]
127.0.0.1:6379> srem set1 a
(integer) 1
從集合中取移除隨機元素:spop [key]
127.0.0.1:6379> spop set1
"e"
3. 取集合元素個數
scard [key]
127.0.0.1:6379> scard set1
(integer) 5
4. 取集合元素成員
smembers [key]
127.0.0.1:6379> smembers set1
1) "b"
2) "g"
3) "d"
4) "c"
5) "f"
6) "e"

5.SortedSet

Redis 有序集合和集合一樣也是string型別元素的集合,且不允許重複的成員。不同的是每個元素都會關聯一個double型別的分數。redis正是通過分數來為集合中的成員進行從小到大的排序。有序集合的成員是唯一的,但分數(score)卻可以重複。集合是通過雜湊表實現的,所以新增,刪除,查詢的複雜度都是O(1)。集合中最大的成員數為 2^32 - 1(4294967295, 每個集合可儲存40多億個成員)。由於SortedSet所有的命令都是以Z開頭所以SortedSet也叫做zset。

1. 新增元素
zadd [key] [score] [member]
2. 刪除元素
zrem [key] [member]
3. 元素數量
zcard [key]
4. 獲取集合成員
zrange [key] [start] [stop] [withscroes]