如何解决是否可以将此PostgreSQL查询从50毫秒降低到几毫秒的数量级?
我有一个查询,希望尽快查询。是这样的:
explain analyze
select
*
from
rtsepezocoav_102999 av
join rtco_102097 c on
c.lo_id = av.co_id
where
av.ad_id = 335
and av.pe_id = 70
and av.se_id = 12
我得到以下计划:
Hash Join (cost=1238.88..3275.61 rows=40581 width=80) (actual time=10.341..47.707 rows=41238 loops=1)
Hash Cond: (av.co_id = c.lo_id)
-> Bitmap Heap Scan on rtsepezocoav_p_70_103719 av (cost=868.38..2798.54 rows=40581 width=68) (actual time=4.550..17.615 rows=41238 loops=1)
Recheck Cond: ((se_id = 12) AND (ad_id = 335))
Filter: (pe_id = 70)
Heap Blocks: exact=360
-> Bitmap Index Scan on rtsepezocoav_p_70_103719_se_id_ad_id_idx (cost=0.00..858.23 rows=40581 width=0) (actual time=4.450..4.450 rows=41238 loops=1)
Index Cond: ((se_id = 12) AND (ad_id = 335))
-> Hash (cost=204.67..204.67 rows=13267 width=12) (actual time=5.759..5.759 rows=13267 loops=1)
Buckets: 16384 Batches: 1 Memory Usage: 699kB
-> Seq Scan on rtco_102097 c (cost=0.00..204.67 rows=13267 width=12) (actual time=0.009..2.125 rows=13267 loops=1)
Planning Time: 0.515 ms
Execution Time: 51.100 ms
我猜这并不可怕。但是实际的查询会涉及更多+我将在不同的分片上并行运行此查询。因此,我非常专注于快速获得闪电。我有什么想念的吗,或者这仅仅是postgres的极限吗?将40K记录(rtsepezocoav_p_70_103719)与10K记录(rtco)结合起来似乎有点“慢”。
rtsepezocoav_p_70_103719在以下位置具有索引: (ad_id,pe_id,se_id) (ad_id,se_id) (co_id)
rtco的索引为(lo_id)
想到的第一件事,为什么它使用“位图堆扫描”而不是仅索引扫描?
当我这样做时:
explain analyze select 1 from rtsepezocoav_102999 av
我得到了仅索引扫描,它需要15毫秒(似乎也很长)。
我在使用Postgres 12。
解决方法
我认为您可以在co_id
上添加索引。您确实在where的所有ID中都有索引,但是在联接上,联接的一侧只有索引。
rtco has index on (lo_id)
rtsepezocoav_p_70_103719 has indexes on: (ad_id,pe_id,se_id) => this one should have index on co_id
在co_id上没有索引的情况下,最终在加入时rtsepezocoav_p_70_103719
表上进行了顺序扫描
提示,但老实说,我认为我确实在进行过早的优化...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。