Hive的DML数据操作
数据的导入
向表中装载数据(load)::
语法
hive>load data [local] inpath ‘/opt/module/datas/student.txt’ [overwrite] into table student [partition (partcol1=val1,…)];
(1)load data:表示加载数据
(2)local:表示从本地加载数据到hive表;否则从HDFS加载数据到hive表
(3)inpath:表示加载数据的路径
(4)into table:表示加载到哪张表
(5)student:表示具体的表
(6)overwrite:表示覆盖表中已有数据,否则表示追加
(7)partition:表示上传到指定分区
实例:
创建一张表
hive (hive)> create table student(id string, name string) row format delimited fields terminated by '\t';
加载本地文件到hive
hive (hive)> load data local inpath '/opt/datas/student.txt' into table student;
加载HDFS上的数据(去掉local即可)
hive (hive)> dfs -put /opt/datas/student.txt /user
hive (hive)> load data inpath /user/student.txt into table student;
加载数据覆盖表中已有的数据(overwrite关键词)
load data inpath '/user/student.txt' overwrite into table student;
通过查询语句向表中插入数据(insert)
创建一张分区表
hive (hive)> create table student2(id string, name string) partitioned by (month string) row format delimited fields terminated by '\t';
插入数据
hive (hive)> insert into table student2 partition(month='201811') values('100','zyd');
基本模式插入(根据单张表查询结果)
hive (hive)> insert overwrite table student2 partition(month='201708') select id,name from student where month='201811';
多插入模式(根据多张表查询结果)
hive (hive)> from student2
> insert overwrite table student2 partition(month='201812')
> select id, name
> insert overwrite table student2 partition(month='201901')
> select id,name;
查询语句中创建表并加载数据(as关键字)
hive (hive)> create table student3 as select id, name from student2;
创建表时通过Location指定加载数据路径(指定在hdfs上的位置)
create table student6(
id int, name string
)
row format delimited fields terminated by '\t'
location '/user/student.txt';
数据的导出
Insert导出
1)将查询的结果导出到本地
insert overwrite local directory '/opt/datas/export' select * from student;
但是导出的数据格式
001^Azhangshan
1002^Alishi
1003^Azhaoliu
1001^Azhangshan
1002^Alishi
1003^Azhaoliu
-
将查询的结果格式化导出到本地
insert overwrite local directory ‘/opt/datas/export/student1’
row format delimited fields terminated by ‘\t’ collection items terminated by ‘\n’
select * from student;
3)将查询的结果导出到HDFS上(没有local)
insert overwrite directory '/user/student'
row format delimited fields terminated by '\t' collection items terminated by '\n'
select * from student;
Hadoop命令导出到本地
hive (default)> dfs -get /user/hive/warehouse/student/month=201709/000000_0 /opt/module/datas/export/student3.txt;
Hive Shell 命令导出到本地
[root@note03 export]# hive -e 'select * from hive.student' > student.txt
Export导出到HDFS上
hive (hive)> export table student to '/user/student2';
数据导入 import数据到指定的hive表中(先用export导出后,再将数据导入)
hive (hive)> import table student2 partition(month='201512')from '/user/student2';
FAILED: SemanticException [Error 10006]: Partition not found - Specified partition not found in import directory
导出的数据必须要有分区,导入的表分区不能存在
清除表中数据(Truncate)
hive (hive)> truncate table student;
OK
Time taken: 0.331 seconds
hive (hive)> select * from student;
OK
student.id student.name
注意:Truncate只能删除管理表,不能删除外部表中数据