Hive数据导入和导出

一、数据导入

 1、向表中装载数据(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)overwrite:表示覆盖表中已有数据,否则表示追加 
(5)into table:表示加载到哪张表 
(6)student:表示具体的表 
(7)partition:表示上传到指定分区 

加载本地文件到hive表

load data local inpath '/opt/temp/student.txt' into table test.student; 

load data local inpath '/opt/temp/student.txt' overwrite into table test.student; 

加载hdfs文件到hive表

load data inpath '/opt/temp/student.txt' into table test.student; 

load data inpath '/opt/temp/student.txt' overwrite into table test.student; 

2、查询语句向表中插入数据(Insert)

创建一张stuinfo3测试

create table test.stuinfo3 like test.stuinfo;

(1)插入1条数据

 insert into table stuinfo3 partition(pdate='2020-02-01') values('tom',30,'male');

(2)根据单张表查询结果

insert overwrite table stuinfo3 partition(pdate='2020-01-09') select name,age,gender from stuinfo where pdate='2020-01-09';

(3)插入查询多张表结果

注意:当多张表是同一张时,可以用下面的写法

from stuinfo
insert overwrite table stuinfo3 partition(pdate='2020-01-09') 
select name,age,gender where pdate='2020-01-09'
insert overwrite table stuinfo3 partition(pdate='2020-01-10') 
select name,age,gender where pdate='2020-01-10'

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

create table if not exists stuinfo4 as select * from stuinfo;

注意:As Select 的方式不支持创建分区表,且不会保留原始表的分区信息。通过create table xxx like xxxx;会保留分区信息

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

create table stuInfo(
name string,
age int,
gender string
)
partitioned by (pdate string) 
row format delimited fields terminated by ','
lines terminated by '\n'
location '/warehouse/test/stuinfo';

5、Import 数据到指定 Hive 表中 

注意:先用 export 导出后,再将数据导入,原因时Import导入的目录里必须有元数据才可以

export table test.stuinfo3 to '/test/stuinfo3_1';

create table test.stuinfo4 like stuinfo;

将/test/stuinfo3_1导入到stuinfo4

import table stuinfo4 partition(pdate='2020-01-09') 
from '/test/stuinfo3_1'

二、 数据导出 

1、 Insert 导出 

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

insert overwrite local directory '/opt/temp/hive' select * from test.stuinfo3;

在目录下会生成一个000000_0文件

000000_0内容:

(2)查询的结果格式化导出到本地 

insert overwrite local directory '/opt/temp/hive/test'
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' 
select * from stuinfo3;

000000_0内容:

(3)将查询的结果导出到 HDFS 

insert overwrite directory '/test/stuinfo3'
ROW FORMAT DELIMITED FIELDS TERMINATED BY '\t' 
select * from stuinfo3;

2、 Hadoop 命令导出到本地 

dfs -get /user/hive/warehouse/test.db/stuinfo3/pdate=2020-01-09/000000_0 /opt/temp/hive/stuinfo3

3、Export 导出到 HDFS 上 

export table test.stuinfo3 to '/test/stuinfo3_1';

4、Sqoop 导出 

后面有机会写Sqoop博客时,再补上。

发布了69 篇原创文章 · 获赞 2 · 访问量 4478

猜你喜欢

转载自blog.csdn.net/zuodaoyong/article/details/104133318