Hive DML 数据操作
一、数据导入
1.1 向表中加载数据
-
语法
load data [local] inpath '数据的路径' [overwrite] into table table_name [partition (partcol1=val1,…)];load data:表示加载数据。local:表示从本地加载数据到Hive表;否则从HDFS中加载数据到Hive表。inpath:表示加载数据的路径。overwrite:表示覆盖表中已有的数据,否则表示追加。into table:表示加载到那张表。partition:表示上传到指定分区。
-
例子
# 创建一张表 create table student(id string, name string) row format delimited fields terminated by '\t'; # 加载本地文件到Hive load data local inpath '/opt/module/hive/datas/student.txt' into table default.student; # 加载HDFS文件到Hive dfs -put /opt/module/hive/datas/student.txt /user/root/ load data inpath '/user/root/student.txt' into table default.student; # 加载数据覆盖表中的数据 load data inpath 'user/root/student.txt' overwrite into table default.student;
1.2 通过查询语句向表中插入数据
create table student_par(id int, name string)
row format delimited fields terminated by '\t';
insert into table student_par
values(1,'zhangsan'),(2,'wangwu');
insert overwrite table student_par
select id,name from student where month='202108'
# insert into:追加
# insert overwrite :覆盖
# 注意insert不支持插入部分字段
# 多表(多分区)插入模式
from student
insert overwrite table student partition(month='201707')
select id, name where month='201709'
insert overwrite table student partition(month='201706')
select id, name where month='201709';
1.3 查询语句中创建表并加载数据
create table if not exists student0
as select id,name from student;
1.4 创建表时通过location指定加载数据路径
# 上传数据
dfs -mkdir /data/student;
dfs -put /opt/module/hive/datas/student.txt /data/student;
# 创建外部表,并指定数据位置
create external table if not exists student(
id int, name string)
row format delimited fields terminated by '\t'
location '/data/student';
# 查询数据
select * from student;
1.5 Import数据导指定Hive表中
# 注意先用export导出后,再将数据导入
import table student2 from '/user/hive/warehouse/export/student';
二、数据导出
2.1 Insert导出
# 将查询的结果导出到本地
insert overwrite local directory '/opt/module/hive/datas/export/student'
select * from student;
# 将查询的结果格式化导出到本地
insert overwrite local directory '/opt/module/hive/datas/export/student1'
row format delimited fields terminated by '\t'
select * from student;
# 将查询的结果导出到HDFS上,没有local
insert overwrite directory '/user/root/student'
row format delimited fields terminated by '\t'
select * from student;
2.2 Hadoop命令导出到本地
dfs -get /user/hive/warehouse/student/student.txt /opt/tool/data/export/student.txt;
2.3 Hive Shell 命令导出
hive -e 'select * from default.student;' > /opt/tool/data/export/student1.txt
2.4 Export导出到HDFS上
export table default.student to '/user/hive/warehouse/export/student';
export和import主要用于两个Hadoop平台集群之间Hive表迁移
2.5 清除表中的数据—Truncate
truncate table student;
truncate只能删除管理表,不能删除外部表的数据。
本文详细介绍了Hive中的数据导入(包括本地和HDFS加载,覆盖与追加选项),查询时插入数据(创建表、多分区插入),以及数据导出的各种方式,如Insert导出、Hadoop命令和Export工具。重点讲解了如何使用Hive DML进行高效的数据操作和迁移。
218

被折叠的 条评论
为什么被折叠?



