Spark學習小記-(1)DataFrame的schema


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)

jupyter需要自己創建SparkSession

 

 

 關閉sc.stop()


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM