前言
本文隶属于专栏《1000个问题搞定大数据技术体系》,该专栏为笔者原创,引用请注明来源,不足和错误之处请在评论区帮忙指出,谢谢!
本专栏目录结构和参考文献请见1000个问题搞定大数据技术体系
正文
Hive数据导入
向表中加载数据(load)
- 语法
hive> load data [local] inpath 'dataPath' overwrite | into table student [partition (partcol1=val1,…)];
load data: 表示加载数据
local: 表示从本地加载数据到hive表;否则从HDFS加载数据到hive表
inpath: 表示加载数据的路径
overwrite: 表示覆盖表中已有数据,否则表示追加
into table: 表示加载到哪张表
student: 表示具体的表
partition: 表示上传到指定分区
例如:
--普通表:
load data local inpath '/opt/bigdata/data/person.txt' into table person
--分区表:
load data local inpath '/opt/bigdata/data/person.txt' into table person partition(dt="20210620")
通过查询语句向表中插入数据(insert)
-
从指定的表中查询数据结果数据然后插入到目标表中
-
语法
insert into/overwrite table tableName select xxxx from tableName
insert into table student_partition1 partition(dt="2021-06-20") select * from student1;
查询语句中创建表并加载数据(as select)
-
在查询语句时先创建表,然后进行数据加载
-
语法
create table if not exists tableName as select id, name from tableName;
创建表时通过 location 指定加载数据路径
- 创建表,并指定在hdfs上的位置
create table if not exists student1(
id int,
name string)
row format delimited fields terminated by '\t'
location '/user/hive/warehouse/student1';
- 上传数据文件到hdfs上对应的目录中
hdfs dfs -put /opt/student1.txt /user/hive/warehouse/student1
Import 数据到指定 Hive 表中
注意:先用 export 导出后,再将数据导入。
create table student2 like student1;
export table student1 to '/export/student1';
import table student2 from '/export/student1';
Hive 数据导出
insert 导出
- 1、将查询的结果导出到本地
insert overwrite local directory '/opt/bigdata/export/student'
select * from student;
- 2、将查询的结果格式化导出到本地
insert overwrite local directory '/opt/bigdata/export/student'
row format delimited fields terminated by ','
select * from student;
- 3、将查询的结果导出到HDFS上==(没有local)==
insert overwrite directory '/export/student'
row format delimited fields terminated by ','
select * from student;
Hadoop 命令导出到本地
hdfs dfs -get /user/hive/warehouse/student/student.txt /opt/bigdata/data
Hive Shell 命令导出
- 基本语法:
hive -e "sql语句" > file
hive -f sql文件 > file
- 举例:
bin/hive -e 'select * from default.student;' > /opt/bigdata/data/student1.txt
export 导出到 HDFS 上
export table default.student to
'/user/hive/warehouse/export/student1';