如何使用kenxjs在psql中批量插入?

问题描述 投票:0回答:1

我搜索了很多东西,这是不建议使用的问题。

我正在尝试批量插入表中。

我的方法就是这样

knex('test_table').where({
  user: '[email protected]',
})
.then(result => {
  knex.transaction(trx => {
    Bluebird.map(result, data => {
      return trx('main_table')
        .insert(data.insert_row)
    }, { concurrency: 3 })
    .then(trx.commit);
  })
  .then(() => {
    console.log("done bulk insert")
  })
  .catch(err => console.error('bulk insert error: ', err))
})

如果列在文本或数字列中,但我有jsonb列,则可以使用此方法

所以我收到此错误

json类型的无效输入语法

所以我该如何解决这个问题?

node.js postgresql knex.js
1个回答
0
投票

像某些json列之类的声音在发送到数据库时没有字符串化的数据。

这也是插入多行的最慢的方法,因为您要对每个插入的行执行1个查询,并使用单个连接进行插入。

并发3仅使pg驱动程序在与其他所有查询通过同一事务发送给DB之前缓冲这2个查询。

这样的事情应该非常有效(没有测试运行代码,所以可能会有错误):

const rows = await knex('test_table').where({ user: '[email protected]' });
rows.forEach(row => {
  // make sure that json columns are actually json strings
  row.someColumnWithJson = JSON.stringify(row.someColumnWithJson);
});

await knex.transaction(async trx => {
  let i, j, temparray, chunk = 200;

  // insert rows in 200 row batches
  for (i = 0, j = rows.length; i < j; i += chunk) {
    rowsToInsert = rows.slice(i, i + chunk);
    await trx('main_table').insert(rowsToInsert);
  }
});

knex.batchInsert可能对您有用。

© www.soinside.com 2019 - 2024. All rights reserved.