当前位置:网站首页>Redis getting started complete tutorial: hash description
Redis getting started complete tutorial: hash description
2022-07-04 23:00:00 【Gu Ge academic】
Almost all programming languages provide hashes (hash) type , Their name may be ha
Greek 、 Dictionaries 、 Associative array . stay Redis in , Hash type means that the key itself is a key value pair
structure , Form like value={ {field1,value1},...{fieldN,valueN}},Redis Key value pairs and
The relationship between hash type and hash type can be shown in Figure 2-14 To express .
The mapping relationship in a hash type is called field-value, Notice the value Refer to field Corresponding
Value , The key of the value is not , Please note that value Role in different contexts .
2.3.1 command
(1) Set the value
hset key field value
The following is user:1 Add a pair of field-value:
127.0.0.1:6379> hset user:1 name tom
(integer) 1
If the setting is successful, it will return 1, On the contrary, it will return 0. Besides Redis Provides hsetnx command , it
Our relationship is like set and setnx command , It's just that the scope changes from bond to field.
(2) Get value
hget key field
for example , The following operation gets user:1 Of name Domain ( attribute ) Corresponding value :
127.0.0.1:6379> hget user:1 name
"tom"
If the key or field non-existent , Returns the nil:
127.0.0.1:6379> hget user:2 name
(nil)
127.0.0.1:6379> hget user:1 age
(nil)
(3) Delete field
hdel key field [field ...]
hdel Will delete one or more field, The result is successfully deleted field The number of , for example :
127.0.0.1:6379> hdel user:1 name
(integer) 1
127.0.0.1:6379> hdel user:1 age
(integer) 0
(4) Calculation field Number
hlen key
for example user:1 Yes 3 individual field:
127.0.0.1:6379> hset user:1 name tom
(integer) 1
127.0.0.1:6379> hset user:1 age 23
(integer) 1
127.0.0.1:6379> hset user:1 city tianjin
(integer) 1
127.0.0.1:6379> hlen user:1
(integer) 3
(5) Batch set or get field-value
hmget key field [field ...]
hmset key field value [field value ...]
hmset and hmget They are batch setting and obtaining field-value,hmset The required parameter is key
And many pairs field-value,hmget The required parameter is key And multiple field. for example :
127.0.0.1:6379> hmset user:1 name mike age 12 city tianjin
OK
127.0.0.1:6379> hmget user:1 name city
1) "mike"
2) "tianjin"
(6) Judge field Whether there is
hexists key field
for example ,user:1 contain name Domain , So the return result is 1, Return when not included 0:
127.0.0.1:6379> hexists user:1 name
(integer) 1
(7) Get all field
hkeys key
hkeys The order should be hfields More appropriate , It returns all of the field, example
Such as :
127.0.0.1:6379> hkeys user:1
1) "name"
2) "age"
3) "city"
(8) Get all value
hvals key
The following operation gets user:1 All value:
127.0.0.1:6379> hvals user:1
1) "mike"
2) "12"
3) "tianjin"
(9) Get all field-value
hgetall key
The following operation gets user:1 be-all field-value:
127.0.0.1:6379> hgetall user:1
1) "name"
2) "mike"
3) "age"
4) "12"
5) "city"
6) "tianjin"
Development tips
In the use of hgetall when , If there are many hash elements , There will be blocking Redis The possibility of .
If the developer just needs to get part of it field, have access to hmget, If you have to get everything
field-value, have access to hscan command , This command iterates over the hash type ,hscan Will be in
2.7 Section introduction .
(10)hincrby hincrbyfloat
hincrby key field
hincrbyfloat key field
hincrby and hincrbyfloat, It's like incrby and incrbyfloat command , But their work
The domain is filed.
(11) Calculation value String length of ( need Redis3.2 above )
hstrlen key field
for example hget user:1name Of value yes tom, that hstrlen The return result is 3:
127.0.0.1:6379> hstrlen user:1 name
(integer) 3
surface 2-3 Is the time complexity of hash type commands , Developers can refer to this table to select the appropriate
The order of .
2.3.2 Internal encoding
There are two types of internal encoding for hash types :
·ziplist( Compressed list ): When the number of hash type elements is less than hash-max-ziplist-entries
To configure ( Default 512 individual )、 At the same time, all values are less than hash-max-ziplist-value To configure ( Default 64
byte ) when ,Redis Will use ziplist As an internal implementation of hash ,ziplist Use more compact
Structure realizes the continuous storage of multiple elements , So in terms of saving memory hashtable Better .
·hashtable( Hashtable ): When the hash type cannot be satisfied ziplist The condition of ,Redis Can make
use hashtable As an internal implementation of hash , Because at this time ziplist The efficiency of reading and writing will decrease , and
hashtable The time complexity of reading and writing is O(1).
The following example demonstrates the internal encoding of a hash type , And the corresponding changes .
1) When field The number is small and there is no big one value when , The internal code is ziplist:
127.0.0.1:6379> hmset hashkey f1 v1 f2 v2
OK
127.0.0.1:6379> object encoding hashkey
"ziplist"
2.1) When there is value Greater than 64 byte , The internal code will be written by ziplist Turn into hashtable:
127.0.0.1:6379> hset hashkey f3 "one string is bigger than 64 byte... Ignore ..."
OK
127.0.0.1:6379> object encoding hashkey
"hashtable"
2.2) When field The number exceeds 512, Internal coding will also be done by ziplist Turn into hashtable:
127.0.0.1:6379> hmset hashkey f1 v1 f2 v2 f3 v3 ... Ignore ... f513 v513
OK
127.0.0.1:6379> object encoding hashkey
"hashtable"
2.3.3 Use scenarios
chart 2-15 Two pieces of user information recorded for a relational data table , The user's properties are the columns of the table ,
Each user information as a line .
If you store it in a hash type , Pictured 2-16 Shown .
Instead of caching user information using string serialization , Hash types become more intuitive , also
102
It will be more convenient to update . Each user's id Defined as the key suffix , How to field-
value Attribute corresponding to each user , Similar to the following pseudo code :
UserInfo getUserInfo(long id){
// user id As key suffix
userRedisKey = "user:info:" + id;
// Use hgetall Get all user information mapping relationships
userInfoMap = redis.hgetAll(userRedisKey);
UserInfo userInfo;
if (userInfoMap != null) {
// Convert the mapping relationship to UserInfo
userInfo = transferMapToUserInfo(userInfoMap);
} else {
// from MySQL Get user information
userInfo = mysql.get(id);
// take userInfo Change to mapping relation using hmset Save to Redis in
redis.hmset(userRedisKey, transferUserInfoToMap(userInfo));
// Add expiration time
redis.expire(userRedisKey, 3600);
}
return userInfo;
}
But it should be noted that there are two differences between hash type and relational database :
· Hash type is sparse , And relational databases are completely structured , For example, hash type
Each key can have a different field, Once a new column is added to a relational database , All lines should be
Its setting value ( Even for NULL), Pictured 2-17 Shown .
· Relational databases can do complex relational queries , and Redis To simulate complex relational queries
Development is difficult , Maintenance costs are high .
Developers need to understand the characteristics of both , In order to use the right technology in the right scene
Technique . up to now , We've been able to cache user information in three ways , Three methods are given below
Implementation method and analysis of advantages and disadvantages of the case .
1) Native string type : One key per attribute .
set user:1:name tom
set user:1:age 23
set user:1:city beijing
advantage : Simple and intuitive , Each property supports update operations .
shortcoming : Too many keys , Large memory consumption , At the same time, the cohesion of user information is relatively poor ,
So this kind of solution will not be used in the production environment .
2) Serialized string type : Serialize user information and save it with a key .
set user:1 serialize(userInfo)
advantage : Simplify programming , If the reasonable use of serialization can improve the efficiency of memory use .
shortcoming : Serialization and deserialization have some overhead , At the same time, every time the attribute is updated, the full
Part of the data is taken out for deserialization , Update and serialize to Redis in .
3) Hash type : Each user attribute uses a pair of field-value, But with only one key
save .
hmset user:1 name tomage 23 city beijing
advantage : Simple and intuitive , If used reasonably, it can reduce the use of memory space .
shortcoming : To control the hash in ziplist and hashtable Conversion of two internal codes ,hashtable Meeting
Consume more memory .
边栏推荐
- UML图记忆技巧
- NFT insider 64: e-commerce giant eBay submitted an NFT related trademark application, and KPMG will invest $30million in Web3 and metauniverse
- 攻防世界 MISC 进阶区 Ditf
- MySQL Architecture - user rights and management
- Redis入门完整教程:Bitmaps
- Redis入门完整教程:列表讲解
- 环境加密技术解析
- 位运算符讲解
- MySQL Architecture - logical architecture
- Redis démarrer le tutoriel complet: Pipeline
猜你喜欢
Detailed explanation of heap sort code
Redis入门完整教程:慢查询分析
Hit the core in the advanced area of misc in the attack and defense world
【机器学习】手写数字识别
Mongodb aggregation operation summary
Redis的持久化机制
Lost in the lock world of MySQL
位运算符讲解
Analysis of the self increasing and self decreasing of C language function parameters
Complete tutorial for getting started with redis: bitmaps
随机推荐
剑指 Offer 67. 把字符串转换成整数
9 - 类
Notepad++--编辑的技巧
Co create a collaborative ecosystem of software and hardware: the "Joint submission" of graphcore IPU and Baidu PaddlePaddle appeared in mlperf
Advanced area of attack and defense world misc 3-11
攻防世界 MISC 进阶区 can_has_stdio?
页面关闭前,如何发送一个可靠请求
【ODX Studio編輯PDX】-0.2-如何對比Compare兩個PDX/ODX文件
Li Kou 98: verify binary search tree
Editplus-- usage -- shortcut key / configuration / background color / font size
Redis入门完整教程:Pipeline
华泰证券是国家认可的券商吗?开户安不安全?
Business is too busy. Is there really no reason to have time for automation?
Redis入门完整教程:Bitmaps
MySQL Architecture - logical architecture
企业如何跨越数字化鸿沟?尽在云原生2.0
The Sandbox 和数字好莱坞达成合作,通过人力资源开发加速创作者经济的发展
Tla+ introductory tutorial (1): introduction to formal methods
Redis introduction complete tutorial: slow query analysis
Analysis of the self increasing and self decreasing of C language function parameters