【问题标题】:Google BigQuery Node library: how to stream data in batches?Google BigQuery 节点库:如何批量流式传输数据?
【发布时间】:2017-09-12 12:20:48
【问题描述】:

我正在为 BigQuery 使用 Google Cloud 节点库。我正在使用 createQueryStream method 从 BigQuery 流式传输数据:

var query = 'SELECT transfer_date, price, postcode FROM ';
query += '[table] ORDER BY transfer_date LIMIT 10000';
bigquery.createQueryStream(query)
  .on('error', console.error)
  .on('data', function(row) {
    console.log(row);
  })
  .on('end', function() {
    // All rows retrieved.
  });

这会将每一行单独输出到控制台。但是,我想分批更新我的应用程序,比如每 10,000 个结果。那么如何修改查询以流式传输 10,000 个数据块?

query method 有一个autoPaginate 选项,但我不明白如何使用它。

或者我是否需要手动编写一个函数来触发每 10,000 行?但这似乎效率很低。

【问题讨论】:

    标签: javascript node.js google-bigquery


    【解决方案1】:

    Bigquery node.js API 会在您执行查询时自动处理分页,您无需执行任何操作。 您使用的 API 方法是一次流式传输结果记录 一个。 如果您只对批量处理结果感兴趣,而不对在每个 REST 请求期间如何发生分页感兴趣,那么您可能想尝试:

        var rows = [];
        var batchSize = 10 * 1000;
        var counter = 0;
        var batchCounter = 0;
        var query = 'SELECT transfer_date, price, postcode FROM ';
        query += '[table] ORDER BY transfer_date';
    
        var bigquery = require('@google-cloud/bigquery')();
        bigquery.createQueryStream(query)
        .on('error', console.error)
        .on('data', function(row) {
            //Either use the stream record or keep pushing it to stack.
                if(counter < batchSize){
                    rows.push(row);                      
                    counter++;
                }else{
                    counter=0;
                    batchCounter++;
                    //process the batch of records i.e., fire the custom event or send the content to down-stream applications etc.
                    rows.forEach(function(row){console.log(row)});
                    console.log('Completed batch no.:'+batchCounter);
                    rows.clear;
                }
        })
        .on('end', function() {
            //If you want to process results only at the end.
            console.log('+++++End of the query results+++++'));
        });
    

    options 对象在 createQueryStream 方法中与查询方法相同。 autoPaginate 选项默认设置为 true。 从文档来看,这是一个link

    附:您始终可以通过在查询中包含 LIMIT 子句来限制查询流中的记录总数。

    【讨论】:

    • 谢谢。但是,这不会在请求中返回 maximum 10,000 行吗?我想处理数百万行,但每次有 10,000 行可用时,我的客户端代码中都会触发一个事件。
    • 我已经更新了答案。 maxResults 参数控制分页时每页包含多少条记录。我进行了快速测试,看来您只能使用查询中的 LIMIT 子句控制 createQueryStream 方法中的记录总数。 maxApiCallsmaxResults 只影响内部分页。
    猜你喜欢
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    • 1970-01-01
    • 2020-01-21
    • 2018-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多