运维笔记 -- postgresql查询优化一例

场景描述:

      测试反馈Django项目中,某条通过ORM查询的请求,耗时较长,单次查询响应时间接近2分钟,严重影响系统交互体验。

处理方式:

  基本思路:分析ORM查询写法,转换成SQL语句,分析查询条件、字段类型,创建相应索引,验证查询效率。

--分析ORM查询写法:

price_qty_data_li = TestStatistics.objects.filter(aa_code=aa_code,bb_code=bb_code,time_period__istartswith=str(year)).values('time_period').annotate(all_price=Sum('total_price'),all_number=Sum("qty"))

--转换成SQL语句

select Sum(total_price), Sum(qty) 
   from test_statistics where aa_code='012345' and bb_code='678910' and time_period='202002' 
       group by time_period;

--分析查询条件、字段类型

   查询条件基于三个字段查询,aa_code,bb_code,time_period,可以考虑创建组合索引。

--创建相应索引

create index idx_test_statistics_un_1 on test_statistics using btree(aa_code,bb_code,time_period);

---查看创建的索引

select * from pg_indexes where tablename='test_statistics';

--验证查询效率

--OK

    

 

posted @ 2020-04-24 11:07  hello-Jesson  阅读(333)  评论(0编辑  收藏  举报