一直没有好好关注这个功能,昨天看了一下,数据库插入有瓶颈,今天研究了一下:

主要有以下方案:

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.

pg批量插入_postgresql大批量数据导入方法相关推荐

  1. pg批量插入_PostgreSQL实现批量插入、更新与合并操作的方法

    前言 就在 2019 年 1 月份微软收购了 PostgreSQL 数据库的初创公司 CitusData, 在云数据库方面可以增强与 AWS 的竟争.AWS 的 RDS 两大开源数据库就是 MySQL ...

  2. vb.net datagridview数据批量导入sql_导入:Java实现大批量数据导入导出(100W以上)

    阅读文本大概需要3分钟. 来源:https://www.cnblogs.com/barrywxx/p/10700221.html 最近业务方有一个需求,需要一次导入超过100万数据到系统数据库.可能大 ...

  3. 关于使用mybatis-plus进行大批量数据导入

    一.背景 项目中经常会遇到需要对数据库进行大批量数据导入的问题,就目前java应用常用的springboot+mybatis-plus架构而言,在大批量数据导入时不是很清晰,本文做简单分析及解决,希望 ...

  4. java大批量数据导入(MySQL)

    © 版权声明:本文为博主原创文章,转载请注明出处 最近同事碰到大批量数据导入问题,因此也关注了一下.大批量数据导入主要存在两点问题:内存溢出和导入速率慢. 内存溢出:将文件中的数据全部取出放在集合中, ...

  5. 教你两种数据库覆盖式数据导入方法

    摘要:本文主要介绍如何在数据库中完成覆盖式数据导入的方法. 前言 众所周知,数据库中INSERT INTO语法是append方式的插入,而最近在处理一些客户数据导入场景时,经常遇到需要覆盖式导入的情况 ...

  6. 【SpringBoot项目中使用Mybatis批量插入百万条数据】

    SpringBoot项目中使用Mybatis批量插入百万条数据 话不多说,直接上代码,测试原生批处理的效率 开始测试 背景:因为一些业务问题,需要做多数据源,多库批量查询.插入操作,所以就研究了一下. ...

  7. 公司新来个同事,MyBatis批量插入10w条数据仅用2秒,拍案叫绝!

    批量插入功能是我们日常工作中比较常见的业务功能之一,今天咱们来一个 MyBatis 批量插入的汇总篇,同时对 3 种实现方法做一个性能测试,以及相应的原理分析. 先来简单说一下 3 种批量插入功能分别 ...

  8. mysql命令行批量添加数据_mysql命令行批量插入100条数据命令

    先介绍一个关键字的使用: delimiter 定好结束符为"$$",(定义的时候需要加上一个空格) 然后最后又定义为";", MYSQL的默认结束符为" ...

  9. mysql一次读取500条数据_mysql批量插入500条数据

    表格结构如下 需求name和password字段,生成如下格式: 总共批量生成500个. 解决思路:可以用mysql 存储过程 如果linux环境下可以用shell 我们先测试第一种,用存储过程.DE ...

最新文章

  1. mysql 编码分层_【平台开发】— 5.后端:代码分层
  2. python3精要(51)--抛出异常与自定义异常
  3. hive复合数据类型之map
  4. VideoJS - HTML5免费视频播放器源码 支持多格式
  5. 最小方差问题---------------给你出道题
  6. 给 layui upload 带每个文件的进度条, .net 后台代码
  7. 为什么鸟哥说 int 再怎么随机也申请不到奇数地址
  8. iOS:xxx referenced from
  9. 寄存器的七种寻址方式
  10. 无心剑英译许巍《温暖》
  11. laravel数据填充seeder
  12. Typora如何把图片上传到图床smms.app
  13. python xlwt表格写入操作
  14. csgo 放置机器人_一键跑图!极为方便的CSGO跑图工具(附2020年5月28日更新)
  15. python读txt的各种操作(逗号,tab键,空格隔开,转成list)
  16. Ubuntu中使用apt-get时无法搜索软件的解决方法
  17. Excel如何快速录入大写数字序列
  18. Docker--Dockerfile镜像
  19. [杂记]CodeBlocks下载、安装及设置
  20. 论文阅读笔记(二)——牛的人脸识别,能做到吗?

热门文章

  1. 各种下载文件方式总结
  2. 十、RabbitMQ发布确认高级
  3. c语言中1 lt lt 10什么意思,卡西欧lt1和lt3是什么意思
  4. 速领电商:怎么制作视频短片
  5. c语言wb是标识符,C语言文件 "w+"与"wb+"区别
  6. python处理excel表格中合并的行
  7. 浏览器点击链接打开指定APP详解
  8. 【Halcon】线阵相机标定
  9. 关于m3u8格式的视频文件ts转mp4下载和key加密问题
  10. 实现斗地主牌的大小顺序,实现分发牌的顺序,每个人手中的牌按照大小排序