【发布时间】:2020-12-16 19:05:42
【问题描述】:
这很好用:
import org.apache.spark.sql.types.{StructType, StructField, StringType, IntegerType, DateType}
import org.apache.spark.sql.functions._
val df = Seq( ("2018-01-01", "2018-01-31", 80)
, ("2018-01-07","2018-01-10", 10)
, ("2018-01-07","2018-01-31", 10)
, ("2018-01-11","2018-01-31", 5)
, ("2018-01-25","2018-01-27", 5)
, ("2018-02-02","2018-02-23", 100)
).toDF("sd","ed","coins")
val schema = List(("sd", "date"), ("ed", "date"), ("coins", "integer"))
val newColumns = schema.map(c => col(c._1).cast(c._2))
val newDF = df.select(newColumns:_*)
newDF.show(false)
这是我提出的以下问题的解决方法:
import org.apache.spark.sql.types.{StructType, StructField, StringType, IntegerType, DateType};
val someData = Seq(
Row("2018-01-01","2018-01-31", 80)
, Row("2018-01-07","2018-01-10", 10)
, Row("2018-01-07","2018-01-31", 10)
, Row("2018-01-11","2018-01-31", 5)
, Row("2018-01-25","2018-01-27", 5)
, Row("2018-02-02","2018-02-23", 100)
)
val someSchema = List(
StructField("sd", DateType, true),
StructField("ed", DateType, true),
StructField("coins", IntegerType, true),
)
val dfA = spark.createDataFrame(
spark.sparkContext.parallelize(someData),
StructType(someSchema)
)
dfA.show(false)
产生如下错误:
Caused by: RuntimeException: java.lang.String is not a valid external type for schema of date
我知道 int、bigint 问题,并在第一个 sn-p 中指出了日期的解决方法,但我似乎无法使用日期类型 - 我想知道第二个 sn-p 的方法,继续这条脉络。
【问题讨论】:
-
很有趣...我想知道用例是什么?如果从 csv 读取,您可以指定日期格式/时间戳格式,并且大概这不应该发生......
-
刚刚准备databricks考试和复习。我找不到正确的方法,诚然更具学术性,但人们希望这种方法可以理想地发挥作用
-
也许我们只需要假设通常源始终来自磁盘,流并保留它,但我自己很好奇。
标签: scala apache-spark