Postgresql 提高select查询的性能

Postgresql 提高select查询的性能,postgresql,indexing,query-performance,materialized-views,Postgresql,Indexing,Query Performance,Materialized Views,我有一个物化视图,它聚集了来自多个表的数据,这些表在我的应用程序中存储有关统计数据的信息。目前,此视图包含大约800000条记录。问题是这个查询运行速度非常慢(大约1.5秒),不能满足客户的需求。有什么方法可以提高它的性能吗?我正在使用PostgreSQL 9.6 我试图创建索引。但这没用 CREATE INDEX t1 ON statistic_basic_view (active, visible, removed, draft, id, name, object_type, is_paid

我有一个物化视图,它聚集了来自多个表的数据,这些表在我的应用程序中存储有关统计数据的信息。目前,此视图包含大约800000条记录。问题是这个查询运行速度非常慢(大约1.5秒),不能满足客户的需求。有什么方法可以提高它的性能吗?我正在使用PostgreSQL 9.6

我试图创建索引。但这没用

CREATE INDEX t1 ON statistic_basic_view (active, visible, removed, draft, id, name, object_type, is_paid, company_name);

CREATE INDEX t2 ON statistic_basic_view (company_name, is_paid, object_type, name, id, draft, removed, visible, active);

CREATE INDEX t3 ON statistic_basic_view (company_name, is_paid, object_type, name, id);

CREATE INDEX t4 ON statistic_basic_view (draft, removed, visible, active);

CREATE INDEX t5 ON statistic_basic_view (active, visible, removed, draft);

CREATE INDEX t6 ON statistic_basic_view (id, name, object_type, is_paid, company_name);

CREATE INDEX t8 ON statistic_basic_view (active, visible, removed, draft, id, name, object_type, is_paid, company_name);

CREATE INDEX t9 ON statistic_basic_view ((active AND visible AND (NOT removed) AND (NOT draft)));

CREATE INDEX t10 ON statistic_basic_view (((NOT draft) AND (NOT removed) AND active = true AND visible = true));

查询:

选择id,
名称
对象类型,
你有报酬吗,
公司名称,
总数(例)
当type='COMPARE'
和服务输入('GG_WEB'),然后1
其他0
结束)作为比较计数,
总数(例)
当类型为“导出”时
和服务输入('GG_WEB'),然后1
其他0
结束)作为导出计数,
总数(例)
当type='VIEW'
和服务输入('GG_WEB'),然后1
其他0
结束)作为视图_计数,
总数(例)
当type='记住'
和服务输入('GG_WEB'),然后1
其他0
结束)请记住,
总数(例)
当type='SEARCH'
和服务输入('GG_WEB'),然后1
其他0
结束)作为搜索计数,
总数(例)
当type='MAIL'
和服务输入('GG_WEB'),然后1
其他0
结束)作为邮件计数
从统计基本观点
其中active=TRUE
可见=真
并删除=FALSE
和草稿=假
按id分组,
名称
对象类型,
你有报酬吗,
公司名称
按视图排序\u计数说明,
身份证
限额15;
解释和分析:

Limit  (cost=74204.47..74204.50 rows=15 width=130) (actual time=1420.542..1420.545 rows=15 loops=1)
  ->  Sort  (cost=74204.47..74600.55 rows=158432 width=130) (actual time=1420.540..1420.542 rows=15 loops=1)
        Sort Key: (sum(CASE WHEN ((type = 'VIEW'::text) AND ((service_type)::text = 'GG_WEB'::text)) THEN 1 ELSE 0 END)) DESC, id
        Sort Method: top-N heapsort  Memory: 28kB
        ->  HashAggregate  (cost=68733.10..70317.43 rows=158432 width=130) (actual time=1420.539..1420.542 rows=8988 loops=1)
              Group Key: id, name, object_type, is_paid, company_name
              ->  Seq Scan on statistic_basic_view  (cost=0.00..24950.65 rows=761434 width=94) (actual time=0.023..249.851 rows=762118 loops=1)
                    Filter: (active AND visible AND (NOT removed) AND (NOT draft))
                    Rows Removed by Filter: 30047
Planning time: 0.665 ms
Execution time: 1420.545 ms

没有索引可以帮助您进行此查询

如果条件是有选择性的,中没有一个是有选择性的,,那么多的组使用索引,你就不能加快分组速度,也不能使用索引进行排序(因为之前有一个按不同标准分组的组)

您应该做的是在物化视图的顶部(或直接在基表的顶部)创建另一个预计算结果并定期刷新的视图。这会使您的数据稍微陈旧,但速度很快