繁体   English   中英

Apache Beam Python SDK:如何访问元素的时间戳?

[英]Apache Beam Python SDK: How to access timestamp of an element?

我正在通过带有timestamp_attribute=NoneReadFromPubSub阅读消息,这应该将时间戳设置为发布时间。

这样,我最终得到了PCollection元素的PubsubMessage

如何按顺序访问这些元素的时间戳,例如将它们保存到数据库中? 我能看到的唯一属性是dataattributes ,而attributes只有来自 Pub/Sub 的键。

编辑:示例代码

with beam.Pipeline(options=pipeline_options) as p:
    items = (p
        | ReadFromPubSub(topic=args.read_topic, with_attributes=True)
        | beam.WindowInto(beam.window.FixedWindows(args.time_window))
        | 'FormatMessage' >> beam.Map(format_message)
        | 'WriteRaw' >> WriteToBigQuery(args.raw_table, args.dataset,
            args.project, write_disposition='WRITE_APPEND')
    )

其中format_message将采用PubsubMessage并将代表行的字典返回到 append 到表中:

def format_message(message):
    formatted_message = {
        'data': base64.b64encode(message.data),
        'attributes': str(message.attributes)
    }
    return formatted_message

事实证明,可以修改映射函数以读取其他参数:

def format_message(message, timestamp=beam.DoFn.TimestampParam):    
    formatted_message = {
        'data': base64.b64encode(message.data),
        'attributes': str(message.attributes),
        'timestamp': float(timestamp)
    }

    return formatted_message

更多可能的参数: https : //beam.apache.org/releases/pydoc/2.7.0/apache_beam.transforms.core.html#apache_beam.transforms.core.DoFn

您是否尝试过设置with_attributes = True?

希望Beam文档对您有所帮助。 参数包括:

with_attributes – True-输出元素将是PubsubMessage对象。 默认为False-输出元素将为字节类型(仅消息数据)。

调用beam.io.gcp.pubsub.ReadFromPubSub()时似乎有(新发布的!!timestamp_attribute参数。

但我尽了最大努力,但并没有达到我的预期。 如果有人想要跟进DataFlow(PY 2.x SDk)ReadFromPubSub :: id_label和timestamp_attribute表现异常,则在SO上发布新查询

我不知道这是什么时候引入的,但除了shadesofdarkred 的回答之外还有另一种方法(例如也可以在lambda中使用)。

ReadFromPubSub返回的PubsubMessage有一个属性publish_time

因此,考虑到原始问题中的代码,您可以使用message.publish_time轻松访问它。

文档

发布时间

(日期时间)消息发布的时间。 如果将消息写入 pubsub,将重置为 None。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM