val path="/Volumes/Data/BigData_code/data/"
//读取json生成dataframe
val df = spark.read.format("json").load(path + "flight-data/json/2015-summary.json")
df.printSchema()
读时模式是通过前几行的数据,来对各个列进行推断各个列的数据类型。优点是方便。但是,读时模式会造成精度损失。因为在前几行推断出是int类型,但是,实际是long类型。
val path="/Volumes/Data/BigData_code/data/"
//自定义schema模式
val mySchema = StructType(Array(
StructField("DEST_COUNTRY_NAME", StringType, true),
StructField("ORIGIN_COUNTRY_NAME", StringType, true),
StructField("count", LongType, false, Metadata.fromJson("{\"home\":\"world\"}"))
))
//生成DataFrame
val df = spark.read.format("json").schema(mySchema) //使用自定义的schema模式
.load(path + "flight-data/json/2015-summary.json")
df.printSchema()
spark的DataFrame的schema模式:读时模式, 指定模式
原文:https://www.cnblogs.com/ALINGMAOMAO/p/14445553.html