前言
我負(fù)責(zé)的有幾個系統(tǒng)隨著業(yè)務(wù)量的增長,存儲在MySQL中的數(shù)據(jù)日益劇增,我當(dāng)時就想現(xiàn)在的業(yè)務(wù)方不講武德,搞偷襲,趁我沒反應(yīng)過來把很多表,很快,很快啊都打到了億級別,這就導(dǎo)致跟其Join的表的SQL變得很慢,對的應(yīng)用接口的response time也變長了,影響了用戶體驗。
事后我分析原因發(fā)現(xiàn),發(fā)現(xiàn)有些表的數(shù)據(jù)量增長很快,對應(yīng)SQL掃描了很多無效數(shù)據(jù),導(dǎo)致SQL慢了下來,通過確認(rèn)之后,這些大表都是一些流水、記錄、日志類型數(shù)據(jù),只需要保留1到3個月,此時需要對表做數(shù)據(jù)清理實現(xiàn)瘦身,一般都會想到用insert + delete的方式去清理。
這篇文章我會從InnoDB存儲空間分布,delete對性能的影響,以及優(yōu)化建議方面解釋為什么不建議delete刪除數(shù)據(jù)。
InnoDB存儲架構(gòu)
從這張圖可以看到,InnoDB存儲結(jié)構(gòu)主要包括兩部分:邏輯存儲結(jié)構(gòu)和物理存儲結(jié)構(gòu)。
邏輯上是由表空間tablespace —> 段segment或者inode —> 區(qū)Extent ——>數(shù)據(jù)頁Page構(gòu)成,Innodb邏輯管理單位是segment,空間分配的最小單位是extent,每個segment都會從表空間FREE_PAGE中分配32個page,當(dāng)這32個page不夠用時,會按照以下原則進行擴展:如果當(dāng)前小于1個extent,則擴展到1個extent;當(dāng)表空間小于32MB時,每次擴展一個extent;表空間大于32MB,每次擴展4個extent。
物理上主要由系統(tǒng)用戶數(shù)據(jù)文件,日志文件組成,數(shù)據(jù)文件主要存儲MySQL字典數(shù)據(jù)和用戶數(shù)據(jù),日志文件記錄的是data page的變更記錄,用于MySQL Crash時的恢復(fù)。
Innodb表空間
InnoDB存儲包括三類表空間:系統(tǒng)表空間,用戶表空間,Undo表空間。
**系統(tǒng)表空間:**主要存儲MySQL內(nèi)部的數(shù)據(jù)字典數(shù)據(jù),如information_schema下的數(shù)據(jù)。
**用戶表空間:**當(dāng)開啟innodb_file_per_table=1時,數(shù)據(jù)表從系統(tǒng)表空間獨立出來存儲在以table_name.ibd命令的數(shù)據(jù)文件中,結(jié)構(gòu)信息存儲在table_name.frm文件中。
**Undo表空間:**存儲Undo信息,如快照一致讀和flashback都是利用undo信息。
從MySQL 8.0開始允許用戶自定義表空間,具體語法如下:
CREATE TABLESPACE tablespace_name
ADD DATAFILE 'file_name' #數(shù)據(jù)文件名
USE LOGFILE GROUP logfile_group #自定義日志文件組,一般每組2個logfile。
[EXTENT_SIZE [=] extent_size] #區(qū)大小
[INITIAL_SIZE [=] initial_size] #初始化大小
[AUTOEXTEND_SIZE [=] autoextend_size] #自動擴寬尺寸
[MAX_SIZE [=] max_size] #單個文件最大size,最大是32G。
[NODEGROUP [=] nodegroup_id] #節(jié)點組
[WAIT]
[COMMENT [=] comment_text]
ENGINE [=] engine_name
復(fù)制代碼
這樣的好處是可以做到數(shù)據(jù)的冷熱分離,分別用HDD和SSD來存儲,既能實現(xiàn)數(shù)據(jù)的高效訪問,又能節(jié)約成本,比如可以添加兩塊500G硬盤,經(jīng)過創(chuàng)建卷組vg,劃分邏輯卷lv,創(chuàng)建數(shù)據(jù)目錄并mount相應(yīng)的lv,假設(shè)劃分的兩個目錄分別是/hot_data 和 /cold_data。
這樣就可以將核心的業(yè)務(wù)表如用戶表,訂單表存儲在高性能SSD盤上,一些日志,流水表存儲在普通的HDD上,主要的操作步驟如下:
#創(chuàng)建熱數(shù)據(jù)表空間
create tablespace tbs_data_hot add datafile '/hot_data/tbs_data_hot01.dbf' max_size 20G;
#創(chuàng)建核心業(yè)務(wù)表存儲在熱數(shù)據(jù)表空間
create table booking(id bigint not null primary key auto_increment, …… ) tablespace tbs_data_hot;
#創(chuàng)建冷數(shù)據(jù)表空間
create tablespace tbs_data_cold add datafile '/hot_data/tbs_data_cold01.dbf' max_size 20G;
#創(chuàng)建日志,流水,備份類的表存儲在冷數(shù)據(jù)表空間
create table payment_log(id bigint not null primary key auto_increment, …… ) tablespace tbs_data_cold;
#可以移動表到另一個表空間
alter table payment_log tablespace tbs_data_hot;
復(fù)制代碼
Inndob存儲分布
創(chuàng)建空表查看空間變化
mysql> create table user(id bigint not null primary key auto_increment,
-> name varchar(20) not null default '' comment '姓名',
-> age tinyint not null default 0 comment 'age',
-> gender char(1) not null default 'M' comment '性別',
-> phone varchar(16) not null default '' comment '手機號',
-> create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時間',
-> update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時間'
-> ) engine = InnoDB DEFAULT CHARSET=utf8mb4 COMMENT '用戶信息表';
Query OK, 0 rows affected (0.26 sec)
復(fù)制代碼
# ls -lh user1.ibd
-rw-r----- 1 mysql mysql 96K Nov 6 12:48 user.ibd
復(fù)制代碼
設(shè)置參數(shù)innodb_file_per_table=1時,創(chuàng)建表時會自動創(chuàng)建一個segment,同時分配一個extent,包含32個data page的來存儲數(shù)據(jù),這樣創(chuàng)建的空表默認(rèn)大小就是96KB,extent使用完之后會申請64個連接頁,這樣對于一些小表,或者undo segment,可以在開始時申請較少的空間,節(jié)省磁盤容量的開銷。
# Python2 py_innodb_page_info.py -v /data2/mysql/test/user.ibd
page offset 00000000, page type <File Space Header>
page offset 00000001, page type <Insert Buffer Bitmap>
page offset 00000002, page type <File Segment inode>
page offset 00000003, page type <B-tree Node>, page level <0000>
page offset 00000000, page type <Freshly Allocated Page>
page offset 00000000, page type <Freshly Allocated Page>
Total number of page: 6: #總共分配的頁數(shù)
Freshly Allocated Page: 2 #可用的數(shù)據(jù)頁
Insert Buffer Bitmap: 1 #插入緩沖頁
File Space Header: 1 #文件空間頭
B-tree Node: 1 #數(shù)據(jù)頁
File Segment inode: 1 #文件端inonde,如果是在ibdata1.ibd上會有多個inode。
復(fù)制代碼
插入數(shù)據(jù)后的空間變化
mysql> DELIMITER $$
mysql> CREATE PROCEDURE insert_user_data(num INTEGER)
-> BEGIN
-> DECLARE v_i int unsigned DEFAULT 0;
-> set autocommit= 0;
-> WHILE v_i < num DO
-> insert into user(`name`, age, gender, phone) values (CONCAT('lyn',v_i), mod(v_i,120), 'M', CONCAT('152',ROUND(RAND(1)*100000000)));
-> SET v_i = v_i+1;
-> END WHILE;
-> commit;
-> END $$
Query OK, 0 rows affected (0.01 sec)
mysql> DELIMITER ;
#插入10w數(shù)據(jù)
mysql> call insert_user_data(100000);
Query OK, 0 rows affected (6.69 sec)
復(fù)制代碼
# ls -lh user.ibd
-rw-r----- 1 mysql mysql 14M Nov 6 10:58 /data2/mysql/test/user.ibd
# python2 py_innodb_page_info.py -v /data2/mysql/test/user.ibd
page offset 00000000, page type <File Space Header>
page offset 00000001, page type <Insert Buffer Bitmap>
page offset 00000002, page type <File Segment inode>
page offset 00000003, page type <B-tree Node>, page level <0001> #增加了一個非葉子節(jié)點,樹的高度從1變?yōu)?.
........................................................
page offset 00000000, page type <Freshly Allocated Page>
Total number of page: 896:
Freshly Allocated Page: 493
Insert Buffer Bitmap: 1
File Space Header: 1
B-tree Node: 400
File Segment inode: 1
復(fù)制代碼
delete數(shù)據(jù)后的空間變化
mysql> select min(id),max(id),count(*) from user;
+---------+---------+----------+
| min(id) | max(id) | count(*) |
+---------+---------+----------+
| 1 | 100000 | 100000 |
+---------+---------+----------+
1 row in set (0.05 sec)
#刪除50000條數(shù)據(jù),理論上空間應(yīng)該從14MB變長7MB左右。
mysql> delete from user limit 50000;
Query OK, 50000 rows affected (0.25 sec)
#數(shù)據(jù)文件大小依然是14MB,沒有縮小。
# ls -lh /data2/mysql/test/user1.ibd
-rw-r----- 1 mysql mysql 14M Nov 6 13:22 /data2/mysql/test/user.ibd
#數(shù)據(jù)頁沒有被回收。
# python2 py_innodb_page_info.py -v /data2/mysql/test/user.ibd
page offset 00000000, page type <File Space Header>
page offset 00000001, page type <Insert Buffer Bitmap>
page offset 00000002, page type <File Segment inode>
page offset 00000003, page type <B-tree Node>, page level <0001>
........................................................
page offset 00000000, page type <Freshly Allocated Page>
Total number of page: 896:
Freshly Allocated Page: 493
Insert Buffer Bitmap: 1
File Space Header: 1
B-tree Node: 400
File Segment inode: 1
#在MySQL內(nèi)部是標(biāo)記刪除,
復(fù)制代碼
mysql> use information_schema;
Database changed
mysql> SELECT A.SPACE AS TBL_SPACEID, A.TABLE_ID, A.NAME AS TABLE_NAME, FILE_FORMAT, ROW_FORMAT, SPACE_TYPE, B.INDEX_ID , B.NAME AS INDEX_NAME, PAGE_NO, B.TYPE AS INDEX_TYPE FROM INNODB_SYS_TABLES A LEFT JOIN INNODB_SYS_INDEXES B ON A.TABLE_ID =B.TABLE_ID WHERE A.NAME = 'test/user1';
+-------------+----------+------------+-------------+------------+------------+----------+------------+---------+------------+
| TBL_SPACEID | TABLE_ID | TABLE_NAME | FILE_FORMAT | ROW_FORMAT | SPACE_TYPE | INDEX_ID | INDEX_NAME | PAGE_NO | INDEX_TYPE |
+-------------+----------+------------+-------------+------------+------------+----------+------------+---------+------------+
| 1283 | 1207 | test/user | Barracuda | Dynamic | Single | 2236 | PRIMARY | 3 | 3 |
+-------------+----------+------------+-------------+------------+------------+----------+------------+---------+------------+
1 row in set (0.01 sec)
PAGE_NO = 3 標(biāo)識B-tree的root page是3號頁,INDEX_TYPE = 3是聚集索引。 INDEX_TYPE取值如下:
0 = nonunique secondary index;
1 = automatically generated clustered index (GEN_CLUST_INDEX);
2 = unique nonclustered index;
3 = clustered index;
32 = full-text index;
#收縮空間再后進行觀察
復(fù)制代碼
MySQL內(nèi)部不會真正刪除空間,而且做標(biāo)記刪除,即將delflag:N修改為delflag:Y,commit之后會會被purge進入刪除鏈表,如果下一次insert更大的記錄,delete之后的空間不會被重用,如果插入的記錄小于等于delete的記錄空會被重用,這塊內(nèi)容可以通過知數(shù)堂的innblock工具進行分析。
Innodb中的碎片
碎片的產(chǎn)生
我們知道數(shù)據(jù)存儲在文件系統(tǒng)上的,總是不能100%利用分配給它的物理空間,刪除數(shù)據(jù)會在頁面上留下一些”空洞”,或者隨機寫入(聚集索引非線性增加)會導(dǎo)致頁分裂,頁分裂導(dǎo)致頁面的利用空間少于50%,另外對表進行增刪改會引起對應(yīng)的二級索引值的隨機的增刪改,也會導(dǎo)致索引結(jié)構(gòu)中的數(shù)據(jù)頁面上留下一些"空洞",雖然這些空洞有可能會被重復(fù)利用,但終究會導(dǎo)致部分物理空間未被使用,也就是碎片。
同時,即便是設(shè)置了填充因子為100%,Innodb也會主動留下page頁面1/16的空間作為預(yù)留使用(An innodb_fill_factor setting of 100 leaves 1/16 of the space in clustered index pages free for future index growth)防止update帶來的行溢出。
mysql> select table_schema,
-> table_name,ENGINE,
-> round(DATA_LENGTH/1024/1024+ INDEX_LENGTH/1024/1024) total_mb,TABLE_ROWS,
-> round(DATA_LENGTH/1024/1024) data_mb, round(INDEX_LENGTH/1024/1024) index_mb, round(DATA_FREE/1024/1024) free_mb, round(DATA_FREE/DATA_LENGTH*100,2) free_ratio
-> from information_schema.TABLES where TABLE_SCHEMA= 'test'
-> and TABLE_NAME= 'user';
+--------------+------------+--------+----------+------------+---------+----------+---------+------------+
| table_schema | table_name | ENGINE | total_mb | TABLE_ROWS | data_mb | index_mb | free_mb | free_ratio |
+--------------+------------+--------+----------+------------+---------+----------+---------+------------+
| test | user | InnoDB | 4 | 50000 | 4 | 0 | 6 | 149.42 |
+--------------+------------+--------+----------+------------+---------+----------+---------+------------+
1 row in set (0.00 sec)
復(fù)制代碼
其中data_free是分配了未使用的字節(jié)數(shù),并不能說明完全是碎片空間。
碎片的回收
對于InnoDB的表,可以通過以下命令來回收碎片,釋放空間,這個是隨機讀IO操作,會比較耗時,也會阻塞表上正常的DML運行,同時需要占用額外更多的磁盤空間,對于RDS來說,可能會導(dǎo)致磁盤空間瞬間爆滿,實例瞬間被鎖定,應(yīng)用無法做DML操作,所以禁止在線上環(huán)境去執(zhí)行。
#執(zhí)行InnoDB的碎片回收
mysql> alter table user engine=InnoDB;
Query OK, 0 rows affected (9.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
##執(zhí)行完之后,數(shù)據(jù)文件大小從14MB降低到10M。
# ls -lh /data2/mysql/test/user1.ibd
-rw-r----- 1 mysql mysql 10M Nov 6 16:18 /data2/mysql/test/user.ibd
復(fù)制代碼
mysql> select table_schema, table_name,ENGINE, round(DATA_LENGTH/1024/1024+ INDEX_LENGTH/1024/1024) total_mb,TABLE_ROWS, round(DATA_LENGTH/1024/1024) data_mb, round(INDEX_LENGTH/1024/1024) index_mb, round(DATA_FREE/1024/1024) free_mb, round(DATA_FREE/DATA_LENGTH*100,2) free_ratio from information_schema.TABLES where TABLE_SCHEMA= 'test' and TABLE_NAME= 'user';
+--------------+------------+--------+----------+------------+---------+----------+---------+------------+
| table_schema | table_name | ENGINE | total_mb | TABLE_ROWS | data_mb | index_mb | free_mb | free_ratio |
+--------------+------------+--------+----------+------------+---------+----------+---------+------------+
| test | user | InnoDB | 5 | 50000 | 5 | 0 | 2 | 44.29 |
+--------------+------------+--------+----------+------------+---------+----------+---------+------------+
1 row in set (0.00 sec)
復(fù)制代碼
delete對SQL的影響
未刪除前的SQL執(zhí)行情況
#插入100W數(shù)據(jù)
mysql> call insert_user_data(1000000);
Query OK, 0 rows affected (35.99 sec)
#添加相關(guān)索引
mysql> alter table user add index idx_name(name), add index idx_phone(phone);
Query OK, 0 rows affected (6.00 sec)
Records: 0 Duplicates: 0 Warnings: 0
#表上索引統(tǒng)計信息
mysql> show index from user;
+-------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment |
+-------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
| user | 0 | PRIMARY | 1 | id | A | 996757 | NULL | NULL | | BTREE | | |
| user | 1 | idx_name | 1 | name | A | 996757 | NULL | NULL | | BTREE | | |
| user | 1 | idx_phone | 1 | phone | A | 2 | NULL | NULL | | BTREE | | |
+-------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+
3 rows in set (0.00 sec)
#重置狀態(tài)變量計數(shù)
mysql> flush status;
Query OK, 0 rows affected (0.00 sec)
#執(zhí)行SQL語句
mysql> select id, age ,phone from user where name like 'lyn12%';
+--------+-----+-------------+
| id | age | phone |
+--------+-----+-------------+
| 124 | 3 | 15240540354 |
| 1231 | 30 | 15240540354 |
| 12301 | 60 | 15240540354 |
.............................
| 129998 | 37 | 15240540354 |
| 129999 | 38 | 15240540354 |
| 130000 | 39 | 15240540354 |
+--------+-----+-------------+
11111 rows in set (0.03 sec)
mysql> explain select id, age ,phone from user where name like 'lyn12%';
+----+-------------+-------+-------+---------------+----------+---------+------+-------+-----------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+----------+---------+------+-------+-----------------------+
| 1 | SIMPLE | user | range | idx_name | idx_name | 82 | NULL | 22226 | Using index condition |
+----+-------------+-------+-------+---------------+----------+---------+------+-------+-----------------------+
1 row in set (0.00 sec)
#查看相關(guān)狀態(tài)呢變量
mysql> select * from information_schema.session_status where variable_name in('Last_query_cost','Handler_read_next','Innodb_pages_read','Innodb_data_reads','Innodb_pages_read');
+-------------------+----------------+
| VARIABLE_NAME | VARIABLE_VALUE |
+-------------------+----------------+
| HANDLER_READ_NEXT | 11111 | #請求讀的行數(shù)
| INNODB_DATA_READS | 7868409 | #數(shù)據(jù)物理讀的總數(shù)
| INNODB_PAGES_READ | 7855239 | #邏輯讀的總數(shù)
| LAST_QUERY_COST | 10.499000 | #SQL語句的成本COST,主要包括IO_COST和CPU_COST。
+-------------------+----------------+
4 rows in set (0.00 sec)
復(fù)制代碼
刪除后的SQL執(zhí)行情況
#刪除50w數(shù)據(jù)
mysql> delete from user limit 500000;
Query OK, 500000 rows affected (3.70 sec)
#分析表統(tǒng)計信息
mysql> analyze table user;
+-----------+---------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+-----------+---------+----------+----------+
| test.user | analyze | status | OK |
+-----------+---------+----------+----------+
1 row in set (0.01 sec)
#重置狀態(tài)變量計數(shù)
mysql> flush status;
Query OK, 0 rows affected (0.01 sec)
mysql> select id, age ,phone from user where name like 'lyn12%';
Empty set (0.05 sec)
mysql> explain select id, age ,phone from user where name like 'lyn12%';
+----+-------------+-------+-------+---------------+----------+---------+------+-------+-----------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+----------+---------+------+-------+-----------------------+
| 1 | SIMPLE | user | range | idx_name | idx_name | 82 | NULL | 22226 | Using index condition |
+----+-------------+-------+-------+---------------+----------+---------+------+-------+-----------------------+
1 row in set (0.00 sec)
mysql> select * from information_schema.session_status where variable_name in('Last_query_cost','Handler_read_next','Innodb_pages_read','Innodb_data_reads','Innodb_pages_read');
+-------------------+----------------+
| VARIABLE_NAME | VARIABLE_VALUE |
+-------------------+----------------+
| HANDLER_READ_NEXT | 0 |
| INNODB_DATA_READS | 7868409 |
| INNODB_PAGES_READ | 7855239 |
| LAST_QUERY_COST | 10.499000 |
+-------------------+----------------+
4 rows in set (0.00 sec)
復(fù)制代碼
結(jié)果統(tǒng)計分析
操作 |
COST |
物理讀次數(shù) |
邏輯讀次數(shù) |
掃描行數(shù) |
返回行數(shù) |
執(zhí)行時間 |
初始化插入100W |
10.499000 |
7868409 |
7855239 |
22226 |
11111 |
30ms |
100W隨機刪除50W |
10.499000 |
7868409 |
7855239 |
22226 |
0 |
50ms |
這也說明對普通的大表,想要通過delete數(shù)據(jù)來對表進行瘦身是不現(xiàn)實的,所以在任何時候不要用delete去刪除數(shù)據(jù),應(yīng)該使用優(yōu)雅的標(biāo)記刪除。
delete優(yōu)化建議
控制業(yè)務(wù)賬號權(quán)限
對于一個大的系統(tǒng)來說,需要根據(jù)業(yè)務(wù)特點去拆分子系統(tǒng),每個子系統(tǒng)可以看做是一個service,例如美團App,上面有很多服務(wù),核心的服務(wù)有用戶服務(wù)user-service,搜索服務(wù)search-service,商品product-service,位置服務(wù)location-service,價格服務(wù)price-service等。每個服務(wù)對應(yīng)一個數(shù)據(jù)庫,為該數(shù)據(jù)庫創(chuàng)建單獨賬號,同時只授予DML權(quán)限且沒有delete權(quán)限,同時禁止跨庫訪問。
#創(chuàng)建用戶數(shù)據(jù)庫并授權(quán)
create database mt_user charset utf8mb4;
grant USAGE, SELECT, INSERT, UPDATE ON mt_user.* to 'w_user'@'%' identified by 't$W*g@gaHTGi123456';
flush privileges;
復(fù)制代碼
delete改為標(biāo)記刪除
在MySQL數(shù)據(jù)庫建模規(guī)范中有4個公共字段,基本上每個表必須有的,同時在create_time列要創(chuàng)建索引,有兩方面的好處:
- 一些查詢業(yè)務(wù)場景都會有一個默認(rèn)的時間段,比如7天或者一個月,都是通過create_time去過濾,走索引掃描更快。
- 一些核心的業(yè)務(wù)表需要以T +1的方式抽取數(shù)據(jù)倉庫中,比如每天晚上00:30抽取前一天的數(shù)據(jù),都是通過create_time過濾的。
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵id',
`is_deleted` tinyint(4) NOT NULL DEFAULT '0' COMMENT '是否邏輯刪除:0:未刪除,1:已刪除',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '創(chuàng)建時間',
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改時間'
#有了刪除標(biāo)記,業(yè)務(wù)接口的delete操作就可以轉(zhuǎn)換為update
update user set is_deleted = 1 where user_id = 1213;
#查詢的時候需要帶上is_deleted過濾
select id, age ,phone from user where is_deleted = 0 and name like 'lyn12%';
復(fù)制代碼
數(shù)據(jù)歸檔方式
通用數(shù)據(jù)歸檔方法
#1. 創(chuàng)建歸檔表,一般在原表名后面添加_bak。
CREATE TABLE `ota_order_bak` (
`id` bigint(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
`order_id` varchar(255) DEFAULT NULL COMMENT '訂單id',
`ota_id` varchar(255) DEFAULT NULL COMMENT 'ota',
`check_in_date` varchar(255) DEFAULT NULL COMMENT '入住日期',
`check_out_date` varchar(255) DEFAULT NULL COMMENT '離店日期',
`hotel_id` varchar(255) DEFAULT NULL COMMENT '酒店ID',
`guest_name` varchar(255) DEFAULT NULL COMMENT '顧客',
`purcharse_time` timestamp NULL DEFAULT NULL COMMENT '購買時間',
`create_time` datetime DEFAULT NULL,
`update_time` datetime DEFAULT NULL,
`create_user` varchar(255) DEFAULT NULL,
`update_user` varchar(255) DEFAULT NULL,
`status` int(4) DEFAULT '1' COMMENT '狀態(tài) : 1 正常 , 0 刪除',
`hotel_name` varchar(255) DEFAULT NULL,
`price` decimal(10,0) DEFAULT NULL,
`remark` longtext,
PRIMARY KEY (`id`),
KEY `IDX_order_id` (`order_id`) USING BTREE,
KEY `hotel_name` (`hotel_name`) USING BTREE,
KEY `ota_id` (`ota_id`) USING BTREE,
KEY `IDX_purcharse_time` (`purcharse_time`) USING BTREE,
KEY `IDX_create_time` (`create_time`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8
PARTITION BY RANGE (to_days(create_time)) (
PARTITION p201808 VALUES LESS THAN (to_days('2018-09-01')),
PARTITION p201809 VALUES LESS THAN (to_days('2018-10-01')),
PARTITION p201810 VALUES LESS THAN (to_days('2018-11-01')),
PARTITION p201811 VALUES LESS THAN (to_days('2018-12-01')),
PARTITION p201812 VALUES LESS THAN (to_days('2019-01-01')),
PARTITION p201901 VALUES LESS THAN (to_days('2019-02-01')),
PARTITION p201902 VALUES LESS THAN (to_days('2019-03-01')),
PARTITION p201903 VALUES LESS THAN (to_days('2019-04-01')),
PARTITION p201904 VALUES LESS THAN (to_days('2019-05-01')),
PARTITION p201905 VALUES LESS THAN (to_days('2019-06-01')),
PARTITION p201906 VALUES LESS THAN (to_days('2019-07-01')),
PARTITION p201907 VALUES LESS THAN (to_days('2019-08-01')),
PARTITION p201908 VALUES LESS THAN (to_days('2019-09-01')),
PARTITION p201909 VALUES LESS THAN (to_days('2019-10-01')),
PARTITION p201910 VALUES LESS THAN (to_days('2019-11-01')),
PARTITION p201911 VALUES LESS THAN (to_days('2019-12-01')),
PARTITION p201912 VALUES LESS THAN (to_days('2020-01-01')));
#2. 插入原表中無效的數(shù)據(jù)(需要跟開發(fā)同學(xué)確認(rèn)數(shù)據(jù)保留范圍)
create table tbl_p201808 as select * from ota_order where create_time between '2018-08-01 00:00:00' and '2018-08-31 23:59:59';
#3. 跟歸檔表分區(qū)做分區(qū)交換
alter table ota_order_bak exchange partition p201808 with table tbl_p201808;
#4. 刪除原表中已經(jīng)規(guī)范的數(shù)據(jù)
delete from ota_order where create_time between '2018-08-01 00:00:00' and '2018-08-31 23:59:59' limit 3000;
復(fù)制代碼
優(yōu)化后的歸檔方式
#1. 創(chuàng)建中間表
CREATE TABLE `ota_order_2020` (........) ENGINE=InnoDB DEFAULT CHARSET=utf8
PARTITION BY RANGE (to_days(create_time)) (
PARTITION p201808 VALUES LESS THAN (to_days('2018-09-01')),
PARTITION p201809 VALUES LESS THAN (to_days('2018-10-01')),
PARTITION p201810 VALUES LESS THAN (to_days('2018-11-01')),
PARTITION p201811 VALUES LESS THAN (to_days('2018-12-01')),
PARTITION p201812 VALUES LESS THAN (to_days('2019-01-01')),
PARTITION p201901 VALUES LESS THAN (to_days('2019-02-01')),
PARTITION p201902 VALUES LESS THAN (to_days('2019-03-01')),
PARTITION p201903 VALUES LESS THAN (to_days('2019-04-01')),
PARTITION p201904 VALUES LESS THAN (to_days('2019-05-01')),
PARTITION p201905 VALUES LESS THAN (to_days('2019-06-01')),
PARTITION p201906 VALUES LESS THAN (to_days('2019-07-01')),
PARTITION p201907 VALUES LESS THAN (to_days('2019-08-01')),
PARTITION p201908 VALUES LESS THAN (to_days('2019-09-01')),
PARTITION p201909 VALUES LESS THAN (to_days('2019-10-01')),
PARTITION p201910 VALUES LESS THAN (to_days('2019-11-01')),
PARTITION p201911 VALUES LESS THAN (to_days('2019-12-01')),
PARTITION p201912 VALUES LESS THAN (to_days('2020-01-01')));
#2. 插入原表中有效的數(shù)據(jù),如果數(shù)據(jù)量在100W左右可以在業(yè)務(wù)低峰期直接插入,如果比較大,建議采用dataX來做,可以控制頻率和大小,之前我這邊用Go封裝了dataX可以實現(xiàn)自動生成json文件,自定義大小去執(zhí)行。
insert into ota_order_2020 select * from ota_order where create_time between '2020-08-01 00:00:00' and '2020-08-31 23:59:59';
#3. 表重命名
alter table ota_order rename to ota_order_bak;
alter table ota_order_2020 rename to ota_order;
#4. 插入差異數(shù)據(jù)
insert into ota_order select * from ota_order_bak a where not exists (select 1 from ota_order b where a.id = b.id);
#5. ota_order_bak改造成分區(qū)表,如果表比較大不建議直接改造,可以先創(chuàng)建好分區(qū)表,通過dataX把導(dǎo)入進去即可。
#6. 后續(xù)的歸檔方法
#創(chuàng)建中間普遍表
create table ota_order_mid like ota_order;
#交換原表無效數(shù)據(jù)分區(qū)到普通表
alter table ota_order exchange partition p201808 with table ota_order_mid;
##交換普通表數(shù)據(jù)到歸檔表的相應(yīng)分區(qū)
alter table ota_order_bak exchange partition p201808 with table ota_order_mid;
復(fù)制代碼
這樣原表和歸檔表都是按月的分區(qū)表,只需要創(chuàng)建一個中間普通表,在業(yè)務(wù)低峰期做兩次分區(qū)交換,既可以刪除無效數(shù)據(jù),又能回收空,而且沒有空間碎片,不會影響表上的索引及SQL的執(zhí)行計劃。
總結(jié)
通過從InnoDB存儲空間分布,delete對性能的影響可以看到,delete物理刪除既不能釋放磁盤空間,而且會產(chǎn)生大量的碎片,導(dǎo)致索引頻繁分裂,影響SQL執(zhí)行計劃的穩(wěn)定性;
同時在碎片回收時,會耗用大量的CPU,磁盤空間,影響表上正常的DML操作。
在業(yè)務(wù)代碼層面,應(yīng)該做邏輯標(biāo)記刪除,避免物理刪除;為了實現(xiàn)數(shù)據(jù)歸檔需求,可以用采用MySQL分區(qū)表特性來實現(xiàn),都是DDL操作,沒有碎片產(chǎn)生。
另外一個比較好的方案采用Clickhouse,對有生命周期的數(shù)據(jù)表可以使用Clickhouse存儲,利用其TTL特性實現(xiàn)無效數(shù)據(jù)自動清理。