Postgres 索引问题

如何解决Postgres 索引问题

我们现在正在开发一个平台,我在优化我们的一个查询时遇到了困难,它实际上是一个视图。

在解释查询时,会对我的 user_role 表执行全表扫描。 视图背后的查询看起来像我在下面发布的内容(我使用 * 代替不同表的不同列,只是为了展示我的问题)。所有结果均基于该简化查询。

SELECT t.*
FROM task t
         LEFT JOIN project p ON t.project_id = p.id
         LEFT JOIN company comp ON comp.id = p.company_id
         LEFT JOIN company_users cu ON cu.companies_id = comp.id
         LEFT JOIN user_table u ON u.email= cu.users_email
         LEFT JOIN user_role role ON u.email= role.user_email
WHERE lower(t.type) = 'project'
  AND t.project_id IS NOT NULL
  AND role.role::text in ('SOME_ROLE_1','SOME_ROLE_2')

基本上这个查询可以像这样运行。如果我解释查询,它会使用我所有的索引,很好! 但是.. 一旦我开始添加额外的 where 子句,问题就出现了。我只是添加这个:

  and u.email = 'my@email.com'
  and comp.id = 4
  and p.id = 3

突然对表 company_usersuser_role 执行全表扫描。表 project 上没有。

完整的查询计划是:

Nested Loop  (cost=0.98..22.59 rows=1 width=97) (actual time=0.115..4.448 rows=189 loops=1)                                                                                 
  ->  Nested Loop  (cost=0.84..22.02 rows=1 width=632) (actual time=0.099..3.091 rows=252 loops=1)                                                                          
        ->  Nested Loop  (cost=0.70..20.10 rows=1 width=613) (actual time=0.082..1.774 rows=252 loops=1)                                                                    
              ->  Nested Loop  (cost=0.56..19.81 rows=1 width=621) (actual time=0.068..0.919 rows=252 loops=1)                                                              
                    ->  Nested Loop  (cost=0.43..19.62 rows=1 width=101) (actual time=0.058..0.504 rows=63 loops=1)                                                         
                          ->  Index Scan using task_project_id_index on task t  (cost=0.28..11.43 rows=1 width=97) (actual time=0.041..0.199 rows=63 loops=1)               
                                Index Cond: (project_id IS NOT NULL)                                                                                                        
                                Filter: (lower((type)::text) = 'project'::text)                                                                                             
                          ->  Index Scan using project_id_uindex on project p  (cost=0.15..8.17 rows=1 width=8) (actual time=0.003..0.003 rows=1 loops=63)                  
                                Index Cond: (id = t.project_id)                                                                                                             
                    ->  Index Scan using company_users_companies_id_index on company_users cu  (cost=0.14..0.17 rows=1 width=520) (actual time=0.002..0.004 rows=4 loops=63)
                          Index Cond: (companies_id = p.company_id)                                                                                                         
              ->  Index Only Scan using company_id_index on company comp  (cost=0.14..0.29 rows=1 width=4) (actual time=0.002..0.002 rows=1 loops=252)                      
                    Index Cond: (id = p.company_id)                                                                                                                         
                    Heap Fetches: 252                                                                                                                                       
        ->  Index Only Scan using user_table_email_index on user_table u  (cost=0.14..1.81 rows=1 width=19) (actual time=0.004..0.004 rows=1 loops=252)                     
              Index Cond: (email = (cu.users_email)::text)                                                                                                                  
              Heap Fetches: 252                                                                                                                                             
  ->  Index Scan using user_role_user_email_index on user_role role  (cost=0.14..0.56 rows=1 width=516) (actual time=0.004..0.004 rows=1 loops=252)                         
        Index Cond: ((user_email)::text = (u.email)::text)                                                                                                                  
        Filter: ((role)::text = ANY ('{COMPANY_ADMIN,COMPANY_USER}'::text[]))                                                                                               
        Rows Removed by Filter: 0                                                                                                                                           
Planning time: 2.581 ms                                                                                                                                                     
Execution time: 4.630 ms                                                                                                                                                    

特别是对 company_users 的解释是:

SEQ_SCAN (Seq Scan)  table: company_users;  1   1.44    0.0 Parent Relationship = Inner;
Parallel Aware = false;
Alias = cu;
Plan Width = 520;
Filter = ((companies_id = 4) AND ((users_email)::text = 'my@email.com'::text));

但是我已经在 company_users 表上创建了一个索引:create index if not exists company_users_users_email_companies_id_index on company_users (users_email,companies_id);

user_role 表的计数相同。 解释是

SEQ_SCAN (Seq Scan)  table: user_role;  1   1.45    0.0 Parent Relationship = Inner;
Parallel Aware = false;
Alias = role;
Plan Width = 516;
Filter = (((role)::text = ANY ('{SOME_ROLE_1,SOME_ROLE_2}'::text[])) AND ((user_email)::text = 'my@email.com'::text));

因此对于 user_role,我还在列 roleuser_email 上建立了索引:create index if not exists user_role_role_user_email_index on user_role (role,user_email);

没想到它会改变任何东西,但无论如何我确实尝试调整查询以在 where 类中只包含一个角色,并且还尝试使用 OR 语句而不是 IN,但一切都没有区别!

对我来说奇怪的是,如果没有我额外的 3 个过滤器,它就可以完美运行,一旦我添加它们,它就不起作用,但我确实为解释中提到的字段创建了索引...>

我们在其他一些查询中使用了完全相同的算法,并且它们在这两个领域都遇到了同样的问题...... 所以最大的问题是,如何进一步改进我的查询并使其使用索引而不是全表扫描?

解决方法

创建索引并计算统计数据:

CREATE INDEX ON task (lower(type)) WHERE project_id IS NOT NULL;

ANALYZE task;

这应该会提高估计值,以便 PostgreSQL 选择更好的连接策略。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-