Spark學習小記-(1)DataFrame的schema
阿新 • • 發佈:2021-01-03
Schema是什麼
DataFrame中的資料結構資訊,即為schema。DataFrame中提供了詳細的資料結構資訊,從而使得SparkSQL可以清楚地知道該資料集中包含哪些列,每列的名稱和型別各是什麼。
自動推斷生成schema
使用spark的示例檔案people.json, 檢視資料:
[root@hadoop01 resources]# head -5 people.json {"name":"Michael"} {"name":"Andy", "age":30} {"name":"Justin", "age":19}
建立dataframe,檢視該dataframe的schema:
>>>df=spark.read.format("json").load("/opt/module/spark/examples/src/main/resources/people.json") >>> df.printSchema() root |-- age: long (nullable = true) --age列,long型,可以為null |-- name: string (nullable = true) --name列,string型,可以為null
換一種schema檢視方式
>>>spark.read.format("json").load("/opt/module/spark/examples/src/main/resources/people.json").schema StructType(List(StructField(age,LongType,true),StructField(name,StringType,true))) # 模式Schema是多個欄位構成的StructType,欄位是StructField,每個StructField資訊包括名稱、型別、能否為null. 還可以指定與列關聯的元資料
指定schema
>>> from pyspark.sql.types import StructField,StructType,StringType,IntegerType>>> myschema=StructType([StructField("nianling",IntegerType(), True),StructField("xingming",StringType(), True)]) # 這裡注意是[]、StringType()、True,而不是List、StringType、true >>>df=spark.read.format("json").schema(myschema).load("/opt/module/spark/examples/src/main/resources/people.json") >>> df.take(5) [Row(nianling=None, xingming=None), Row(nianling=None, xingming=None), Row(nianling=None, xingming=None)] # 為什麼資料沒有載入進去???
可能是指定的欄位與json中的key值不一致??有可能
# 這裡就只是把年齡型別由預設推斷的long改成了int,可以讀取成功 >>> myschema=StructType([StructField("age",IntegerType(), True),StructField("name",StringType(), True)]) >>> df=spark.read.format("json").schema(myschema).load("/opt/module/spark/examples/src/main/resources/people.json") >>> df.take(5) [Row(age=None, name=u'Michael'), Row(age=30, name=u'Andy'), Row(age=19, name=u'Justin')]
(示例用的是pyspark)