MySQL 的分區(qū)表是一種簡單有效的處理極大數據表的特性,通過它可以使應用程序幾乎很少改動就能達成對極大數據表的高效處理,但由于 Rails ActiveRecord 設計上一些慣例,可能導致一些數據處理不能利用分區(qū)表特性,反而變得很慢,在使用分區(qū)表過程中一定要多加注意。
下面以一個例子來說明。在 light 系統(tǒng)中,有一張數據表是 diet_items, 主要字段是 id, schedule_id, meal_order food_id, weight, calory 等等,它的每一條記錄表示為用戶生成每日的減肥計劃(減肥食譜 + 運動計劃)中的一條飲食項,平均一條的計劃有 10 多條數據,數據量非常大,預計每天生成數據會超過 100 萬條,所以對其做了分表處理,根據 schedule_id hash 分成 60 張表,也就是數據將動態(tài)分到 60 張表中。分表后 diet_items 的建表語句如下所示:
復制代碼 代碼如下:
CREATE TABLE `diet_items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`schedule_id` int(11) NOT NULL,
`meals_order` int(11) NOT NULL,
`food_id` int(11) DEFAULT NULL,
....
KEY id (`id`),
UNIQUE KEY `index_diet_items_on_schedule_id_and_id` (`schedule_id`,`id`)
)
PARTITION BY HASH (schedule_id)
PARTITIONS 60;
分表之后,所有查詢 diet_items 的地方都要求帶上 schedule_id,比如獲取某一個 schedule 的所有 diet_items,通過 schedule. diet_items,獲取某一個 id 的 diet_item 也是通過 schedule.diet_items.find(id) 進行。生成 diet_item 也沒有問題,因為生成 diet_item 都是通過 schedule.diet_items.build(data) 方式,在生成的時候都是帶了 schedule_id 的。
觀察 newrelic 日志,發(fā)現(xiàn) diet_item 的 update 和 destroy 相關的請求特別慢,仔細分析后,發(fā)現(xiàn)這兩種操作非常忙是由于 ActiveRecord 生成的 sql 并沒有帶 schedule_id 導致。 diet_item update 操作 ActiveRecord 生成的 sql 語句類似于 update diet_items set … where id = id>。 diet_item destroy 生成的語句類似于 delete diet_items where id = id> 因為沒有帶 schedule_id,導致這兩種語句都需要 mysql 掃描 60 張分區(qū)表才能夠完成一個語句執(zhí)行,非常慢!
知道原因之后就好辦了,把原來的 update 和 destroy 調用改為自定義版本的 update 和 destroy 調用就可以了。
diet_item.update(attributes) 改成 DietItem.where(id: diet_item.id, schedule_id: diet_item.schedule_id).update_all(attributes)
diet_item.destroy 改成 DietItem.where(id: diet_item.id, schedule_id: diet_item.schedule_id).delete_all
這樣生成的 sql 都帶上 schedule_id 條件,從而避免了掃描全部的分區(qū)表,性能提升立竿見影。
您可能感興趣的文章:- MySQL優(yōu)化之分區(qū)表
- 詳解MySQL分區(qū)表
- MySQL最佳實踐之分區(qū)表基本類型
- MySQL分區(qū)表的正確使用方法
- MySQL分區(qū)表的局限和限制詳解
- PostgreSQL分區(qū)表(partitioning)應用實例詳解
- Mysql分區(qū)表的管理與維護
- PostgreSQL教程(三):表的繼承和分區(qū)表詳解
- mysql使用教程之分區(qū)表的使用方法(刪除分區(qū)表)
- 分區(qū)表場景下的 SQL 優(yōu)化