快速数据加载
- 将您的数据转换为CSV格式。
- 创建一个临时表(如您所指出的,不含索引)。
- 执行COPY命令:
\COPY schema.temp_table FROM /tmp/data.csv WITH CSV
- 将数据插入到非临时表中。
- 创建索引。
- 设置适当的统计信息。
进一步的建议
对于大量数据:
- 将数据分割成子表。
- 按大部分SELECT语句将使用的列顺序插入。换句话说,尽量使物理模型与逻辑模型相一致。
- 调整配置设置。
- 创建一个CLUSTER索引(最重要的列在左侧)。例如:
CREATE UNIQUE INDEX measurement_001_stc_index
ON climate.measurement_001
USING btree
(station_id, taken, category_id);
ALTER TABLE climate.measurement_001 CLUSTER ON measurement_001_stc_index;
配置设置
在具有4GB RAM的计算机上,我进行了以下操作...
内核配置
告诉内核程序可以使用大量的共享内存:
sysctl -w kernel.shmmax=536870912
sysctl -p /etc/sysctl.conf
PostgreSQL配置
- 编辑
/etc/postgresql/8.4/main/postgresql.conf
文件并设置以下参数:shared_buffers = 1GB
temp_buffers = 32MB
work_mem = 32MB
maintenance_work_mem = 64MB
seq_page_cost = 1.0
random_page_cost = 2.0
cpu_index_tuple_cost = 0.001
effective_cache_size = 512MB
checkpoint_segments = 10
- 根据您的环境需要适当调整这些值以进行读/写优化。
- 重启PostgreSQL。
子表
例如,假设您有基于天气数据的不同类别。与其拥有单个庞大的表,将其分成几个表(每个类别一个)。
主表
CREATE TABLE climate.measurement
(
id bigserial NOT NULL,
taken date NOT NULL,
station_id integer NOT NULL,
amount numeric(8,2) NOT NULL,
flag character varying(1) NOT NULL,
category_id smallint NOT NULL,
CONSTRAINT measurement_pkey PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
子表
CREATE TABLE climate.measurement_001
(
CONSTRAINT measurement_001_pkey PRIMARY KEY (id),
CONSTRAINT measurement_001_category_id_ck CHECK (category_id = 1)
)
INHERITS (climate.measurement)
WITH (
OIDS=FALSE
);
表格统计信息
针对重要的列提高表格统计信息:
ALTER TABLE climate.measurement_001 ALTER COLUMN taken SET STATISTICS 1000;
ALTER TABLE climate.measurement_001 ALTER COLUMN station_id SET STATISTICS 1000;
别忘了在之后执行 VACUUM
和 ANALYSE
。