如何高效地将Postgres查询数据传输到S3

7

我的node.js应用程序服务目前使用提供的select查询来访问postgres数据库,将其转换为csv格式,然后将该CSV文件上传到S3。

我想知道是否有更好的方法来更有效地处理大数据拉取?

1个回答

5

这应该能让你达到90%的目标。我没有测试过这个确切的实现,可能会有一两个笔误,但我现在正在生产中运行类似的代码。

const { Transform } = require('json2csv');
const { Client, Query } = require('pg')
const { S3 } = require('aws-sdk');
const { Passthrough } = require('stream')

const client = new Client()
const s3 = new S3({ region: 'us-east-1' });


const opts = { fields: ['field1', 'field2', 'field3'] };
const transformOpts = { highWaterMark: 8192, encoding: 'utf-8', objectMode: true };

const transform = new Transform(opts, transformOpts);
const passthrough = new Passthrough();
transform.pipe(passthrough)


client.connect()

const query = new Query('SELECT field1, field2, field3 FROM table')
client.query(query)

query.on('row', row => {
  transform.push(row);
  console.log('row!', row) // { field1: 1, field2: 2, field3: 3 }
})
query.on('end', () => {
  transform.push(null)
  console.log('query done')
})
query.on('error', err => {
  transform.end();
  console.error(err.stack)
})

s3.upload({ Body: passthrough, Key: 'somefile.csv', Bucket: 'some_bucket' })
.send((err, data) => {
  if (err) {
    console.error({ err });
    passthrough.destroy(err);
  } else {
    console.log(`File uploaded and available at ${data.Location}`);
    passthrough.destroy();
  }
});

经过头脑风暴,我最终使用了非常类似的方法,利用了 pg-copy-streams 节点包(https://github.com/brianc/node-pg-copy-streams)。感谢您详尽的回复。 - rotsner

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接