postgresql delete优化

来源:互联网 发布:edius8软件下载 编辑:程序博客网 时间:2024/06/05 19:44

最新需要整理数据库

因为有些表已经达到了2千多万行数据,并且有相当一部分数据是几年以前的

所以那些数据,对于用户来说是没有必要,所以不得不考虑清除部分过期的数据


但是发现当我使用delete时,发现删除数据很慢,语句如下

delete from tablename where id <500000


从sql 上发现,很难有优化的地方了,这种语句已经相当的精炼了

并且查询了下,发现主键已经建立了索引


后来几经查询,终于找到了解决方案(还是搜索国外的好)

原来,我这个表用到了外键,而外键表又用到了外键表,所以是个嵌套的表


所以只需在表的层面调用:

ALTER TABLE mytable DISABLE TRIGGER ALL;

在删除之后再调用:

ALTER TABLE mytable ENABLE TRIGGER ALL;删除数据从几十分钟,缩短到1分钟之内,终于达到了可接受的范围摘自一段老外的描述:
The usual advice when you complain about slow bulk deletions in postgresql is "make sure the foreign keys (pointing to the table you are deleting from) are indexed". This is because postgresql doesn't create the indexes automatically for all the foreign keys (FK) which can be considered a degree of freedom or a nuisance, depends how you look at it. Anyway, the indexing usually solves the performance issue. Unless you stumble upon a FK field that is not indexable. Like I did.

The field in question has the same value repeated over thousands of rows. Neither B-tree nor hash indexing works so postgresql is forced to do the slow sequential scan each time it deletes the table referenced by this FK (because the FK is a constraint and an automated check is triggered). Multiply this by the number of rows deleted and you'll see the minutes adding up.


在删除多余的记录之后

最好做一个vacuum和reindex这2个操作,会让表的物理空间更加优化

REINDEX TABLE tablename

vacuum FULL tablename


经过这件事,让我觉得

你用google搜索对应的外文解决方案一定要输对对应的key

对于这个google的关键字为:

postgres bulk delete

或者

postgres optimize delete


最后附上链接:

http://od-eon.com/blogs/stefan/optimizing-particular-case-bulk-deletion-postgresq/
http://www.linuxinsight.com/optimize_postgresql_database_size.html

原创粉丝点击
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 水观音叶子黄了怎么办 富贵竹根部腐烂发臭怎么办 富贵竹根部发粘怎么办 水竹草叶子发黄怎么办 水竹叶子心发黄怎么办 塔竹叶子发黄怎么办 铁树叶有发黄怎么办 铁树夏天叶发黄怎么办 铁树的叶尖发黄怎么办 铁树叶子发黄是怎么办 榕树盆景长蜜怎么办 六月雪叶子枯萎了怎么办 小叶冬青掉叶子怎么办 榕树叶子发黄落叶怎么办 榕树的叶子发黄怎么办 盆景的叶子发黄怎么办 盆景叶子枯了怎么办 迎春盆景掉叶子怎么办 花叶子边缘干枯怎么办 刺梅的叶子发黄怎么办 榕树叶子发黑落叶怎么办 榕树树叶黄落叶怎么办 铜钱草叶子黄了怎么办 三角梅的叶子发黄怎么办 铜钱草水养叶子发黄怎么办 罗汉松叶片干了怎么办 三角梅叶子发甘怎么办 三角梅叶子蔫了怎么办 土培的绿萝烂根怎么办 水竹叶子变黄怎么办 富贵竹叶子蔫了怎么办 绿萝叶尖干枯怎么办 水竹叶干裂了怎么办 金钱草叶子蔫了怎么办 金钱草叶子太密怎么办 庭院竹子杆发黄怎么办 水竹长根了怎么办 富贵竹生虫子了怎么办 富贵竹张根了怎么办 盆栽树叶子发黄怎么办 水培转运竹杆发黄了怎么办