关于postgresql:Postgresql-慢查询语句记录与分析

5次阅读

共计 1384 个字符,预计需要花费 4 分钟才能阅读完成。

1. 记录

postgresql 以 12 版本为例

咱们须要先关上 postgresql 的慢查问日志,此为前置条件,先记录下咱们工夫较长的查问。

  • 编辑配置文件:/var/postgres12/data/postgresql.conf
#log_min_duration_statement = -1        # -1 is disabled, 0 logs all statements
                                        # and their durations, > 0 logs only
                                        # statements running at least this number
                                        # of milliseconds

批改 -1200,示意大于等于 200 毫秒的操作将被记录到日志。

  • 重载配置
/path/to/pg_ctl reload -D /path/to/pgdata

2. 获取慢查问语句

2.1 切 postgresql 超户

sudo su - postgres

2.2 获取慢查问语句

  • 关上日志文件
less /path/to/pg_log/postgresql.log
  • 跳到文件开端
Shift + G
  • 查问关键字 duration

因为被记录的日志格局形如:

duration xxx ms  select ….

3. 剖析

  • 连贯 postgresql 服务器
path/to/psql -U postgres -d <database>
  • 关上计时
\timing
  • 语句剖析
explain select max(id) as max_id from test_table where  created < now() - interval '24 hours';
                                                          QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------
 Finalize Aggregate  (cost=12673.45..12673.46 rows=1 width=8)
   ->  Gather  (cost=12673.24..12673.45 rows=2 width=8)
         Workers Planned: 2
         ->  Partial Aggregate  (cost=11673.24..11673.25 rows=1 width=8)
               ->  Parallel Seq Scan on test_table  (cost=0.00..10631.80 rows=416575 width=8)
                     Filter: (created < (now() - '24:00:00'::interval))
(6 rows)

explain 是显示查问打算,不会真正执行,所以甚至 update 也能够放在 explain 前面。
然而要留神,不能是 explain analyze,带了 analyze 就真跑了,所以这个不能用于 DML

DQL: SELECT
DML: UPDATE/DELETE/INSERT
DDL: CREATE TABLE/VIEW/INDEX/SYN/CLUSTER
DCL: GRANT/ROLLBACK/COMMIT

另外能够看到后果中显示的是 Seq Scan,程序扫描,所以能够为它创立一个索引,变成 Index Scan

create index test_index on test_table (created);

而后再次剖析,如果工夫没有显著缩小,能够再去掉此索引。
反复以上步骤,即可逐渐缩小零碎中的慢查问。

正文完
 0