Hive(五)之 Hive数据操作DML语言

5.DML数据操作

5.1 数据导入

5.1.1 向表中装载数据(Load)

  • 语法
hive> load data [local] inpath '路径' [overwrite] into table 表名 [partition (partcol1=val1,)];

(1)load data:表示加载数据

(2)local:表示从本地加载数据到hive表;否则从HDFS加载数据到hive表

(3)inpath:表示加载数据的路径

(4)overwrite:表示覆盖表中已有数据,否则表示追加

(5)into table:表示加载到哪张表

(6)表名:表示具体的表

(7)partition:表示上传到指定分区

5.1.2 通过查询语句向表中插入数据(Insert)

  • 案例

基本插入

insert into table  student partition(month='201709') values(1,'wangwu');
insert overwrite table student partition(month='201708') select id, name from student where month='201709';

多插入

from dept_partition
              insert overwrite table dept_partition partition(month='201707')
              select deptno,dname,loc where month='201709'
              insert overwrite table dept_partition partition(month='201706')
              select deptno,dname,loc  where month='201709';

5.1.3 查询语句中创建表并加载数据(As Select)

根据查询结果创建表(查询的结果会添加到新创建的表中)

create table if not exists student3 as select id, name from student;

5.1.4 创建表时通过Location指定加载数据路径

创建表,并指定在hdfs上的位置

create table if not exists student5(
id int, name string)
row format delimited fields terminated by '\t'
location '/user/hive/warehouse/student5';

上传数据到hdfs上

dfs -put /opt/datas/student.txt /opt/hive/warehouse/student5;

5.1.5 Import数据到指定Hive表中

注意:先用export导出后,再将数据导入。

import table student2 partition(month='201709') from '/opt/hive/warehouse/export/student';

5.2 数据导出

5.2.1 Insert导出

1.将查询的结果导出到本地

insert overwrite local directory '/opt/datas' select * from dept_partition;

image-20200918084842193

image-20200918085621207

2.将查询的结果格式化导出到本地

insert overwrite local directory '/opt/datas/dept1'
row format delimited
fields terminated by '|'
select * from dept_partition;

image-20200918085644479

3.将查询的结果导出到HDFS上(没有local)

insert overwrite directory '/opt/datas/dept'
row format delimited
fields terminated by '|'
select * from dept_partition;

image-20200918090048512

5.2.2 Hadoop命令导出到本地

dfs -get /opt/hive/warehouse/employee/employee.txt /opt/datas/dept2/dept.txt;

5.2.3 Hive Shell 命令导出

基本语法:(hive -f/-e 执行语句或者脚本 > file)

hive -e 'select * from hivetest.dept_partition;' > /opt/datas/dept3/dept.txt;

注意:需要在shell窗口执行,需要库名.表名,需要本地文件夹存在。

image-20200918091555443

5.2.4 Export导出到HDFS上

export table hivetest.dept_partition to '/opt/datas/dept2';

5.2.5 Sqoop导出

后续

5.3 清除表中数据(Truncate)

注意:Truncate只能删除管理表,不能删除外部表中数据

truncate table student;

猜你喜欢

转载自blog.csdn.net/zmzdmx/article/details/108658818