快速数据加载
- 将您的数据转换为 CSV。
- 创建一个临时表(如您所述,没有索引)。
- 执行复制命令:
\COPY schema.temp_table FROM /tmp/data.csv WITH CSV
- 将数据插入到非临时表中。
- 创建索引。
- 设置适当的统计数据。
进一步的建议
对于大量数据:
- 将数据拆分为子表。
SELECT
按照大多数语句将使用的列的顺序插入它。换句话说,尝试将物理模型与逻辑模型对齐。
- 调整您的配置设置。
- 创建一个
CLUSTER
索引(左侧最重要的列)。例如:
创建唯一索引 measure_001_stc_index
ONclimate.measurement_001
使用 btree
(station_id, 采取, category_id);
ALTER TABLEclimate.measurement_001 CLUSTER ON measure_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
临时缓冲区 = 32MB
工作内存 = 32MB
维护工作内存 = 64MB
seq_page_cost = 1.0
random_page_cost = 2.0
cpu_index_tuple_cost = 0.001
有效缓存大小 = 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
(
-- Inherited from table climate.measurement_001: id bigint NOT NULL DEFAULT nextval('climate.measurement_id_seq'::regclass),
-- Inherited from table climate.measurement_001: taken date NOT NULL,
-- Inherited from table climate.measurement_001: station_id integer NOT NULL,
-- Inherited from table climate.measurement_001: amount numeric(8,2) NOT NULL,
-- Inherited from table climate.measurement_001: flag character varying(1) NOT NULL,
-- Inherited from table climate.measurement_001: category_id smallint NOT NULL,
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
之后。