JSON数据源
Spark SQL可以自动推断JSON文件的元数据,并且加载其数据,创建一个DataFrame。可以使用SQLContext.read.json()方法,针对一个元素类型为String的RDD,或者是一个JSON文件。
但是要注意的是,这里使用的JSON文件与传统意义上的JSON文件是不一样的。每行都必须,也只能包含一个,单独的,自包含的,有效的JSON对象。不能让一个JSON对象分散在多行。否则会报错。
综合性复杂案例:查询成绩为80分以上的学生的基本信息与成绩信息
数据
{"name":"Leo", "score":85}
{"name":"Marry", "score":99}
{"name":"Jack", "score":74}
Java版本
public class JSONDataSource {
public static void main(String[] args) {
SparkConf conf = new SparkConf().setAppName("JSONDataSourceJava").setMaster("local");
JavaSparkContext sparkContext = new JavaSparkContext(conf);
SQLContext sqlContext = new SQLContext(sparkContext);
DataFrame studentScoreDF = sqlContext.read().json("E:\\testdata\\sparksql\\students.json");
// 针对json文件,创建DataFrame(针对json文件创建DataFrame)
// 针对学生成绩信息的DataFrame,注册临时表,查询分数大于80分的学生的姓名
// (注册临时表,针对临时表执行sql语句)
studentScoreDF.registerTempTable("student_score");
DataFrame goodStudentDF = sqlContext.sql("select * from student_score where score > 80");
goodStudentDF.show();
// (将DataFrame转换为rdd,执行transformation操作)
JavaRDD<String> goodStudentNameRDD = goodStudentDF.javaRDD().map(new Function<Row, String>() {
@Override
public String call(Row v1) throws Exception {
return v1.getString(0);
}
});
// 然后针对JavaRDD<String>,创建DataFrame
// (针对包含json串的JavaRDD,创建DataFrame)
List<String> studentInfoList = new ArrayList<String>();
studentInfoList.add("{\"name\":\"Leo\", \"age\":18}");
studentInfoList.add("{\"name\":\"Marry\", \"age\":17}");
studentInfoList.add("{\"name\":\"Jack\", \"age\":19}");
JavaRDD<String> studentInfoListRDD = sparkContext.parallelize(studentInfoList);
DataFrame studentInfoDF = sqlContext.read().json(studentInfoListRDD);
studentInfoDF.show();
// 针对学生基本信息DataFrame,注册临时表,然后查询分数大于80分的学生的基本信息
studentInfoDF.registerTempTable("student_info");
String sql = "select * from student_info where name in ( ";
List<String> goodStudentNameList = goodStudentNameRDD.collect();
for(int i = 0; i < goodStudentNameList.size(); i++) {
if(i == 0) {
sql = sql +"'" + goodStudentNameList.get(i) +"'";
}else {
sql = sql +", " +"'" + goodStudentNameList.get(i) +"'";
}
}
sql += ")";
DataFrame goodStudentInfoDF = sqlContext.sql(sql);
goodStudentDF.show();
// 然后将两份数据的DataFrame,转换为JavaPairRDD,执行join transformation
// (将DataFrame转换为JavaRDD,再map为JavaPairRDD,然后进行join)
JavaPairRDD<String, Long> goodStudentNameScoreRDD = goodStudentDF.javaRDD().mapToPair(new PairFunction<Row, String, Long>() {
@Override
public Tuple2<String, Long> call(Row row) throws Exception {
return new Tuple2<>(row.getString(0), row.getLong(1));
}
});
JavaPairRDD<String, Long> goodStudentNameAgeRDD = goodStudentInfoDF.javaRDD().mapToPair(new PairFunction<Row, String, Long>() {
@Override
public Tuple2<String, Long> call(Row row) throws Exception {
return new Tuple2<>(row.getString(1), row.getLong(0));
}
});
JavaPairRDD<String, Tuple2<Long, Long>> goodStudentInfo = goodStudentNameScoreRDD.join(goodStudentNameAgeRDD);
// 然后将封装在RDD中的好学生的全部信息,转换为一个JavaRDD<Row>的格式
// (将JavaRDD,转换为DataFrame)
JavaRDD<Row> rowRDD = goodStudentInfo.map(new Function<Tuple2<String, Tuple2<Long, Long>>, Row>() {
@Override
public Row call(Tuple2<String, Tuple2<Long, Long>> v1) throws Exception {
return RowFactory.create(v1._1.toString(), v1._2._1, v1._2._2);
}
});
// 创建一份元数据,将JavaRDD<Row>转换为DataFrame
List<StructField> fieldList = new ArrayList<StructField>();
fieldList.add(DataTypes.createStructField("name", DataTypes.StringType, true));
fieldList.add(DataTypes.createStructField("score", DataTypes.LongType, true));
fieldList.add(DataTypes.createStructField("age", DataTypes.LongType, true));
StructType structType = DataTypes.createStructType(fieldList);
DataFrame df = sqlContext.createDataFrame(rowRDD, structType);
// 将好学生的全部信息保存到一个json文件中去
// (将DataFrame中的数据保存到外部的json文件中去)
df.write().format("json").save("E:\\testdata\\sparksql\\goodStudent_java");
}
}
Scala版本
object JSONDataSource {
def main(args: Array[String]): Unit = {
val conf = new SparkConf().setMaster("local").setAppName("JSONDataSourceScala")
val sparkContext = new SparkContext(conf)
val sqlContext = new SQLContext(sparkContext)
// 针对json文件,创建DataFrame(针对json文件创建DataFrame)
val studentScore = sqlContext.read.json("E:\\testdata\\sparksql\\students.json")
// 针对学生成绩信息的DataFrame,注册临时表,查询分数大于80分的学生的姓名
// (注册临时表,针对临时表执行sql语句)
studentScore.registerTempTable("student_score")
val goodStudentScoreDF = sqlContext.sql("select * from student_score where score > 80")
goodStudentScoreDF.show()
// (将DataFrame转换为rdd,执行transformation操作)
val goodStudentName = goodStudentScoreDF.rdd.map(row => row.getAs("name").toString)
// 然后针对JavaRDD<String>,创建DataFrame
// (针对包含json串的JavaRDD,创建DataFrame)
import sqlContext.implicits._
val studentInfo = Array("{\"name\":\"Leo\", \"age\":18}", "{\"name\":\"Marry\", \"age\":17}", "{\"name\":\"Jack\", \"age\":19}")
val value = sparkContext.parallelize(studentInfo)
val studentInfoDF = sqlContext.read.json(value)
// 针对学生基本信息DataFrame,注册临时表,然后查询分数大于80分的学生的基本信息
studentInfoDF.registerTempTable("student_info")
var sql = "select * from student_info where name in ( "
val strings = goodStudentName.collect()
for(i <- 0 until strings.length) {
if(i == 0) sql = sql + "'" + strings(i) + "'"
else sql= sql + ", '" + strings(i) + "'"
}
sql = sql + ")"
val goodStudentInfoDF = sqlContext.sql(sql)
// 然后将两份数据的DataFrame,转换为JavaPairRDD,执行join transformation
// (将DataFrame转换为JavaRDD,再map为JavaPairRDD,然后进行join)
val goodStudentScoreRDD = goodStudentScoreDF.map(f => (f.getString(0), f.getLong(1)))
val goodStudentInfoRDD = goodStudentInfoDF.map(f => (f.getString(1), f.getLong(0)))
val rdd = goodStudentScoreRDD.join(goodStudentInfoRDD)
// 然后将封装在RDD中的好学生的全部信息,转换为一个JavaRDD<Row>的格式
// (将JavaRDD,转换为DataFrame)
val result = rdd.map(f => Row(f._1, f._2._1, f._2._2))
// 创建一份元数据,将JavaRDD<Row>转换为DataFrame
val structFieldList = Array(StructField("name", DataTypes.StringType, true),
StructField("score", DataTypes.LongType, true),
StructField("age", DataTypes.LongType, true))
val structType = StructType.apply(structFieldList)
val df = sqlContext.createDataFrame(result, structType)
// 将好学生的全部信息保存到一个json文件中去
// (将DataFrame中的数据保存到外部的json文件中去)
df.write.format("json").save("E:\\testdata\\sparksql\\goodStudent_scala")
}
}