【问题标题】:Postgresql slow query on two indexes combinedPostgresql对两个索引组合的慢查询
【发布时间】:2018-02-02 23:50:06
【问题描述】:

我有一个包含大约 1 亿条记录和以下索引的表:

 Column        |           Type           | Modifiers | Storage  |
---------------------+--------------------------+------------------------------------------------------------+----------+--------------+-------------
 id            | integer                  | ... pk ...| plain    |
 url           | character varying(500)   | not null  | extended |
 description   | text                     |           | extended |
 domain_id     | integer                  |           | plain    |
 index_status  | integer                  | not null  | plain    |

索引:

  • “mytable_pkey”主键,btree (id)
  • "mytable_url_key" 唯一约束,btree (url)
  • "mytable_662cbf12" btree (domain_id)
  • "mytable_id_idx" btree (id) WHERE index_status = 0

我首先创建了index_status=0 索引,因为我想使用以下命令查询表:

select * 
from mytable 
where index_status = 0 
limit 1000;

它工作得很好,但现在我也想这样查询它:

select * 
from mytable 
where index_status = 0 and domain_id = 233 
limit 1000;

如您所见,我现在正在使用两个索引查询我的数据库,它运行良好,因为我与 domain_id 相关的记录在 50,000 附近,因此查询它们的速度非常快(在 @987654327 附近@)。

但现在我有与 domain_id 相关的记录,大约有 3,000,000 记录,这需要大约 10 分钟。

如果两个字段都被索引了怎么办?我应该怎么做才能加快这种查询?我应该创建一个新索引吗?

【问题讨论】:

    标签: sql postgresql indexing


    【解决方案1】:

    您可以在多个列上创建过滤索引:

    create index idx_mytable_3 on mytable(domain_id, id) where index_status = 0;
    

    你可以用这个替换mytable_id_idx

    注意:使用 limit 而不使用 order by 是可疑的。如果您想要id 顺序的结果,则应明确包含order by id

    【讨论】:

    • 我查询它们并更改index_status,以便下次我得到新的。
    猜你喜欢
    • 2015-02-06
    • 1970-01-01
    • 2021-09-19
    • 2020-05-03
    • 1970-01-01
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多