【发布时间】: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 表所期望的。
我想要处理的问题是:
如果某些消息带有意外的结构,我想将管道分叉并展平并将它们写入另一个 BigQuery 表中。
如果某些消息带有意外的字段数据类型,则在管道的最后一级应该将它们写入表中时会发生错误。我想通过将记录转移到第三个表来管理此类错误。
我阅读了以下页面上的文档,但一无所获: https://cloud.google.com/dataflow/docs/guides/troubleshooting-your-pipeline https://cloud.google.com/dataflow/docs/guides/common-errors
顺便说一句,如果我选择通过从 PubSubSubscription 读取并写入 BigQuery 的模板来配置管道的选项,我会得到以下架构,这与我正在寻找的架构相同:
【问题讨论】:
标签: python google-bigquery google-cloud-dataflow apache-beam google-cloud-pubsub