在Python中使用BigQuery接收器流式传输管道

时间:2018-07-31 20:44:20

标签: python google-cloud-dataflow apache-beam apache-beam-io

我正在构建一个Apache光束流水线,其源是Pubsub,接收器是BigQuery。我收到了错误消息:

“工作流程失败。原因:消息代码未知。”

我现在相信这条消息很神秘,因为不支持BigQuery作为流管道的接收器,它在这里说: Streaming from Pub/Sub to BigQuery

我当然纠正这是引起问题的原因吗?还是如果仍然不被支持?

谁能暗示何时发布此功能?真可惜,我很高兴能使用它。

1 个答案:

答案 0 :(得分:2)

根据Beam docs here

所述,从Beam 2.5.0开始,Python Streaming管道在实验上可用。

因此,您将需要安装apache-beam 2.5.0和apache-beam [gcp]

pip install apache-beam==2.5.0
pip install apache-beam[gcp]

我运行了以下命令:

python pubsub_to_bq.py --runner DataflowRunner --input_topic=projects/pubsub-public-data/topics/taxirides-realtime --project <my-project> --temp_location gs://<my-bucket>/tmp --staging_location gs://<my-bucket>/staging --streaming

使用下面的代码,它可以正常工作:

from __future__ import absolute_import

import argparse
import logging

import apache_beam as beam

def parse_pubsub(line):
    import json
    record = json.loads(line)
    return (record['ride_id']), (record['point_idx']), (record['latitude']), (record['longitude']), (record['timestamp']), (record['meter_increment']), (record['ride_status']), (record['meter_reading']), (record['passenger_count'])

def run(argv=None):
  """Build and run the pipeline."""

  parser = argparse.ArgumentParser()
  parser.add_argument(
      '--input_topic', dest='input_topic', required=True,
      help='Input PubSub topic of the form "/topics/<PROJECT>/<TOPIC>".')
  known_args, pipeline_args = parser.parse_known_args(argv)

  with beam.Pipeline(argv=pipeline_args) as p:

    # Read from PubSub
    lines = p | beam.io.ReadFromPubSub(known_args.input_topic)
    #Adapt messages from PubSub to BQ table
    lines = lines | beam.Map(parse_pubsub)
    lines = lines | beam.Map(lambda (ride_id, point_idx, latitude, longitude, timestamp, meter_increment, ride_status,meter_reading, passenger_count): {'ride_id':ride_id, 'point_idx':point_idx, 'latitude':latitude, 'longitude':longitude, 'timestamp':timestamp, 'meter_increment':meter_increment,'ride_status': ride_status,'meter_reading':meter_reading,'passenger_count': passenger_count})
    #Write to a BQ table 
    lines | beam.io.WriteToBigQuery(table ='<my-table>',dataset='<my-dataset>',project='<my-project>' )

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

此代码使用publicly available topic“ --topic 我使用正确的架构创建的projects / pubsub-public-data / topics / taxirides-realtime”和BQ表。

如果您使用此示例,请注意不要使其继续运行,否则会产生费用,因为您会收到来自此PubSub主题的大量消息。