Spark - 使用SparkSQL将数据写入Hive表详解3(使用SparkSQL语句)
作者:hangge | 2024-07-19 08:34
在之前的文章中,我介绍了如何在 SparkSQL 中集成 Hive 并查询 Hive 表中的数据(点击查看)。实际工作中,我们不仅需要查询数据并计算结果,还希望将结果数据写入 Hive 表中。通常来说,向 Hive 表中写入数据有如下 3 种方法。
(2)然后给表中添加一些初始数据:
(2)查看这个表的数据也是都有的:
- 第一种:使用 inserInto() 方法。
- 第二种:使用 saveAsTable() 方法。
- 第三种:使用 SparkSQL 语句。
其中第二种不推荐使用,最常用的是第三种,用起来比较方便。我在前文介绍了前面两个方法,本文接着介绍最后一种方法,即使用 SparkSQL 语句。
三、使用 SparkSQL 语句写入 Hive 表数据
1,准备工作
(1)首先我们在 hive 中创建一张 student 表:
create table student (
id int,
stu_name string,
stu_birthday date,
online boolean
)
row format delimited
fields terminated by '\t'
lines terminated by '\n';
(2)然后给表中添加一些初始数据:
load data local inpath '/usr/local/student.txt' into table student;
2,编写代码
(1)首先我们的项目要做好 Hive 的集成配置,具体可以参考我之前写的文章:
(2)接着我们编写测试代码,用于通过 SparkSQL 从 Hive 表 student 查询数据并将其写入到另一个 Hive 表 student_bak。这里又分两种情况:
- 表不存在,使用 create table as select
import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession
object SparkSQLWriteHive_3 {
def main(args: Array[String]): Unit = {
val conf = new SparkConf()
.setMaster("local")
//获取SparkSession,为了操作SparkSQL
val sparkSession = SparkSession
.builder()
.appName("SparkSQLWriteHive_3")
.config(conf)
//开启对Hive的支持,支持连接Hive的MetaStore、Hive的序列化、Hive的自定义函数
.enableHiveSupport()
.getOrCreate()
import sparkSession.sql
//3:SparkSQL语句(表不存在)
sql(
"""
|create table student_bak
|as
|select * from student
|""".stripMargin)
sparkSession.stop()
}
}
- 表存在,使用 insert into select
import org.apache.spark.SparkConf
import org.apache.spark.sql.SparkSession
object SparkSQLWriteHive_3 {
def main(args: Array[String]): Unit = {
val conf = new SparkConf()
.setMaster("local")
//获取SparkSession,为了操作SparkSQL
val sparkSession = SparkSession
.builder()
.appName("SparkSQLWriteHive_3")
.config(conf)
//开启对Hive的支持,支持连接Hive的MetaStore、Hive的序列化、Hive的自定义函数
.enableHiveSupport()
.getOrCreate()
import sparkSession.sql
//3:SparkSQL语句(表存在)
sql(
"""
|create table if not exists student_bak(
| id int,
| name string,
| sub string,
| score int
|)using hive
| OPTIONS(
| fileFormat 'textfile',
| fieldDelim ','
| )
|""".stripMargin)
sql(
"""
|insert into student_bak
|select * from student
|""".stripMargin)
sparkSession.stop()
}
}
3,运行测试
(1)上面代码运行后,我们可以到到 Hive 中查看目标表的详细信息:
show create table student_bak;
(2)查看这个表的数据也是都有的:
select * from student_bak;
全部评论(0)