微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Postgres 中优化此查询

如何解决如何在 Postgres 中优化此查询

以下查询需要更多时间来运行。如何优化以下查询以运行更多记录?我已为此查询运行 Explain Analyze。附上相同的输出

这是作为视图创建的现有查询,需要很长时间(超过几个小时)才能返回结果。

我已经对这 2 个表进行了清理、分析和重新索引,但没有成功。

select st_tr.step_trail_id,st_tr.test_id,st_tr.trail_id,st_tr.step_name,filter.regular_expression as filter_expression,filter.order_of_occurrence as filter_order,filter.match_type as filter_match_type,null as begins_with,null as ends_with,null as input_source,null as pattern_expression,null as pattern_matched,null as pattern_status,null as pattern_order,'filter' as record_type
from tab_report_step st_tr,tab_report_filter filter
where st_tr.st_tr_id = filter.st_tr_id)

查询计划:

 Hash Join  (cost=446852.58..1176380.76 rows=6353676 width=489) (actual time=16641.953..47270.831 rows=6345360 loops=1)
   Buffers: shared hit=1 read=451605 dirtied=5456 written=5424,temp read=154080 written=154074
   -> Seq Scan on tab_report_filter filter  (cost=0..24482.76 rows=6353676 width=161) (actual time=0.041..8097.233 rows=6345360 loops=1)
      Buffers: shared read=179946 dirtied=4531 written=4499
   -> Hash  (cost=318817.7..318817.7 rows=4716070 width=89) (actual time=16627.291..16627.291 rows=4709040 loops=1)
      Buffers: shared hit=1 read=271656 dirtied=925 written=925,temp written=47629
        -> Seq Scan on tab_report_step st_tr  (cost=0..318817.7 rows=4716070 width=89) (actual time=0.059..10215.484 rows=4709040 loops=1)
           Buffers: shared hit=1 read=271656 dirtied=925 written=925

解决方法

没有在这些表上运行 VACUUM。也许VACUUM (FULL),但肯定不是VACUUM

有两点可以改进:

  • 确保在您阅读时没有弄脏或书写任何页面。这很可能是因为这是您第一次读取行,并且 PostgreSQL 设置了提示位

    运行 VACUUM(没有 FULL)可以解决这个问题。另外,如果你重复这个实验,你不应该再得到那些脏的和写过的缓冲区。

  • 通过增加 work_mem 为查询提供更多内存。散列不适合 work_mem 并溢出到磁盘,这会导致额外的磁盘读写,这对性能不利。

由于您连接了两个没有限制 WHERE 条件的大表并且有很多结果行,因此此查询永远不会很快。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。