[英]Scala - How to Call REST API and save as json file in HDFS?
环境:Scala和spark 1.6
我在尝试着 -
1.通过Rest API调用获取JSON数据
2.将HDFS作为json文件写入。3.将json文件转换为数据框
val rawdata = "curl http://services.groupkt.com/state/get/USA/all"!!
println(rawdata) // can see json output, but can't save as file in HDFS
我可以在屏幕上看到输出,但是如何将原始数据的内容写入hdfs url(hdfs://quickstart.cloudera:8020 / user / hive / warehouse / test /)? 还是有没有办法保存原始数据内容而不保存为文件? 我还需要将json转换为dataframe。
提前致谢
侯赛因
val rawdata = "curl http://services.groupkt.com/state/get/USA/all"!!
println(rawdata)
一旦有了data
,就可以使用此答案中的代码将其保存在Hadoop
。
创建数据框:
假设您的json字符串是这样的:
{"time":"sometext1","host":"somehost1","event": {"category":"sometext2","computerName":"somecomputer1"}}
您可以通过以下代码将json into dataframe
:
// Creating Rdd
val vals = sc.parallelize(
"""{"time":"sometext1","host":"somehost1","event": {"category":"sometext2","computerName":"somecomputer1"}}""" ::
Nil)
// Creating Schema
val schema = (new StructType)
.add("time", StringType)
.add("host", StringType)
.add("event", (new StructType)
.add("category", StringType)
.add("computerName", StringType))
import sqlContext.implicits._
val jsonDF = sqlContext.read.schema(schema).json(vals)
创建dataframe
您仍然可以选择使用spark-csv lib或在RDD上使用saveAsTextFile
方法将其保存在hadoop
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.