SparkSQL提供了HiveContext类,它继承与SQLContext,因此不仅具有SQLContext的功能,而且还可以直接操作hive表中的数据,以及执行hive的sql语句。
在上篇中,使用了json数据来表示表数据,然后后对表数据进行join操作,需要在javaRDD和DataFrame中转来转去,稍显繁琐。
本篇继续上一个问题,使用SaprkSQL对同样的两张表数据进行过滤并join操作。
思路如下:
首先,将本地数据直接导入到hive表中(也可以创建外部表),然后直接在SparkSQL中执行sql语句,对两张表数据进行过滤和join操作,最后将得到的结果保存到hive表中。
具体代码如下:
创建HiveContext对象
SparkConf conf = new SparkConf().setAppName("DataFrameWithHive");
JavaSparkContext sc = new JavaSparkContext(conf);
HiveContext hc = new HiveContext(sc.sc());
直接利用HiveContext来创建hive表。并且加载外部数据源到表中
//读取hive中的表数据,映射为spark中的DataFrame
hc.sql("drop table if exists studentInfo");
hc.sql("create table if not exists studentInfo(name string,age int,area string)");
//将本地数据导入到studentInfo hive表中
hc.sql("load data local inpath '/cqt/testdata/students/studentInfo.txt' into table studentInfo");
//同样,将将学生分数表的数据也导入到hive表中
hc.sql("drop table if exists studentScore");
hc.sql("create table if not exists studentScore(name string,score int)");
hc.sql("load data local inpath '/cqt/testdata/students/studentScore.txt' into table studentScore");
得到两张映射的表studentInfo和studentScore,然后对这两张表数据直接执行正常的sql语句即可
//直接对表数据进行sql 的join操作
DataFrame joinedDF = hc.sql("select si.name ,si.age, si.area, ss.score from studentInfo si join studentScore ss on si.name=ss.name where ss.score>80");
然后将得到的结果保存到hive表中
//将得到的结果,存放到hive表中
hc.sql("drop table if exists joinedStudent");
//DataFrame中已经包含了元数据信息,无需创建表数据元信息,直接调用DataFrame的save方法即可
joinedDF.saveAsTable("joinedStudent");
然后使用maven打包,将jar包放在集群的某台节点上,通过spark-submit提交应用!
注意:如果配置了hive的元数据信息保存在mysql中,需要执行下面操作
1、需要将hive-site.xml文件放在spark的conf目录下
2、将mysql的驱动jar包也拷贝一份到spark的lib目录中
或者在执行spark-submit时,通过–files和–driver-class-path来指定配置文件和mysql驱动包的路径。