Spark-csv数据源:推断数据类型

Spark-csv data source: infer data types

我正在尝试使用 Spark-CSV 包 (https://github.com/databricks/spark-csv) 将 csv 文件读入 Spark DataFrames

一切正常,但假定所有列都是 StringType

如 Spark SQL 文档 (https://spark.apache.org/docs/latest/sql-programming-guide.html) 所示,对于 JSON 等内置源,可以自动推断具有数据类型的架构。

能否自动推断 CSV 文件中的列类型?

遗憾的是,目前不支持此功能,但这将是一个非常有用的功能。目前它们必须在 DLL 中声明。从文档我们有:

header: when set to true the first line of files will be used to name columns and will not be included in data. All types will be assumed string. Default value is false.

这就是您所看到的。

请注意,可以在查询时推断模式,例如

select sum(mystringfield) from mytable

从 Spark 2 开始,我们可以像这样使用选项 'inferSchema': getSparkSession().read().option("inferSchema", "true").csv("YOUR_CSV_PATH")