【问题标题】:How to insert 10 million rows into MySQL database with Knex.js?如何使用 Knex.js 将 1000 万行插入 MySQL 数据库?
【发布时间】:2019-10-07 02:06:03
【问题描述】:

我正在尝试使用 Knex.js 将 10M+ 行插入 MySQL 数据库。有没有办法使用 for 循环插入长度为 10000 的数组(这似乎是我能够插入的最大大小 - 任何大于该大小的东西都会得到“错误:ER_NET_PACKET_TOO_LARGE:得到的数据包大于 'max_allowed_pa​​cket' 字节”)。

我尝试使用承诺链,但链会很长,无法容纳 1000 万条记录。

exports.seed = (knex) => {
  // Deletes ALL existing entries
  return knex('books').del()
    .then(() => {
      const fakeBooks = [];
      for (let i = 0; i < 10000; i += 1) {
        fakeBooks.push(createFakeBooks());
      }
      return knex('books').insert(fakeBooks)
        .then(() => {
          const fakeBooks1 = [];
          for (let i = 0; i < 10000; i += 1) {
            fakeBooks1.push(createFakeBooks());
          }
          return knex('books').insert(fakeBooks1)
            .then(() => {
              const fakeBooks2 = [];
              for (let i = 0; i < 10000; i += 1) {
                fakeBooks2.push(createFakeBooks());
              }
...

【问题讨论】:

  • 在.then() 中调用自身直到数组为空的递归函数怎么样?

标签: javascript mysql node.js knex.js


【解决方案1】:

您可以使用https://knexjs.org/#Utility-BatchInsert 将大量行插入数据库。

await knex.batchInsert('books', create10MFakeBooks(), 5000)

但是,您可能希望以较小的批次实际创建这些书籍,以防止使用千兆字节的内存。所以 MikaS 的回答是有效的,只要使用 async / await 就可以了,写起来很简单。

我不会将 knex 用于此类工作,而是使用原始 SQL。

【讨论】:

    【解决方案2】:

    如果您使用 async 和 await 并放弃 thens,会更容易。然后可以这样写:

    exports.seed = async (knex) => {
        await knex('books').del();
    
        let fakeBooks = [];
        for (let i = 1; i <= 10000000; i += 1) {
          fakeBooks.push(createFakeBooks());
    
          if (i % 1000 === 0) {
            await knex('books').insert(fakeBooks);
            fakeBooks = [];
          }
        }
    };
    

    await 将在函数继续之前完成承诺,而不会阻塞线程。该循环将运行一千万次,每 1000 行插入一次数据库。您可以将其更改为 10000 行,但您最好使用 1000 来确定。

    我自己只尝试了一百万行,因为插入一千万行花费了太多时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-13
      • 1970-01-01
      • 1970-01-01
      • 2015-09-04
      • 1970-01-01
      • 2022-11-12
      • 1970-01-01
      相关资源
      最近更新 更多