当前位置:网站首页>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 .
边栏推荐
- 云服务器设置ssh密钥登录
- Photoshop批量给不同的图片添加不同的编号
- 串口数据帧
- [odx Studio Edit pdx] - 0.2 - Comment comparer deux fichiers pdx / odx
- MYSQL架构——用户权限与管理
- Analog rocker controlled steering gear
- One of the commonly used technical indicators, reading boll Bollinger line indicators
- Redis入门完整教程:初识Redis
- Record: how to scroll screenshots of web pages on Microsoft edge in win10 system?
- Create Ca and issue certificate through go language
猜你喜欢
【室友用一局王者荣耀的时间学会了用BI报表数据处理】
Unity修仙手游 | lua动态滑动功能(3种源码具体实现)
PMO: compare the sample efficiency of 25 molecular optimization methods
Serial port data frame
小程序vant tab组件解决文字过多显示不全的问题
Redis入门完整教程:Pipeline
Redis入门完整教程:哈希说明
Redis getting started complete tutorial: Geo
Duplicate ADMAS part name
Redis introduction complete tutorial: client communication protocol
随机推荐
Taobao commodity review API interface (item_review get Taobao commodity review API interface), tmall commodity review API interface
啃下大骨头——排序(二)
How to send a reliable request before closing the page
The Sandbox 和数字好莱坞达成合作,通过人力资源开发加速创作者经济的发展
[OpenGL] note 29 anti aliasing (MSAA)
Google Earth Engine(GEE)——以MODIS/006/MCD19A2为例批量下载逐天AOD数据逐天的均值、最大值、最小值、标准差、方差统计分析和CSV下载(北京市各区为例)
Redis introduction complete tutorial: slow query analysis
String类中的常用方法
剑指 Offer 65. 不用加减乘除做加法
Feature scaling normalization
Record: how to scroll screenshots of web pages on Microsoft edge in win10 system?
Close system call analysis - Performance Optimization
Gnawing down the big bone - sorting (II)
Redis démarrer le tutoriel complet: Pipeline
Redis入门完整教程:Redis使用场景
Google Earth engine (GEE) -- take modis/006/mcd19a2 as an example to batch download the daily mean, maximum, minimum, standard deviation, statistical analysis of variance and CSV download of daily AOD
浅聊一下中间件
Photoshop批量给不同的图片添加不同的编号
A complete tutorial for getting started with redis: transactions and Lua
Complete tutorial for getting started with redis: bitmaps