postgresql大批量數據導入方法


一直沒有好好關注這個功能,昨天看了一下,數據庫插入有瓶頸,今天研究了一下:

 

主要有以下方案:

 

1.使用copy從文件導入

    copy table_001(a, b, "f", d, c, "e") from 'd:/data1.txt' (delimiter ',');

   速度極快:

     不帶索引:

        查詢成功: 共計 69971 行受到影響,耗時: 4351 毫秒(ms)。

       查詢成功: 共計 69971 行受到影響,耗時: 4971 毫秒(ms)。

    帶索引:

        查詢成功: 共計 69971 行受到影響,耗時: 15582 毫秒(ms)。

 

        查詢成功: 共計 69971 行受到影響,耗時: 12833 毫秒(ms)。

 

   需要做的就是定時生成臨時數據文件,並不斷的切換,清除。

 

2. 使用multi-insert格式的sql

    類似: insert into test values('asd', 'adewf', 12),('asd2', 'adewf2', 12);

   

   目前采用此方案,改動不大,只是修改了一下 sql 的格式,目前滿足要求(大約25萬條記錄每分鍾,合4200每秒),所以暫時采用它。

 

3. 關閉自動提交,使用insert或者multi-insert格式sql,插入大量數據

   目前未測試,不過此方案效果具網上介紹應該也不錯的。

 

4. 采用臨時表

    這個方案備選,臨時表為了加快速度,應該不加任何索引與日志,數據穩定后再加索引與限制,壓縮數據,進行vacuum 等數據優化,這需要與分表結合使用比較好。

 

5. 調整數據庫參數,這個是提高數據庫整體性能的

   網上介紹這幾個優化參數:shared_buffers、work_mem、effective_cache_size、maintence_work_mem 

 

這些可以配置起來使用,詳細請參考 postgresql-9.2-A4.pdf  中的 Chapter 14. Performance Tips。

 

 

One might need to insert a large amount of data when first populating a database. This section contains

some suggestions on how to make this process as efficient as possible.

14.4.1. Disable Autocommit

When using multiple INSERTs, turn off autocommit and just do one commit at the end. (In plain

SQL, this means issuing BEGIN at the start and COMMIT at the end. Some client libraries might do this

behind your back, in which case you need to make sure the library does it when you want it done.) If

you allow each insertion to be committed separately, PostgreSQL is doing a lot of work for each row

that is added. An additional benefit of doing all insertions in one transaction is that if the insertion of

one row were to fail then the insertion of all rows inserted up to that point would be rolled back, so

you won’t be stuck with partially loaded data.

14.4.2. Use COPY

Use COPY to load all the rows in one command, instead of using a series of INSERT commands. The

COPY command is optimized for loading large numbers of rows; it is less flexible than INSERT, but

incurs significantly less overhead for large data loads. Since COPY is a single command, there is no

need to disable autocommit if you use this method to populate a table.

If you cannot use COPY, it might help to use PREPARE to create a prepared INSERT statement, and

then use EXECUTE as many times as required. This avoids some of the overhead of repeatedly parsing

and planning INSERT. Different interfaces provide this facility in different ways; look for “prepared

statements” in the interface documentation.

Note that loading a large number of rows using COPY is almost always faster than using INSERT, even

if PREPARE is used and multiple insertions are batched into a single transaction.

COPY is fastest when used within the same transaction as an earlier CREATE TABLE or TRUNCATE

command. In such cases no WAL needs to be written, because in case of an error, the files containing the newly loaded data will be removed anyway. However, this consideration only applies when

wal_level is minimal as all commands must write WAL otherwise.

367

 

14.4.3. Remove Indexes

If you are loading a freshly created table, the fastest method is to create the table, bulk load the table’s

data using COPY, then create any indexes needed for the table. Creating an index on pre-existing data

is quicker than updating it incrementally as each row is loaded.

If you are adding large amounts of data to an existing table, it might be a win to drop the indexes,

load the table, and then recreate the indexes. Of course, the database performance for other users

might suffer during the time the indexes are missing. One should also think twice before dropping a

unique index, since the error checking afforded by the unique constraint will be lost while the index

is missing.

14.4.4. Remove Foreign Key Constraints

Just as with indexes, a foreign key constraint can be checked “in bulk” more efficiently than row-byrow. So it might be useful to drop foreign key constraints, load data, and re-create the constraints.

Again, there is a trade-off between data load speed and loss of error checking while the constraint is

missing.

What’s more, when you load data into a table with existing foreign key constraints, each new row

requires an entry in the server’s list of pending trigger events (since it is the firing of a trigger that

checks the row’s foreign key constraint). Loading many millions of rows can cause the trigger event

queue to overflow available memory, leading to intolerable swapping or even outright failure of the

command. Therefore it may be necessary, not just desirable, to drop and re-apply foreign keys when

loading large amounts of data. If temporarily removing the constraint isn’t acceptable, the only other

recourse may be to split up the load operation into smaller transactions.

14.4.5. Increase maintenance_work_mem

Temporarily increasing the maintenance_work_mem configuration variable when loading large

amounts of data can lead to improved performance. This will help to speed up CREATE INDEX

commands and ALTER TABLE ADD FOREIGN KEY commands. It won’t do much for COPY itself, so

this advice is only useful when you are using one or both of the above techniques.

14.4.6. Increase checkpoint_segments

Temporarily increasing the checkpoint_segments configuration variable can also make large data

loads faster. This is because loading a large amount of data into PostgreSQL will cause checkpoints

to occur more often than the normal checkpoint frequency (specified by the checkpoint_timeout

configuration variable). Whenever a checkpoint occurs, all dirty pages must be flushed to disk. By

increasing checkpoint_segments temporarily during bulk data loads, the number of checkpoints

that are required can be reduced.

14.4.7. Disable WAL Archival and Streaming Replication

When loading large amounts of data into an installation that uses WAL archiving or streaming replication, it might be faster to take a new base backup after the load has completed than to process

a large amount of incremental WAL data. To prevent incremental WAL logging while loading, disable archiving and streaming replication, by setting wal_level to minimal, archive_mode to off, and

max_wal_senders to zero. But note that changing these settings requires a server restart.

Aside from avoiding the time for the archiver or WAL sender to process the WAL data, doing this

will actually make certain commands faster, because they are designed not to write WAL at all if

wal_level is minimal. (They can guarantee crash safety more cheaply by doing an fsync at the

end than by writing WAL.) This applies to the following commands:

• CREATE TABLE AS SELECT

• CREATE INDEX (and variants such as ALTER TABLE ADD PRIMARY KEY)

• ALTER TABLE SET TABLESPACE

• CLUSTER

• COPY FROM, when the target table has been created or truncated earlier in the same transaction

14.4.8. Run ANALYZE Afterwards

Whenever you have significantly altered the distribution of data within a table, running ANALYZE

is strongly recommended. This includes bulk loading large amounts of data into the table. Running

ANALYZE (or VACUUM ANALYZE) ensures that the planner has up-to-date statistics about the table.

With no statistics or obsolete statistics, the planner might make poor decisions during query planning,

leading to poor performance on any tables with inaccurate or nonexistent statistics. Note that if the

autovacuum daemon is enabled, it might run ANALYZE automatically; see Section 23.1.3 and Section

23.1.6 for more information.


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM