BigQuery表作为Pub/Sub主题在ApacheBeamPythonSDK中无法工作?静态源到流式接收器
创始人
2024-12-12 10:30:06
0

可能原因是在Python SDK中,不支持将BigQuery表作为Pub/Sub主题直接使用。解决方法是,使用Dataflow的Streaming Engine,利用自定义的 PubsubToBigQuery 类将Pub/Sub消息写入到BigQuery表中。

以下是一个示例代码:

import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions, StandardOptions

class PubsubToBigQuery(beam.DoFn):
    def __init__(self,dataset,table):
        self.dataset = dataset
        self.table = table

    def start_bundle(self):
        self.bigquery_client = bigquery.Client()
        self.dataset_ref = self.bigquery_client.dataset(self.dataset)
        self.table_ref = self.dataset_ref.table(self.table)

    def process(self, element, timestamp=beam.DoFn.TimestampParam):
        try:
            row = {
                "column1": element['column1'],
                "column2": element['column2'],
                "timestamp": timestamp
            }
            errors = self.bigquery_client.insert_rows_json(self.table_ref, [row], ignore_unknown_values=True)
            if errors:
                raise Exception(errors)
            else:
                return [element['column1']]
        except Exception as e:
            return []

def run():
    pipeline_options = PipelineOptions()
    pipeline_options.view_as(StandardOptions).streaming = True
    p = beam.Pipeline(options=pipeline_options)

    (p | "Read from Pub/Sub" >> beam.io.ReadFromPubSub(subscription="projects/{project}/subscriptions/{subscription}")
       | "Transform message" >> beam.Map(lambda x: json.loads(x))
       | "Write to BigQuery" >> beam.ParDo(PubsubToBigQuery(dataset='my_dataset', table='my_table')))
    
    p.run().wait_until_finish()

在此示例中,Pub/Sub消息将从指定的订阅中读取,然后将每条消息转换为JSON,并将其传递给 PubsubToBigQuery 类。类将转换后的消息写入到指定的 BigQuery 表中。在表格结构的之后,您

相关内容

热门资讯

4分钟作弊视频!哈糖大菠萝助手... 4分钟作弊视频!哈糖大菠萝助手(透视辅助软件)详细辅助助手(确实助手);1、超多福利:超高返利,海量...
三分钟私人局辅助免费!德普软件... 三分钟私人局辅助免费!德普软件(透视辅助)详细辅助教程(一直教程)1、用户打开应用后不用登录就可以直...
3分钟免费钻石!sohoo p... 3分钟免费钻石!sohoo poker辅助(透视脚本)详细辅助俱乐部(果然俱乐部);1、进入游戏-大...
三分钟有透视!德扑圈有透视吗,... 三分钟有透视!德扑圈有透视吗,德普之星透视辅助软件激活码,详细教程(有挂教程)运德普之星透视辅助软件...
二分钟软件安装包!sohoop... 二分钟软件安装包!sohoopoker辅助(辅助挂)详细辅助软件(好像软件)1、下载好sohoopo...
两分钟软件下载!德普之星有透视... 两分钟软件下载!德普之星有透视辅助吗,德普之星透视,详细教程(有挂秘笈);1、下载好德普之星透视辅助...
4分钟开辅助!拱趴大菠萝挂怎么... 4分钟开辅助!拱趴大菠萝挂怎么安装(透视脚本辅助器)详细辅助教程(本来教程);运拱趴大菠萝挂辅助工具...
九分钟免费透视!德普之星透视辅... 九分钟免费透视!德普之星透视辅助软件下载(透视辅助软件)详细辅助工具(一贯工具)1、金币登录送、破产...
1分钟透视辅助!德普之星透视辅... 1分钟透视辅助!德普之星透视辅助软件,德普之星透视辅助软件下载,详细教程(有挂技巧)1、用户打开应用...
2分钟模拟器!智星德州插件20... 2分钟模拟器!智星德州插件2024最新版,pokermaster修改器,详细教程(有挂技巧);智星德...