spark處理jsonFile

白喬發表於2015-03-10

按照spark的說法,這裡的jsonFile是特殊的檔案:

Note that the file that is offered as jsonFile is not a typical JSON file. Each line must contain a separate, self-contained valid JSON object. As a consequence, a regular multi-line JSON file will most often fail.

它是按行分隔多個JSON物件,否則的話就會出錯。

以下是一個jsonFile的內容:

scala> val path = "examples/src/main/resources/people.json"
path: String = examples/src/main/resources/people.json

scala> Source.fromFile(path).foreach(print)
{"name":"Michael"}
{"name":"Andy", "age":30}
{"name":"Justin", "age":19}

可以獲取到一個SchemaRDD:

scala> val sqlContext = new org.apache.spark.sql.SQLContext(sc)
scala> val jsonFile = sqlContext.jsonFile(path)
scala> jsonFile.printSchema()
root
 |-- age: integer (nullable = true)
 |-- name: string (nullable = true)

針對該SchemaRDD可以做遍歷操作:

jsonFile.filter(row=>{val age=row(0).asInstanceOf[Int];age>=13&&age<=19}).collect

既然是SchemaRDD,就可以採用SQL:

scala> jsonFile.registerTempTable("people")
scala> val teenagers = sqlContext.sql("SELECT name FROM people WHERE age >= 13 AND age <= 19")
scala> teenagers.foreach(println)

相關文章