spark处理jsonFile

按照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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值