Postgres 9.4.12 慢查询

Postgres 9.4.12 Slow queries

我在 table 有 900 万行的 postgres 中查询速度很慢。

查询:EXPLAIN (ANALYZE, BUFFERS) SELECT date_point, geo, alarms, status FROM tracking_master WHERE id_asset = 151 AND date_point >= '2017-07-21 19:20:05' AND date_point <= '2017-07-21 19:25:05' ORDER BY date_point asc LIMIT 1000

此处查询 EXPLAIN (ANALYZE, BUFFERS):

Limit  (cost=161175.31..161175.32 rows=1 width=579) (actual time=60734.109..60734.113 rows=5 loops=1)
  Buffers: shared hit=23470 read=114350
  ->  Sort  (cost=161175.31..161175.32 rows=1 width=579) (actual time=60734.107..60734.110 rows=5 loops=1)
        Sort Key: date_point
        Sort Method: quicksort  Memory: 27kB
        Buffers: shared hit=23470 read=114350
        ->  Index Scan using idx_tracking_master_id_asset on tracking_master  (cost=0.43..161175.30 rows=1 width=579) (actual time=80.682..60734.081 rows=5 loops=1)
              Index Cond: (id_asset = 151)
              Filter: ((date_point >= '2017-07-21 19:20:05-03'::timestamp with time zone) AND (date_point <= '2017-07-21 19:25:05-03'::timestamp with time zone))
              Rows Removed by Filter: 202512
              Buffers: shared hit=23470 read=114350
Planning time: 0.204 ms
Execution time: 60734.152 ms

没有查询,很难提供帮助。您的 where 子句中似乎有这样的内容:

    id_asset=151 
AND (date_point >= '2017-07-21 19:20:05-03') 
AND (date_point <= '2017-07-21 19:25:05-03')

并且在 id_asset 列上有一个索引。

尝试在 (id_asset, date_point) 上创建多列索引。我看到您也在使用 ORDER BY 子句。指定日期列的排序顺序可能会有所帮助。

示例:

CREATE INDEX multicol_index ON tracking_master (id_asset, date_point DESC);

(提示:创建索引后使用 VACUUM ANALYZE)