简体   繁体   English

Postgres 对索引列的简单选择太慢

[英]Postgres simple select on indexed column is too slow

I have a table like below.我有一张像下面这样的桌子。 I have a composite primary key.我有一个复合主键。 I have added index for secondary key as well.我也为辅助键添加了索引。 When I run the simple query, the performance is little slow.当我运行简单查询时,性能有点慢。 For example例如

CREATE TABLE item_ka_preview_relation (
    item_id varchar(40) NOT NULL,
    item_type varchar(40) NOT NULL,
    ka_id varchar(40) NOT NULL,
    sequence_number int4 NULL,
    creation_date timestamp NOT NULL,
    last_modified_date timestamp NOT NULL,
    pp_association_by_rule bool NULL DEFAULT false,
    CONSTRAINT item_ka_relation_preview_pkey PRIMARY KEY (item_id,ka_id),
    CONSTRAINT item_ka_relation_preview_item_type_fkey FOREIGN KEY (item_type) REFERENCES item_type(id)
);
CREATE INDEX idx_itemkarelation_preview_itemtype ON item_ka_preview_relation (item_type DESC) ;
CREATE INDEX idx_itemkarelation_preview_kaid ON item_ka_preview_relation (ka_id DESC) ;

The table has 1 million rows.该表有 100 万行。 The below query fetches some 80k rows.下面的查询获取了一些 80k 行。

explain analyze
select * from item_ka_preview_relation ik where ik.ka_id in ('3800042','69104128','2300023','3800019','5400264','3800039')

The analysis is like this分析是这样的

Bitmap Heap Scan on item_ka_preview_relation ik  (cost=5867.27..20251.85 rows=255062 width=54) (actual time=23.029..115.286 rows=250064 loops=1)
  Recheck Cond: ((ka_id)::text = ANY ('{3800042,69104128,2300023,3800019,5400264,3800039}'::text[]))
  Heap Blocks: exact=8490
  ->  Bitmap Index Scan on idx_itemkarelation_preview_kaid  (cost=0.00..5803.50 rows=255062 width=0) (actual time=21.741..21.742 rows=250064 loops=1)
        Index Cond: ((ka_id)::text = ANY ('{3800042,69104128,2300023,3800019,5400264,3800039}'::text[]))
Planning time: 0.328 ms
Execution time: 160.677 ms

Though I have indexed ka_id column, still query uses Bitmap Heap Scan and response is slow虽然我已经索引了 ka_id 列,但查询仍然使用位图堆扫描并且响应很慢

Any idea to improve this.任何改善这一点的想法。 I am using postgres 9.6.1我正在使用 postgres 9.6.1

The bitmap index scan actually makes the query faster .位图索引扫描实际上使查询更快 It is chosen because there are many result rows.选择它是因为有很多结果行。

You can test by setting enable_seqscan and enable_bitmapscan to off and checking if that improves the execution time.您可以通过将enable_seqscanenable_bitmapscan设置为off并检查是否可以提高执行时间来进行测试。

If it does, maybe you should tune effective_cache_size higher and/or random_page_cost lower so that it matches your actual hardware.如果是的话,也许你应该调整effective_cache_size更高和/或random_page_cost降低,使之与实际硬件相匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM