如何提高 PostgreSQL 在 INSERT 上的性能?

Gol*_*den 5 javascript postgresql performance node.js sql-insert

我编写了一个 Node.js 应用程序,它将大量记录写入 PostgreSQL 9.6 数据库。不幸的是,感觉很慢。为了能够进行测试,我创建了一个简短但完整的程序来重现该场景:

'use strict';

const async = require('async'),
      pg = require('pg'),
      uuid = require('uuidv4');

const pool = new pg.Pool({
  protocol: 'pg',
  user: 'golo',
  host: 'localhost',
  port: 5432,
  database: 'golo'
});

const records = [];

for (let i = 0; i < 10000; i++) {
  records.push({ id: uuid(), revision: i, data: { foo: 'bar', bar: 'baz' }, flag: true });
}

pool.connect((err, database, close) => {
  if (err) {
    /* eslint-disable no-console */
    return console.log(err);
    /* eslint-enable no-console */
  }

  database.query(`
    CREATE TABLE IF NOT EXISTS "foo" (
      "position" bigserial NOT NULL,
      "id" uuid NOT NULL,
      "revision" integer NOT NULL,
      "data" jsonb NOT NULL,
      "flag" boolean NOT NULL,

      CONSTRAINT "foo_pk" PRIMARY KEY("position"),
      CONSTRAINT "foo_index_id_revision" UNIQUE ("id", "revision")
    );
  `, errQuery => {
    if (errQuery) {
      /* eslint-disable no-console */
      return console.log(errQuery);
      /* eslint-enable no-console */
    }

    async.series({
      beginTransaction (done) {
        /* eslint-disable no-console */
        console.time('foo');
        /* eslint-enable no-console */
        database.query('BEGIN', done);
      },
      saveRecords (done) {
        async.eachSeries(records, (record, doneEach) => {
          database.query({
            name: 'save',
            text: `
              INSERT INTO "foo"
                ("id", "revision", "data", "flag")
              VALUES
                ($1, $2, $3, $4) RETURNING position;
            `,
            values: [ record.id, record.revision, record.data, record.flag ]
          }, (errQuery2, result) => {
            if (errQuery2) {
              return doneEach(errQuery2);
            }

            record.position = Number(result.rows[0].position);
            doneEach(null);
          });
        }, done);
      },
      commitTransaction (done) {
        database.query('COMMIT', done);
      }
    }, errSeries => {
      /* eslint-disable no-console */
      console.timeEnd('foo');
      /* eslint-enable no-console */
      if (errSeries) {
        return database.query('ROLLBACK', errRollback => {
          close();

          if (errRollback) {
            /* eslint-disable no-console */
            return console.log(errRollback);
            /* eslint-enable no-console */
          }
          /* eslint-disable no-console */
          console.log(errSeries);
          /* eslint-enable no-console */
        });
      }

      close();
      /* eslint-disable no-console */
      console.log('Done!');
      /* eslint-enable no-console */
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

插入 10,000 行的性能为 2.5 秒。这还不错,但也不是很好。我可以做什么来提高速度?

到目前为止我的一些想法:

  • 使用准备好的语句。正如您所看到的,我已经这样做了,这将速度提高了约 30%。
  • 使用单个命令一次插入多行INSERT。不幸的是,这是不可能的,因为实际上,需要写入的记录数量因调用而异,并且不同数量的参数使得不可能使用准备好的语句。
  • 使用COPY而不是INSERT:我不能使用它,因为这是在运行时发生的,而不是在初始化时发生的。
  • 使用text而不是jsonb:没有改变任何东西。
  • 使用json而不是jsonb:也没有改变任何东西。

关于现实中发生的数据的更多注释:

  • 不一定revision会增加。这只是一个数字。
  • 情况flag并不总是如此true,但也可以true如此false
  • 当然,该data字段也包含不同的数据。

所以最终归结为:

  • 有哪些可能性可以显着加快多个单一调用的速度INSERT

vit*_*y-t 4

使用单个 INSERT 命令一次插入多行。不幸的是,这是不可能的,因为实际上,需要写入的记录数量因调用而异,并且不同数量的参数使得不可能使用准备好的语句。

这是正确的答案,后面是无效的反驳。

您可以在循环中生成多行插入,每个查询大约 1000 - 10,000 条记录,具体取决于记录的大小。

您根本不需要为此准备好声明。

请参阅我写的关于相同问题的这篇文章:性能提升

阅读本文后,我的代码能够在50 毫秒内插入 10,000 条记录。

一个相关的问题:Multi-row insert with pg-promise