如何找到慢速查询和修复,是否有任何工具可以在PostgreSQL中找到慢速查询?

时间:2018-03-14 06:09:50

标签: postgresql psql postgresql-9.5

select
   min(aml.id) as id,
   aml.name as name,
   round(sum(aml.debit),2) as debit,
   round(sum(aml.credit),2) as credit,
   round(sum(aml.balance),2) as balance,                
   aml.account_id as account_id,
   aml.move_id as move_id,
   aml.journal_id as journal_id,
   aml.date as date,
   aml.company_id as company_id,
   aml.invoice_id as invoice_id,
   aml.partner_id as partner_id
 from 
    account_move_line aml
 group by
   aml.name,
   aml.debit,
   aml.credit,
   aml.balance,
   aml.account_id,
   aml.move_id,
   aml.journal_id,
   aml.date,
   aml.company_id,
   aml.invoice_id,
   aml.partner_id
 order by 
   id limit 10

如何找到慢速查询和修复,是否有任何工具可以在PostgreSQL中找到慢速查询? 我坚持这个查询它需要1分钟加载。 / 解释节目 /

Limit  (cost=120766.57..120766.59 rows=10 width=76)
   ->  Sort  (cost=120766.57..122071.83 rows=522104 width=76)
         Sort Key: (min(id))
         ->  HashAggregate  (cost=96431.49..109484.09 rows=522104 width=76)
               Group Key: name, debit, credit, balance, account_id, move_id, journal_id, date, company_id, invoice_id, partner_id
               ->  Seq Scan on account_move_line aml  (cost=0.00..47130.05 rows=1314705 width=76)

/ 解释分析节目 /

Limit  (cost=120766.57..120766.59 rows=10 width=76) (actual time=67457.650..67457.657 rows=10 loops=1)
   ->  Sort  (cost=120766.57..122071.83 rows=522104 width=76) (actual time=67457.636..67457.636 rows=10 loops=1)
         Sort Key: (min(id))
         Sort Method: top-N heapsort  Memory: 26kB
         ->  HashAggregate  (cost=96431.49..109484.09 rows=522104 width=76) (actual time=65464.360..67028.469 rows=1314669 loops=1)
               Group Key: name, debit, credit, balance, account_id, move_id, journal_id, date, company_id, invoice_id, partner_id
               ->  Seq Scan on account_move_line aml  (cost=0.00..47130.05 rows=1314705 width=76) (actual time=118.524..51252.823 rows=1314705 loops=1)
 Planning time: 0.742 ms
 Execution time: 67610.996 ms

1 个答案:

答案 0 :(得分:0)

要查找消耗最多时间的查询,请使用pg_stat_statements contrib。

关于慢速查询:

大部分时间都花在从存储中读取表格。现在,一百万行的50秒听起来相当过分,并提出了几个问题:

  • 那是什么类型的存储?

  • 表格是否非常膨胀(pg_relation_size报告什么)?

  • I / O系统是否过载(请使用sariostat或其他操作系统工具进行检查?

  • 可能是因为机器中的RAM太少而没有任何东西被缓存在内存中?

除此之外,它可能提升work_mem可以将HashAggregate变成GroupAggregate并节省几秒钟。