我想将序列化的protobuf消息的PCollection写入文本文件并将它们读回应该很容易。但经过几次尝试,我没有这样做。如果有人有任何意见,将不胜感激。
// definition of proto.
syntax = "proto3";
package test;
message PhoneNumber {
string number = 1;
string country = 2;
}
我有下面的 python 代码,它实现了一个简单的 Beam 管道,将文本写入序列化的 protobufs。
# Test python code
import apache_beam as beam
from apache_beam.options.pipeline_options import PipelineOptions
import phone_pb2
class ToProtoFn(beam.DoFn):
def process(self, element):
phone = phone_pb2.PhoneNumber()
phone.number, phone.country = element.strip().split(',')
yield phone.SerializeToString()
with beam.Pipeline(options=PipelineOptions()) as p:
lines = (p
| beam.Create(["123-456-789,us", "345-567-789,ca"])
| beam.ParDo(ToProtoFn())
| beam.io.WriteToText('/Users/greeness/data/phone-pb'))
管道可以成功运行并生成一个包含内容的文件:
$ cat ~/data/phone-pb-00000-of-00001
123-456-789us
345-567-789ca
然后我编写另一个管道来读取序列化的 protobuf 并使用ParDo
.
class ToCsvFn(beam.DoFn):
def process(self, element):
phone = phone_pb2.PhoneNumber()
phone.ParseFromString(element)
yield ",".join([phone.number, phone.country])
with beam.Pipeline(options=PipelineOptions()) as p:
lines = (p
| beam.io.ReadFromText('/Users/greeness/data/phone*')
| beam.ParDo(ToCsvFn())
| beam.io.WriteToText('/Users/greeness/data/phone-csv'))
运行时收到此错误消息。
File "/Library/Python/2.7/site-packages/apache_beam/runners/common.py", line 458, in process_outputs
for result in results:
File "phone_example.py", line 37, in process
phone.ParseFromString(element)
File "/Library/Python/2.7/site-packages/google/protobuf/message.py", line 185, in ParseFromString
self.MergeFromString(serialized)
File "/Library/Python/2.7/site-packages/google/protobuf/internal/python_message.py", line 1069, in MergeFromString
raise message_mod.DecodeError('Truncated message.')
DecodeError: Truncated message. [while running 'ParDo(ToCsvFn)']
所以看起来无法解析序列化的 protobuf 字符串。我错过了什么吗?谢谢你的帮助!