当前位置:   article > 正文

创建dataframe的几种方式——读取json格式的RDD_行为json数据的rdd转dataframe

行为json数据的rdd转dataframe

一、Java代码

  1. SparkConf conf = new SparkConf();
  2. conf.setMaster("local").setAppName("jsonRDD");
  3. JavaSparkContext sc = new JavaSparkContext(conf);
  4. SQLContext sqlContext = new SQLContext(sc);
  5. JavaRDD<String> nameRDD = sc.parallelize(Arrays.asList(
  6. "{\"name\":\"zhangsan\",\"age\":\"18\"}",
  7. "{\"name\":\"lisi\",\"age\":\"19\"}",
  8. "{\"name\":\"wangwu\",\"age\":\"20\"}"
  9. ));
  10. JavaRDD<String> scoreRDD = sc.parallelize(Arrays.asList(
  11. "{\"name\":\"zhangsan\",\"score\":\"100\"}",
  12. "{\"name\":\"lisi\",\"score\":\"200\"}",
  13. "{\"name\":\"wangwu\",\"score\":\"300\"}"
  14. ));
  15. DataFrame namedf = sqlContext.read().json(nameRDD);
  16. DataFrame scoredf = sqlContext.read().json(scoreRDD);
  17. namedf.registerTempTable("name");
  18. scoredf.registerTempTable("score");
  19. DataFrame result = sqlContext.sql("select name.name,name.age,score.score from name,score where name.name = score.name");
  20. result.show();
  21. sc.stop();

二、Scala代码

  1. val conf = new SparkConf()
  2. conf.setMaster("local").setAppName("jsonrdd")
  3. val sc = new SparkContext(conf)
  4. val sqlContext = new SQLContext(sc)
  5. val nameRDD = sc.makeRDD(Array(
  6. "{\"name\":\"zhangsan\",\"age\":18}",
  7. "{\"name\":\"lisi\",\"age\":19}",
  8. "{\"name\":\"wangwu\",\"age\":20}"
  9. ))
  10. val scoreRDD = sc.makeRDD(Array(
  11. "{\"name\":\"zhangsan\",\"score\":100}",
  12. "{\"name\":\"lisi\",\"score\":200}",
  13. "{\"name\":\"wangwu\",\"score\":300}"
  14. ))
  15. val nameDF = sqlContext.read.json(nameRDD)
  16. val scoreDF = sqlContext.read.json(scoreRDD)
  17. nameDF.registerTempTable("name")
  18. scoreDF.registerTempTable("score")
  19. val result = sqlContext.sql("select name.name,name.age,score.score from name,score where name.name = score.name")
  20. result.show()
  21. sc.stop()

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/693326
推荐阅读
相关标签
  

闽ICP备14008679号