简体   繁体   中英

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. The below query fetches some 80k rows.

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

Any idea to improve this. I am using 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.

If it does, maybe you should tune effective_cache_size higher and/or random_page_cost lower so that it matches your actual hardware.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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