数据流中带有时间戳的过程字段

时间:2019-03-26 10:13:45

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

我正在从Google Cloud Pub / Sub接收以下格式的消息:

{u'date': u'2019-03-26T09:57:52Z', 'field1': value1, u'field2': u'value2', u'field3': u'value3', u'field4': u'value4',...}

当在窗口的管道中处理此消息时,我希望这样做:

| 'Window' >> beam.WindowInto(window.FixedWindows(1 * 10))

“日期”字段将作为窗口的参考时间戳。

我需要自定义WindowFn还是应该怎么做?

1 个答案:

答案 0 :(得分:1)

您需要这样指定自定义时间戳:

def custom_timestamp(message):
    # assuming that message is already parsed JSON (dict)
    import datetime as dt
    import apache_beam as beam
    ts = dt.datetime.strptime(message["date"], "%Y-%m-%dT%H:%M:%SZ")
    return beam.window.TimestampedValue(message, ts.timestamp())

然后:

| 'CustomTimestamp' >> beam.Map(custom_timestamp)
| 'Window' >> beam.WindowInto(window.FixedWindows(1 * 10))

您可以在这里找到完整的详细信息:https://beam.apache.org/documentation/programming-guide/#adding-timestamps-to-a-pcollections-elements

但是,您必须注意,用于Apache Beam的Streaming Python SDK缺少很多部分,有些事情并没有按您预期的那样工作。我想实现与您完全相同的情况,并在添加自定义时间戳后,由于DataFlow Runner称之为 droppedDueToLateness ,他们丢弃了我的消息。我仍然不确定是否可以设置系统水印来使用PubSub和Python处理历史数据。