如何使用Nodejs从文本文件中读取数据并插入到PostgreSQL中?



这个文本文件包含超过500k行,我想使用nodejs读取并插入到PostgreSQL表中。这些空格也应该像这样读取和保存。

我写了这样的脚本,它正在工作,数据也被插入到表中,但它需要非常多的时间,如10分钟,只有2万行。

const readTextFile = async () => {
const File = await fs.readFileSync('data.txt', 'utf-8');
let arr = File.split("|");
let modified = [];
let temp = [];
for (let i = 0; i < arr.length; i++) {
if (i % 10 === 0) {
modified.push([...temp]);
temp = [];
temp.push(arr[i].replace('x00rn', ''));
} else {
temp.push(arr[i]);
}
}
console.log("modified", modified.length);
for (let i = 0; i < modified.length; i++) {
await insertValuesToDB(modified[i]);
}
}
const insertValuesToDB = async (values) => {
try {
const text = `INSERT INTO requirement(container, module, mod_devdate, part_no, qty, tapdate, tap_qty, taptime, sup_cd, namc_id) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`;
const result = await client.query(text, values);
console.log("result", result);
} catch (e) {
console.log("ERROR", e);
}
}

如果可能的话-我认为一个简单的copy将是最快的解决方案。例如:

如何将CSV文件数据导入PostgreSQL表

也许这是不可能的,因为必须进行数据清理。

另一种可能是,将插入封装在事务中。也许可以"批处理",以降低内存消耗。

最小的例子:

await client.query('BEGIN')
for (let i = 0; i < modified.length; i++) {
await insertValuesToDB(modified[i]);
}
await client.query('COMMIT')

见:https://node-postgres.com/features/transactions

for (let i = 0; i < modified.length; i++) {
await insertValuesToDB(modified[i]);
}

我认为不建议在这个函数中插入数据到数据库时循环这个。我建议在一个查询中完成所有操作。当我在mysql中遇到这种问题时,我这样解决它:

INSERT INTO EXAMPLE (
name,
surname,
email)
VALUES
(
'1name',
'1surname',
'1email'
),
(
'2name',
'2surname',
'2email'
),
(
'3name',
'3surname',
'3email'
);

这是查询最终应该看起来的样子。

let data = [{name: '1name', surname: '1surname', email: '1email'},{name: '2name', surname: '2surname', email: '2email'},{name: '3name', surname: '3surname', email: '3email'}]
let QueryInsert = data.length > 0 ? 'INSERT INTO EXAMPLE (name,surname,email) VALUES ' : '';
data.forEach((el) => {
QueryInsert = QueryInsert + `(${el.name},${el.surname},${el.email}),`
})
QueryInsert = QueryInsert.substring(0,QueryInsert.length-1);
console.log(QueryInsert)

最新更新