在 Spark 中 org.apache.spark.sql.types.Timestamp - 是 abstract class DataType 的子类。所有这些子类就像DataFrame 列的元信息类型。它们不包含一些价值,但 java.sql.Timestamp 做到了。而且它们不是子类,这就是你不能使用asInstanceOf 投射它的原因。
举个小例子感受一下区别:
当您将数据存储到 DataFrame 时,Spark 会自行将其转换为 spark.Timestamp
import java.sql.Timestamp
val t = new Timestamp(System.currentTimeMillis())
val dfA: DataFrame = Seq(
("a", t),
("b", t),
("c", t)
).toDFc"key", "time")
但如果您想读取数据并获取java.Timestamp,您可以这样做:
dfA.collect().foreach{
row =>
println(row.getAs[Timestamp](1))
}
// will prints
2020-07-31 00:45:48.825
2020-07-31 00:45:48.825
2020-07-31 00:45:48.825
如果您会查看DataFrame 架构:
dfA.printSchema()
dfA.schema.fields.foreach(println)
它会打印出来:
root
|-- key: string (nullable = true)
|-- time: timestamp (nullable = true)
StructField(key,StringType,true)
StructField(time,TimestampType,true)
但如果您尝试使用asInctanceOf 强制转换 java.Timestamp,您将得到相当大的错误:
println(t.asInstanceOf[TimestampType])
/*
java.sql.Timestamp incompatible with
org.apache.spark.sql.types.TimestampType java.lang.ClassCastException: java.sql.Timestamp incompatible with org.apache.spark.sql.types.TimestampType
/*