fas*_*sth 7 sql postgresql performance
我创建一个43kk行的表,用值1..200填充它们.因此,通过表格传播的每个数字约为220k.
create table foo (id integer primary key, val bigint);
insert into foo
select i, random() * 200 from generate_series(1, 43000000) as i;
create index val_index on foo(val);
vacuum analyze foo;
explain analyze select id from foo where val = 55;
Run Code Online (Sandbox Code Playgroud)
结果:http: //explain.depesz.com/s/fdsm
我希望总运行时间<1s,是否可能?我有SSD,核心i5(1,8),4GB RAM.9,3 Postgres.
如果我使用Index Only扫描,它的工作速度非常快:
explain analyze select val from foo where val = 55;
Run Code Online (Sandbox Code Playgroud)
http://explain.depesz.com/s/7hm
但我需要选择id而不是val,所以Incex Only扫描不适合我的情况.
提前致谢!
附加信息:
SELECT relname, relpages, reltuples::numeric, pg_size_pretty(pg_table_size(oid))
FROM pg_class WHERE oid='foo'::regclass;
Run Code Online (Sandbox Code Playgroud)
结果:
"foo";236758;43800000;"1850 MB"
Run Code Online (Sandbox Code Playgroud)
配置:
"cpu_index_tuple_cost";"0.005";""
"cpu_operator_cost";"0.0025";""
"cpu_tuple_cost";"0.01";""
"effective_cache_size";"16384";"8kB"
"max_connections";"100";""
"max_stack_depth";"2048";"kB"
"random_page_cost";"4";""
"seq_page_cost";"1";""
"shared_buffers";"16384";"8kB"
"temp_buffers";"1024";"8kB"
"work_mem";"204800";"kB"
Run Code Online (Sandbox Code Playgroud)
我在这里得到了答案:http: //ask.use-the-index-luke.com/questions/235/postgresql-bitmap-heap-scan-on-index-is-very-slow-but-index-only-扫描是快速
诀窍是使用id和value的复合索引:
create index val_id_index on foo(val, id);
Run Code Online (Sandbox Code Playgroud)
因此,将使用仅索引扫描,但我现在可以选择ID.
select id from foo where val = 55;
Run Code Online (Sandbox Code Playgroud)
结果:
http://explain.depesz.com/s/nDt3
但这仅适用于版本9.2+的Postgres.如果您被迫使用以下版本,请尝试其他选项.
尽管您只查询了表的 0.5%,或者大约 10MB 的数据(在将近 2GB 的表中),但感兴趣的值均匀分布在整个表中。
您可以在您提供的第一个计划中看到它:
BitmapIndexScan 在 123.172 毫秒内完成BitmapHeapScan 需要 17055.046 毫秒。您可以尝试根据索引顺序对表进行聚类,这会将行放在同一页上。在我的 SATA 磁盘上,我有以下内容:
SET work_mem TO '300MB';
EXPLAIN (analyze,buffers) SELECT id FROM foo WHERE val = 55;
Bitmap Heap Scan on foo (...) (actual time=90.315..35091.665 rows=215022 loops=1)
Heap Blocks: exact=140489
Buffers: shared hit=20775 read=120306 written=24124
SET maintenance_work_mem TO '1GB';
CLUSTER foo USING val_index;
EXPLAIN (analyze,buffers) SELECT id FROM foo WHERE val = 55;
Bitmap Heap Scan on foo (...) (actual time=49.215..407.505 rows=215022 loops=1)
Heap Blocks: exact=1163
Buffers: shared read=1755
Run Code Online (Sandbox Code Playgroud)
当然,这是一次性操作,随着时间的推移,它会一点一点地变长。