【问题标题】:How do I measure progress while streaming a postgres database query via pg-query-stream?如何在通过 pg-query-stream 流式传输 postgres 数据库查询时测量进度?
【发布时间】:2022-04-14 22:56:56
【问题描述】:

我有一个 ETL 查询,它需要我读取大量行,然后对它们应用一些转换并将它们保存回 Postgres 中的单独表中。我正在使用 pg-query-stream,我计划在 Bullmq 作业中运行下面的测试函数。

我如何衡量以下给定流的进度(已处理的当前行数/总行数)?

const { Pool } = require('pg');
const JSONStream = require('JSONStream');
const QueryStream = require('pg-query-stream');

function test() {
  const pool = new Pool({
    database: process.env.POSTGRES_DB,
    host: process.env.POSTGRES_HOST,
    port: +process.env.POSTGRES_PORT,
    password: process.env.POSTGRES_PASSWORD,
    ssl: process.env.POSTGRES_SSL === 'true',
    user: process.env.POSTGRES_USER,
  });
  const query = `
    SELECT 
        feed_item_id, 
        title, 
        summary, 
        content 
    FROM 
        feed_items 
    ORDER BY 
        pubdate DESC, 
        feed_item_id
    LIMIT 50
    `;

  pool.connect((err, client, done) => {
    if (err) throw err;
    const queryStream = new QueryStream(query, [], {
      batchSize: 200,
    });
    const stream = client.query(queryStream);
    console.log(stream);
    stream.pipe(JSONStream.stringify());
    stream.on('error', (error) => {
      console.error(error);
      done();
    });
    stream.on('end', () => {
      console.log('stream has ended');
      done();
    });
    stream.on('data', async (row) => {
      stream.pause();
      console.log('data received', row.feed_item_id);
      //   const progress = index / ???
      //   Simulate async task
      await timeout(10);
      stream.resume();
    });
  });
}

test();

【问题讨论】:

    标签: node.js postgresql node-streams bullmq


    【解决方案1】:

    为此,您需要先获取表中的行数。
    您可以使用described here

    有了这个计数,您可以将QueryStream 传送到另一个流中并测量那里的进度:

    const Stream = require('stream')
    
    class ProgressStream extends Stream.Writable{
      constructor(total) {
        super();
        this.i = 0;
        this.total = total;
      }
    
      _write(chunk, enc, done) {
        this.i++;
        if (this.i % 100 === 1) {
          console.log(`Processed ${this.i} out of ${this.total} of rows`);
        }
        done();
      }
    }
    
    const progressStream = new ProgressStream(count);
    progressStream.on('finish', () => {
      console.log(`All ${progressStream.i} rows processed!`)
    });
    
    stream.pipe(progressStream);
    

    【讨论】:

      猜你喜欢
      • 2020-10-21
      • 1970-01-01
      • 2020-08-03
      • 2019-10-29
      • 2018-03-06
      • 2010-09-25
      • 2022-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多