Spark读写Hive
文章目录
- Spark读写Hive
- (一)配置本地域名映射
- (二)创建Hive表
- (三)IDEA中编写Spark代码读取Hive数据
- (四)IDEA中编写Spark代码写入数据到Hive
(一)配置本地域名映射
1.查看集群配置
在Linux查看hosts文件
vi /etc/hosts
2.将Linux中查看到的域名配置到Windows本地的hosts文件中
C:\Windows\System32\drivers\etc\hosts
注意:此文件有权限限制,不能直接修改,修改的办法:搜索记事本,使用管理员身份打开记事本,然后从记事本打开hosts文件,然后再修改
(二)创建Hive表
1.要保证Hadoop集群是正常启动的
master和slave1节点上要能看到namenode守护进程
2.本地编辑一个t_student.txt文件
vi ~/t_student.txt
写入数据
1,zhangsan,male,18
2,lisi,female,20
保存并退出
3.上传文件到HDFS根目录
hdfs dfs -put ~/.t_student.txt /
4.进入hive
hive
5.创建数据库
--创建数据库
create database sparktest;--使用数据库
use spark test;--创建表
create table student(id int, name string, gender string, age int) row format delimited fields terminated by "," stored as textfile ;
--row format delimited fields terminated by "," 指定列分隔符为英文的逗号
--stored as textfile 存储为文本文件--加载数据
load data inpath "/t_student.txt" overwrite into table student;
--load data加载数据
--inpath 指定路径
--"/t_student.txt" 具体的HDFS的路径
--overwrite into 覆盖写入
--table 指定表
--student 具体的表名
当执行完load data操作后,hdfs根目录下的t_student.txt文件会被移动到hive的数据目录下
6.查看数据
select * from student;
(三)IDEA中编写Spark代码读取Hive数据
1.环境配置
将hive-site.xml(路径: H I V E H O M E / c o n f )、 c o r e − s i t e . x m l 、 h d f s − s i t e . x m l (路径: HIVE_HOME/conf)、core-site.xml、hdfs-site.xml(路径: HIVEHOME/conf)、core−site.xml、hdfs−site.xml(路径:HADOOP_HOME/etc/hadoop)复制到IDEA项目的resource目录下
2.编写代码
import org.apache.spark.sql.SparkSession/*** 使用DataFrame读取Hive表*/
object spark_read_hive {def main(args: Array[String]): Unit = {//指定本地用户为rootSystem.setProperty("HADOOP_USER_NAME","root")//创建SparkSession,作用:连接Sparkval spark = SparkSession.builder().master("local[*]") //指定运行的方式哦.appName("spark_read_hive") //程序的名字.enableHiveSupport() //开启Hive支持.getOrCreate()//查询Hive表//sparktest.student 数据库名.表名val df = spark.sql("select * from student");df.show()}
}
(四)IDEA中编写Spark代码写入数据到Hive
import org.apache.spark.sql.{Row, SparkSession}
import org.apache.spark.sql.types.{IntegerType, StringType, StructField, StructType}/*** 使用DataFrame写入数据到Hive*/
object spark_write_hive {def main(args: Array[String]): Unit = {//指定本地用户为rootSystem.setProperty("HADOOP_USER_NAME", "root")//创建SparkSession,作用:连接Sparkval spark = SparkSession.builder().master("local[*]") //指定运行的方式哦.appName("spark_write_hive") //程序的名字.enableHiveSupport() //开启Hive支持.getOrCreate()//创建DataFrame//1. 创建schemaval schema = StructType(List(StructField("id", IntegerType, true),StructField("name", StringType, true),StructField("gender", StringType, true),StructField("age", IntegerType, true)))//2. 创建rows//2.1 创建RDDval dataRDD = spark.sparkContext.parallelize(Array(Array(3, "张三", "男", 18),Array(4, "李四", "女", 20)))//2.2 创建rowsval rows = dataRDD.map(x => Row(x(0), x(1), x(2), x(3)))//3. 合并val df = spark.createDataFrame(rows,schema)//在控制台显示DataFrame的内容//df.show()//写入Hive//方法一:通过临时表使用SQL语句添加数据df.createOrReplaceTempView("tmpTable")spark.sql("insert into student select * from tmpTable")}
}