Python Apache Beam:日期值超出范围

时间:2018-11-07 17:07:09

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

应用thisthis示例来构建程序,每次尝试插入Big Query时,都会出现此错误:

OverflowError:[在运行“格式”时]日期值超出范围

我的光束管道是这样的:

Bigquery = (transformation
            | 'Format' >> beam.ParDo(FormatBigQueryoFn())
            | 'Write to BigQuery' >> beam.io.Write(beam.io.BigQuerySink(
            'XXXX',
            schema=TABLE_SCHEMA,
            create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED,
            write_disposition=beam.io.BigQueryDisposition.WRITE_APPEND
        )))

在FormatBigQueryoFn类中,它应该是窗口数据时间的逻辑

示例1的代码:

def timestamp2str(t, fmt='%Y-%m-%d %H:%M:%S.000'):
  """Converts a unix timestamp into a formatted string."""
    return datetime.fromtimestamp(t).strftime(fmt)

    class TeamScoresDict(beam.DoFn):
  """Formats the data into a dictionary of BigQuery columns with their values
  Receives a (team, score) pair, extracts the window start timestamp, and
  formats everything together into a dictionary. The dictionary is in the format
  {'bigquery_column': value}
  """

def process(self, team_score, window=beam.DoFn.WindowParam):
    team, score = team_score
    start = timestamp2str(int(window.start))
    yield {
        'team': team,
        'total_score': score,
        'window_start': start,
        'processing_time': timestamp2str(int(time.time()))
}

示例2的代码:

class FormatDoFn(beam.DoFn):
  def process(self, element, window=beam.DoFn.WindowParam):
    ts_format = '%Y-%m-%d %H:%M:%S.%f UTC'
    window_start = window.start.to_utc_datetime().strftime(ts_format)
    window_end = window.end.to_utc_datetime().strftime(ts_format)
    return [{'word': element[0],
             'count': element[1],
             'window_start':window_start,
'window_end':window_end}]

我的管道有什么问题?

编辑:

例如,如果我打印window.start,我将得到:

Timestamp(-9223372036860)

1 个答案:

答案 0 :(得分:1)

问题是我要先从文件中读取数据,然后才能通过Google Pub / Sub进行测试。

当我从文件中读取数据时,元素没有时间戳。

必须在元素中添加时间戳。

发布/订阅会自动附加此时间戳。

来自documentation

最简单的窗口形式是使用固定时间的窗口:给定时间戳的PCollection可能会不断更新,每个窗口可能会捕获(例如)所有时间戳落在5分钟间隔内的元素。