如何使用Python处理数据流管道中的BigQuery插入错误?
我正在尝试使用数据流创建一个流式管道,该管道从PubSub主题读取消息,最后将其写入BigQuery表。我不想使用任何数据流模板 目前,我只想在从Google VM实例执行的Python3脚本中创建一个管道,对从Pubsub到达的每条消息执行加载和转换过程(解析它包含的记录并添加一个新字段),最终将结果写入BigQuery表 简单来说,我的代码是:如何使用Python处理数据流管道中的BigQuery插入错误?,python,google-bigquery,google-cloud-dataflow,apache-beam,google-cloud-pubsub,Python,Google Bigquery,Google Cloud Dataflow,Apache Beam,Google Cloud Pubsub,我正在尝试使用数据流创建一个流式管道,该管道从PubSub主题读取消息,最后将其写入BigQuery表。我不想使用任何数据流模板 目前,我只想在从Google VM实例执行的Python3脚本中创建一个管道,对从Pubsub到达的每条消息执行加载和转换过程(解析它包含的记录并添加一个新字段),最终将结果写入BigQuery表 简单来说,我的代码是: #!/usr/bin/env python from apache_beam.options.pipeline_options import Pip
#!/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表所期望的
我想处理的问题是:
您无法捕获sink to BigQuery中发生的错误。您写入bigquery的消息必须是好的
最好的模式是执行检查消息结构和字段类型的转换。如果出现错误,您将创建一个错误流,并将此问题流写入一个文件(例如,在没有架构的表中,您将以纯文本形式写入消息)非常感谢Guillaume!这正是我想象的。您知道我可以在哪个网站或存储库中找到数据流中Python检查应用程序的示例吗。在DoFn函数中,如
ProcessWords
,执行检查以确保流程正确。对于所有发现的错误,执行此生成pvalue.TaggedOutput('error\u value',element)
。通过应用ParDo,您可以在输出中获得2个集合:正确流和错误流。然后在每个PCollection上应用所需的接收器。