Spark JSON自动推断模式
我有一个像这样的JSON文件:
{ "id": 1, "str": "a string", "d": "1996-11-20" }
我想让Spark(版本4.0.1)推断模式,并把列 d 转换为日期,但这行不通:
scala> spark.read.option("inferSchema","true").option("dateFormat","yyyy-MM-dd").json("myfile.json").printSchema
root
|-- d: string (nullable = true)
|-- id: long (nullable = true)
|-- str: string (nullable = true)
在加载时无法指定文件的模式。
用CSV时就能正常工作:
1,a string,1996-11-20
scala> spark.read.option("inferSchema","true").csv("myfile.csv").printSchema
root
|-- _c0: integer (nullable = true)
|-- _c1: string (nullable = true)
|-- _c2: date (nullable = true)
我到底做错了什么?
解决方案
看起来目前不支持推断日期,Spark 4.1.1版。尽管有一个 "dateFormat" 选项,但它仅在手动指定模式时用于将字符串解析为日期。
不过有一个 inferTimestamp。我可以把它和 timestampFormat 一起使用,至少可以得到一个时间戳类型(见 JSONOptions.scala):
spark.read.option("inferTimestamp","true").option("timestampFormat","yyyy-MM-dd").json("myfile.json").printSchema
root
|-- d: timestamp (nullable = true)
|-- id: long (nullable = true)
|-- str: string (nullable = true)
这并不理想,因为现在我无法区分日期和时间戳,但至少比字符串要好。
看看我是否能为此提交一个PR。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。