PostgreSQL 9.4非常慢的查询

时间:2016-01-24 23:33:32

标签: sql database performance postgresql postgresql-9.4

对于返回相对少量行的查询,我遇到了很长的响应时间。返回约130万行需要三分钟。我认为这是一个索引问题,除了计算行几乎没有时间。

Amazon AWS:根据AWS控制台,它在带有SSD(已禁用IOPS)的RDS t2.medium上运行。

表格:

CREATE TABLE IF NOT EXISTS ip_range_domains (
  ip_range_domain_id     BIGSERIAL PRIMARY KEY,
  domain_id              BIGINT REFERENCES domains                        NOT NULL,
  source_type_id         INTEGER REFERENCES source_types                  NOT NULL,
  low                    INET                                             NOT NULL,
  high                   INET                                             NOT NULL,
  auto_high_conf         BOOLEAN                                          NOT NULL   DEFAULT FALSE,
  invalidation_reason_id INTEGER REFERENCES invalidation_reasons                     DEFAULT NULL,
  invalidated_at         TIMESTAMP WITHOUT TIME ZONE                                 DEFAULT NULL,
  created_at             TIMESTAMP WITHOUT TIME ZONE                      NOT NULL   DEFAULT current_timestamp
);
CREATE INDEX domain_id_btree ON ip_range_domains (domain_id);

之后我也在它上面创建了一个哈希索引,但它似乎没有任何效果。

慢查询

SELECT * FROM ip_range_domains WHERE domain_id = 400266;

上面的查询花了224.9秒

=> SELECT COUNT(*) FROM ip_range_domains WHERE domain_id = 400266;
  count  
---------
 1383530
(1 row)

上面的查询需要164毫秒才能返回。

=> SELECT COUNT(*) FROM ip_range_domains;
  count   
----------
 23156869
(1 row)

上面的查询需要1.9秒才能完成。

=> EXPLAIN (ANALYZE, BUFFERS) SELECT * FROM ip_range_domains WHERE domain_id = 400266;
                                                                QUERY PLAN                                                                 
-------------------------------------------------------------------------------------------------------------------------------------------
 Bitmap Heap Scan on ip_range_domains  (cost=26398.17..282905.77 rows=1410288 width=55) (actual time=94.046..476.018 rows=1383530 loops=1)
   Recheck Cond: (domain_id = 400266)
   Heap Blocks: exact=44000
   Buffers: shared hit=47783
   ->  Bitmap Index Scan on test_index_9  (cost=0.00..26045.60 rows=1410288 width=0) (actual time=85.699..85.699 rows=1383530 loops=1)
         Index Cond: (domain_id = 400266)
         Buffers: shared hit=3783
 Planning time: 0.122 ms
 Execution time: 697.753 ms
(9 rows)

Postgres版本:

=> select version();
                                                    version                                                    
---------------------------------------------------------------------------------------------------------------
 PostgreSQL 9.4.4 on x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.8.2 20140120 (Red Hat 4.8.2-16), 64-bit
(1 row)

RDS信息:

db.t2.medium
IOPS: disabled

0 个答案:

没有答案