从BigQuery读取数据的Apache Beam管道中float类型转string实现
Apache Beam 从BigQuery读取数据时的float转string方案
报错
TypeError: expected string or bytes-like object的核心原因:beam.Regex.matches算子仅支持字符串/字节类型输入,但从BigQuery读取的Expected列存在非字符串类型值(如float、Python原生nan),直接传入正则匹配触发类型错误。
修复方案
根据转换逻辑的执行位置,分为两种可落地的实现:
方案1:Beam管道内做类型转换(灵活可控)
在提取Expected列值后、正则匹配前,新增类型转换算子,统一处理特殊值(如BigQuery的NULL→PythonNone、floatnan)。
完整修改后代码
from apache_beam.io.gcp.internal.clients import bigquery import apache_beam as beam from apache_beam.options.pipeline_options import PipelineOptions import math # 自定义字符串转换函数,按需处理特殊值 def convert_to_str(value): # 处理BigQuery读取的NULL(对应Python None) if value is None: return '' # 处理float类型的NaN(BigQuery FLOAT64类型的空值/非数会被Beam读为Python nan) if isinstance(value, float) and math.isnan(value): return '' # 其余类型统一转字符串 return str(value) table_spec = bigquery.TableReference( projectId='fill_in', datasetId='fill_in', tableId='fill_in') options = PipelineOptions( runner='DataflowRunner', project='fill_in', job_name='fill_in', temp_location='gs://fill_in', region='us-central1') # 正则匹配规则 regex = r'^\d+\s\w+?$' with beam.Pipeline(options=options) as pipeline: plants_matches = ( pipeline | 'ReadTable' >> beam.io.ReadFromBigQuery(table=table_spec) # 提取Expected列值 | beam.Map(lambda elem: elem['Expected']) # 关键修复:统一转换为字符串 | 'ConvertToStr' >> beam.Map(convert_to_str) # 后续正则匹配 | 'Parse plants' >> beam.Regex.matches(regex) | beam.Map(print) )
若不需要特殊处理
None/NaN,可将转换步骤简化为beam.Map(str),替代自定义函数。
方案2:BigQuery侧做类型转换(高效低开销)
直接用SQL查询读取数据,在BigQuery侧用CAST函数强制将Expected列转为STRING类型,减少Beam管道的计算量。
代码修改片段(替换原有ReadTable步骤)
# 项目、数据集、表名替换为实际值 PROJECT_ID = 'fill_in' DATASET_ID = 'fill_in' TABLE_ID = 'fill_in' plants_matches = ( pipeline # 用SQL查询替代直接读表,在BigQuery侧完成类型转换 | 'ReadTable' >> beam.io.ReadFromBigQuery( query=f'SELECT CAST(Expected AS STRING) as Expected FROM `{PROJECT_ID}.{DATASET_ID}.{TABLE_ID}`', use_standard_sql=True, project=PROJECT_ID ) | beam.Map(lambda elem: elem['Expected']) | 'Parse plants' >> beam.Regex.matches(regex) | beam.Map(print) )
内容的提问来源于stack exchange,提问作者Miya Pniel
相关产品推荐
相关产品推荐

