上篇文章讲了一下Hive的DDL操作,其实是跟数据库的操作很相似的,既然有DDL,那么肯定就有DML,本文主要介绍一下Hive的DML数据操作。Hive的DML操作,概括起来讲可以分为数据导入和数据导出两部分内容,下面一起来看一下吧。关注专栏《破茧成蝶——大数据篇》,查看更多相关的内容~
目录
一、数据导入
1.1 使用Load命令加载数据
1.1.1 语法
load data [local] inpath 'path_name' [overwrite] into table table_name [partition (partcol1=val1,…)];
其中,local表示从本地加载数据到hive表,如果在语句中没有local则表示从HDFS加载数据到hive表。path_name表示数据存放的位置名称。overwrite表示覆盖表中已有数据,否则表示追加。table_name表示hive表的名称。partition表示上传到指定分区。
1.1.2 示例
1、构造测试数据集,还是基于咱们之前的那个文件吧,分隔符为,,如下所示:
2、创建Hive表
create table people(id string, name string, sex string) row format delimited fields terminated by ',';
3、加载本地文件到hive表
load data local inpath '/root/files/p.txt' into table people;
4、加载hdfs上的文件到hive表
load data inpath '/xzw/files/p.txt' into table people;
5、加载数据覆盖hive表中的数据
load data inpath '/xzw/files/p.txt' overwrite into table people;
1.2 使用insert命令加载数据
1.2.1 语法
insert [into|overwrite] table table_name values(...);
insert into表示以追加数据的方式插入到表或分区,原有数据不会删除。insert overwrite表示会覆盖表或分区中已存在的数据。还需要注意的是insert不支持插入部分字段。
1.2.2 示例
1、创建一张员工的分区表,按照日期分区。
create table emp(id int, name string) partitioned by (rq string) row format delimited fields terminated by ',';
2、插入数据
insert into table emp partition(rq='202012') values(1,'xzw'),(2,'lzq');
3、insert+select插入数据
insert overwrite table emp partition(rq='202011') select id,name from emp where rq = '202012';
这里有人会发现明明使用了overwrite怎么会出现数据重复的情况?这是因为我们建的是分区表,这里只会对指定的分区进行覆盖。
4、insert多表多分区插入
from emp
insert overwrite table emp partition(rq='202011')
select id, name where rq='202012'
insert overwrite table emp partition(rq='202010')
select id, name where rq='202012';
1.3 create+select加载数据
create table emp_tmp as select * from emp;
1.4 建表时通过location来指定数据存储路径
create external table e_people(id string, name string, sex string) row format delimited fields terminated by ',' location '/xzw/files';
1.5 使用Import命令将数据导入到Hive中
Import命令适用于使用export命令导出的数据,语法格式如下:
import table table_name [partition(...)] from 'export_data_path';
二、数据导出
2.1 使用Insert命令导出数据
insert overwrite local directory '/root/files/emp_data' ROW FORMAT DELIMITED FIELDS TERMINATED BY ',' select * from emp;
上述命令如果将local去掉的话,就是导出数据到HDFS上的操作。
2.2 使用HDFS的命令获取数据
找到对应数据在HDFS上的存储路径,使用HDFS的get命令将需要的数据get到本地。
2.3 使用hive命令导出数据
使用hive -e/-f导出数据,具体可以参考我的另外一篇博客:《Hive通过-f调用sql文件并进行传参》。
2.4 使用export导出数据
export table people to '/xzw/files/people';
2.5 使用Sqoop语句导出
Sqoop如何导出数据后续会专门讲解,这里暂不多说【虚位以待】。
三、清除数据
使用如下命令清除hive表的数据,这里需要注意的是,truncate命令只能清除内部表的数据,外部表的数据是没法清除的。
truncate table table_name;
OK~Hive的DML数据操作到这里就接近尾声了,你们在此过程中遇到了什么问题,欢迎留言,让我看看你们都遇到了哪些问题~