Node.js 从文件中加载100万条记录并保存到PSQL数据库
我有一个包含100万条记录的文件,其中我必须将一条记录逐一传递给elastic search,并将结果数据保存到数据库中。 但问题是,这样做需要很长时间,因为记录一个接一个地流到elasticsearch,然后它将数据保存到PSQL数据库中。 我想要一些建议,我可以如何改进这一点,或者应该使用一些其他工具 现在,我正在将Nodejs与一些软件包一起使用: 我在nodejs应用程序中上传该文件,并使用Node.js 从文件中加载100万条记录并保存到PSQL数据库,node.js,apache-spark,stream,Node.js,Apache Spark,Stream,我有一个包含100万条记录的文件,其中我必须将一条记录逐一传递给elastic search,并将结果数据保存到数据库中。 但问题是,这样做需要很长时间,因为记录一个接一个地流到elasticsearch,然后它将数据保存到PSQL数据库中。 我想要一些建议,我可以如何改进这一点,或者应该使用一些其他工具 现在,我正在将Nodejs与一些软件包一起使用: 我在nodejs应用程序中上传该文件,并使用 const csv=require('csvtojson') 我用 用于读取json并使用流通过
const csv=require('csvtojson')
我用
用于读取json并使用流通过这些包解析它,因为文件太大。
我使用这个代码
const fileStream = fs.createReadStream(this.fileName);
const jsonStream = StreamArray.withParser();
const incomingThis = this;
const processingStream = new Writable({
write({key, value}, encoding, callback) {
incomingThis.recordParser(value, (val, data) => { // pass the data to elasticsearch to get search data
incomingThis.processQueue(data); // save the data to the PSQL database
callback();
});
},
//Don't skip this, as we need to operate with objects, not buffers
objectMode: true
});
//Pipe the streams as follows
fileStream.pipe(jsonStream.input);
jsonStream.pipe(processingStream);
//So we're waiting for the 'finish' event when everything is done.
processingStream.on('finish', async () => {
console.log('stream end');
const statistics = new Statistics(jobId);
await statistics.update(); // update the job table for completion of data
});
请建议我如何改进这一点,以便在几小时内解析100万条记录文件,而不是几天或最少更少的时间。
我也愿意使用任何其他工具,如redis,spark,如果这些工具对我有帮助的话
谢谢。而不是一个接一个地从小溪里挤出来。使用批处理方法(创建多个批处理)批量获取数据并保存。谢谢您的回答。你能在nodejs中分享一下我应该如何批量发送数据并保存它吗。我对它很陌生。或者有我应该使用的软件包吗。我不是js专家。
const fileStream = fs.createReadStream(this.fileName);
const jsonStream = StreamArray.withParser();
const incomingThis = this;
const processingStream = new Writable({
write({key, value}, encoding, callback) {
incomingThis.recordParser(value, (val, data) => { // pass the data to elasticsearch to get search data
incomingThis.processQueue(data); // save the data to the PSQL database
callback();
});
},
//Don't skip this, as we need to operate with objects, not buffers
objectMode: true
});
//Pipe the streams as follows
fileStream.pipe(jsonStream.input);
jsonStream.pipe(processingStream);
//So we're waiting for the 'finish' event when everything is done.
processingStream.on('finish', async () => {
console.log('stream end');
const statistics = new Statistics(jobId);
await statistics.update(); // update the job table for completion of data
});