DML 数据操作
1. 数据导入
1.1 向表中Load
数据
- 语法
load data [local] inpath '数据的 path' [overwrite] into table student [partition (partcol1=val1,…)];
load data
: 表示加载数据local
: 表示从本地加载数据到hive
表;否则从 HDFS 加载数据到hive
表inpath
: 表示加载数据的路径overwrite
: 表示覆盖表中已有数据,否则表示追加into table
: 表示加载到哪张表student
: 表示具体的表partition
: 表示上传到指定分区
- 案例
- 加载本地文件到
hive
// 创建表 create table if not exists student ( id string, name string ) row format delimited fields terminated by '\t'; // 加载本地文件到hive load data local inpath '/opt/module/hive-3.1.2/datas/student.txt' into table student;
- 加载 HDFS 上的数据到
hive
// 加载HDFS文件到hive (会将hdfs加载路径的文件 移动 到hive在hdfs的工作目录下 /user/hive/warehouse/table_name) load data inpath '/student/student.txt' into table student;
- 加载本地文件到
1.2 向表中Insert
数据
- 创建一张表
create table if not exists student2 ( id string, name string ) row format delimited fields terminated by '\t';
- 插入数据
insert into
: 以追加数据的方式插入到表或分区,原有数据不会删除insert overwrite
: 会覆盖表中已存在的数据insert
不支持插入部分字段,会进行MR
// 插入数据 (mr) insert into table student2 values ('1', 'wangwu'), ('2', 'zhaoliu'); // 根据单张表查询结果插入 insert overwrite table student2 select id, name from student;
1.3 根据查询结果As Select
到表中
// 根据查询结果创建表
create table if not exists student3
as select id, name from student2;
1.4 创建表时通过 Location
指定加载数据路径
- 上传数据到
hdfs
上dfs -put /opt/module/hive-3.1.2/datas/student.txt /student;
- 创建表,并指定在
hdfs
上的位置create table if not exists student4 ( id int, name string ) row format delimited fields terminated by '\t' location '/student';
1.5 Import
数据到表中
注意:先用 export
导出后,再将数据导入
// import数据到指定hive表中
import table student5
from '/user/hive/warehouse/export/student';
2. 数据导出
2.1 Insert
导出
-
将查询的结果导出到本地
insert overwrite local directory '/opt/module/hive-3.1.2/datas/export/student' select * from student;
-
将查询的结果格式化导出到本地
insert overwrite local directory '/opt/module/hive-3.1.2/datas/export/student1' row format delimited fields terminated by '\t' select * from student;
-
将查询的结果导出到
HDFS
上insert overwrite directory '/user/codecat/student' row format delimited fields terminated by '\t' select * from student;
2.2 Export
导出到 HDFS
上
export table student
to '/user/hive/warehouse/export/student';
export
和 import
主要用于两个 Hadoop 平台集群之间 Hive 表迁移
3. 清除表中数据
truncate table student;
Truncate
只能删除管理表,不能删除外部表中数据