PySpark读取CSV时option指定Schema失效问题咨询
PySpark指定CSV Schema两种方式的差异原因
问题场景
尝试加载departuredelays.csv时,使用option("schema", schema)指定自定义Schema未生效:
from pyspark.sql import SparkSession from pyspark.sql.functions import * from pyspark.sql.types import * from pyspark.sql import Window spark = SparkSession.builder.appName('Demo').master('local').getOrCreate() pathData = '/home/data/departuredelays.csv' schema = StructType([ StructField('date', StringType()), StructField('delay', IntegerType()), StructField('distance', IntegerType()), StructField('origin', StringType()), StructField('destination', StringType()), ]) flightsDelatDf = (spark .read .format('csv') .option('path', pathData) .option('header', True) .option("schema", schema) .load() )
执行flightsDelatDf.printSchema()后,列类型不符合定义:
root |-- date: string (nullable = true) |-- delay: string (nullable = true) |-- distance: string (nullable = true) |-- origin: string (nullable = true) |-- destination: string (nullable = true)
改用.schema(schema)方法后,Schema生效:
flightsDelatDf = (spark .read .format('csv') .option('path', pathData) .option('header', True) .schema(schema) .load() )
执行printSchema()结果符合预期:
root |-- date: string (nullable = true) |-- delay: integer (nullable = true) |-- distance: integer (nullable = true) |-- origin: string (nullable = true) |-- destination: string (nullable = true)
原因解析
option("schema", schema)的错误本质
PySpark的option("schema", ...)参数仅接受字符串格式的DDL Schema(例如"date string, delay int, distance int, origin string, destination string"),而非直接传入StructType对象。当你传入StructType实例时,PySpark无法解析该对象,会直接忽略这个无效配置,退回到CSV数据源的默认类型推断逻辑——默认将所有列推断为字符串类型,导致定义的IntegerType不生效。.schema(schema)的正确逻辑.schema()是DataFrameReader专门设计的Schema指定API,它支持两种输入:- 直接传入
StructType对象 - 传入DDL格式的字符串
该API能正确解析你定义的字段类型映射,加载数据时会严格按照指定Schema解析每一列,因此类型符合预期。
- 直接传入
补充验证
如果要通过option方式指定Schema,可将StructType转换为DDL字符串:
flightsDelatDf = (spark .read .format('csv') .option('path', pathData) .option('header', True) .option("schema", schema.simpleString()) .load() )
此时执行printSchema()也会得到符合定义的列类型。
内容的提问来源于stack exchange,提问作者DumbCoder
相关产品推荐
相关产品推荐

