文章目录
Hive中DML数据操作语言
1、数据导入
1.1 向表中装载数据
load data [local] inpath '数据的path' [overwrite] into table student [partition (partcol1=val1,…)];
-
local:表示从本地加载数据到hive表;否则从HDFS加载数据到hive表
-
overwrite:表示覆盖表中已有数据,否则表示追加
-
partition:表示上传到指定分区
1.创建表
create table student(id int, name string) row format delimited fields terminated by '\t';
2.加载本地文件到hive
load data local inpath '/opt/module/hive/datas/student.txt' into table student;
3.加载hdfs文件到hive
dfs -put /opt/module/hive/datas/student.txt /user/hadoop;
load data inpath '/user/atguigu/student.txt' into table student;
4.加载数据覆盖表中已有的数据
load data local inpath '/home/hadoop/test/student.txt' overwrite into table student;
1.2 通过查询语句向表中插入数据(Insert)
1.创建表
create table student2(id int, name string) row format delimited fields terminated by '\t';
2.插入数据
insert into table student2 values(1,'zz')(2,'tt');
3.根据查询内容插入数据
insert overwrite table student2 select id,name from studnet where id=100;
insert overwrite:会覆盖表中已存在的数据
1.3 查询语句中创建表并加载数据(As Select)
create table if not exists student3 as select id, name from student;
1.4 创建表时通过Location指定加载数据路径
1.上传数据到hdfs
hadoop fs -mkdir -p /student4;
hadoop fs -put student.txt /student4
2.创建表时通过Location指定加载数据路径
create external table if not exists student4(
id int,
name string
)
row format delimited fields terminated by '\t'
location '/student4';
3.查询数据
select * from student4;
1.5 Import数据到指定Hive表中
先用export导出后,再将数据导入。并且因为export导出的数据里面包含了元数据,因此import要导入的表不可以存在,否则报错。
import table student6 from '/user/hive/warehouse/student';
2、数据导出
2.1 Insert导出
1.将查询的结果导出到本地
insert overwrite local directory '/opt/module/hive/datas/export/student' select * from student;
2.将查询的结果格式化导出到本地
insert overwrite local directory '/opt/module/hive/datas/export/student'
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'
select * from student;
3.将查询的结果导出到HDFS
insert overwrite directory '/user/student2'
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t'
select * from student;
insert 导出,导出的目录不用自己提前创建,hive会帮我们自动创建,但是由于是overwrite,所以导出路径一定要写具体,否则很可能会误删数据。
2.2 Hadoop命令导出到本地
dfs -get /user/hive/warehouse/student/student.txt /opt/module/hive/datas/export/student3.txt;
2.3 Hive Shell命令导出
bin/hive -e 'select * from default.student;' >
/opt/module/hive/datas/export/student4.txt;
2.4 Export导出到HDFS
export table default.student to '/user/hive/warehouse/export/student';