【问题标题】:How to handle BigQuery insert errors in a Dataflow pipeline using Python?如何使用 Python 在 Dataflow 管道中处理 BigQuery 插入错误?
【发布时间】:2020-03-10 19:29:29
【问题描述】:

我正在尝试使用 Dataflow 创建一个流式管道,该管道从 PubSub 主题读取消息,最终将它们写入 BigQuery 表。我不想使用任何数据流模板。

目前我只想在从 Google VM 实例执行的 Python3 脚本中创建一个管道,以执行从 Pubsub 到达的每条消息的加载和转换过程(解析它包含的记录并添加一个新字段) 最终将结果写入 BigQuery 表。

简单来说,我的代码是:

#!/usr/bin/env python
from apache_beam.options.pipeline_options import PipelineOptions
from google.cloud import pubsub_v1, 
import apache_beam as beam
import apache_beam.io.gcp.bigquery
import logging
import argparse
import sys
import json
from datetime import datetime, timedelta

def load_pubsub(message):
    try:
        data = json.loads(message)
        records = data["messages"]
        return records
    except:
        raise ImportError("Something went wrong reading data from the Pub/Sub topic")

class ParseTransformPubSub(beam.DoFn):
    def __init__(self):
        self.water_mark = (datetime.now() + timedelta(hours = 1)).strftime("%Y-%m-%d %H:%M:%S.%f")
    def process(self, records):
        for record in records:
            record["E"] = self.water_mark 
            yield record

def main():
    table_schema = apache_beam.io.gcp.bigquery.parse_table_schema_from_json(open("TableSchema.json"))
    parser = argparse.ArgumentParser()
    parser.add_argument('--input_topic')
    parser.add_argument('--output_table')
    known_args, pipeline_args = parser.parse_known_args(sys.argv)
    with beam.Pipeline(argv = pipeline_args) as p:
        pipe = ( p | 'ReadDataFromPubSub' >> beam.io.ReadStringsFromPubSub(known_args.input_topic)
                   | 'LoadJSON' >> beam.Map(load_pubsub)
                   | 'ParseTransform' >> beam.ParDo(ParseTransformPubSub())
                   | 'WriteToAvailabilityTable' >> beam.io.WriteToBigQuery(
                                      table = known_args.output_table,
                                      schema = table_schema,
                                      create_disposition = beam.io.BigQueryDisposition.CREATE_IF_NEEDED,
                                      write_disposition = beam.io.BigQueryDisposition.WRITE_APPEND)
                )   
        result = p.run()
        result.wait_until_finish()

if __name__ == '__main__':
  logger = logging.getLogger().setLevel(logging.INFO)
  main()

(例如)PubSub 主题发布的消息使用如下:

'{"messages":[{"A":"Alpha", "B":"V1", "C":3, "D":12},{"A":"Alpha", "B":"V1", "C":5, "D":14},{"A":"Alpha", "B":"V1", "C":3, "D":22}]}'

如果在记录中添加字段“E”,那么记录的结构(Python 中的字典)和字段的数据类型就是 BigQuery 表所期望的。

我想要处理的问题是:

  1. 如果某些消息带有意外的结构,我想将管道分叉并展平并将它们写入另一个 BigQuery 表中。

  2. 如果某些消息带有意外的字段数据类型,则在管道的最后一级应该将它们写入表中时会发生错误。我想通过将记录转移到第三个表来管理此类错误。

我阅读了以下页面上的文档,但一无所获: https://cloud.google.com/dataflow/docs/guides/troubleshooting-your-pipeline https://cloud.google.com/dataflow/docs/guides/common-errors

顺便说一句,如果我选择通过从 PubSubSubscription 读取并写入 BigQuery 的模板来配置管道的选项,我会得到以下架构,这与我正在寻找的架构相同:

Template: Cloud Pub/Sub Subscription to BigQuery

【问题讨论】:

    标签: python google-bigquery google-cloud-dataflow apache-beam google-cloud-pubsub


    【解决方案1】:

    您无法将接收器中发生的错误捕获到 BigQuery。您写入 bigquery 的消息必须是好的。

    最好的模式是执行一个检查你的消息结构和字段类型的转换。如果出现错误,您将创建一个错误流程并将此问题流程写入文件中(例如,或在没有架构的表中,您以纯文本形式写入您的消息)

    【讨论】:

    • 非常感谢纪尧姆!这正是我的想象。您知道任何网站或存储库,我可以在其中找到 Dataflow 中 Python 检查应用程序的示例吗?
    • Beam programming guide provide a full example of what you can do。在 DoFn 函数中,例如 ProcessWords,执行您希望确保流程正确的检查。对于发现的所有错误,请执行此yield pvalue.TaggedOutput('error_value', element)。通过应用 ParDo,您会在输出中获得 2 个 PCollection:正确流和错误流。然后在每个 PCollection 上应用您想要的接收器。
    猜你喜欢
    • 2019-08-14
    • 2019-02-02
    • 2019-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 2018-10-18
    相关资源
    最近更新 更多