Hive(四)【DML 数据导入导出】

一.数据导入

1.1 【load】--向数据中装载数据

load data [local] inpath '数据的路径' [overwrite] into table 表名 [partition('属性'='值',...)];
--load data:表示加载数据
--local:从本地加载数据到hive表;否则从hdfs上加载数据到hive表
--inpath:待加载数据的路径
--overwrite:覆盖表已有数据;否则追加
--into 表名:加载到那张表
--partition:加载进指定分区
案例

1.加载本地文件到hive表

load data local inpath '/opt/moudle/hive/datas/student.txt' into table student;

2.加载hdfs文件到hive表

load data inpath '/user/student.txt' into table student;

3.加载hdfs数据且覆盖student表中数据

load data inpath '/user/student2.txt' overwrite into table student;

1.2 【insert】--查询语句向表中插入数据

insert into/overwrite table 表名 
select id,name from student where id<1006;
--into:追加
--overwrite:覆写

注意:insert不支持插入部分字段,并且后边跟select语句时,select之前不能加as,加了as会报错,一定要跟创建表的as select区分开

案例

1.基本模式插入几条数据

insert into table student values(1004,'张三'),(1005,'王五');

2.根据查询结果插入数据,覆盖原数据

insert overwrite table student2 select id,name from student where id < 1006;

1.3 【as select】--查询语句中创建表且加载数据

案例
create table if not exists 表2 as select id,name from 表1; 

1.4 【location】--创建表指定location加载数据

案例
create table if not exists 表名(
字段1 类型,
字段2 类型,
...
)
row format delimited fields terminated by '\t'
location '/student';

1.5 【import】--import数据到Hive中

案例
import table 表名 from '/user/hive/warehouse/export/student';

注意:必须是通过export导出的数据,才能通过import导入。因为export导出的数据包含元数据,要求import导入的表不能存在;

1.6 【sqoop】--工具导入

二.数据导出

1.1【insert】--insert导出

案例

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

insert overwrite local directory '/opt/module/hive/datas/export/student'
row format delimited fields terminated by '\t'
select * from student;

2.将查询结果导出到hdfs(没有local)

insert overwrite directory'/user/student2'
row format delimited fields terminated by '\t'
select * from student2;

注意注意注意!:insert导出的目录hive会自动创建,所以导出目录要写不存在的目录,否则overwrite很容易误删数据

1.2【hadoop fs -get】--hadoop命令导出

案例

1.先查看表信息

desc formatted 表名;

2.根据表信息找到表在hdfs数据的存储位置,再下载到本地

hadoop fs -get 'hdfs数据存储路径'  '本地路径';
hadoop fs -get '/user/hive/warehouse/student/student.txt' '/opt/export/student.txt';

1.3【hive的shell命令】

在脚本可以通过此方式导出数据到文件

案例

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

bin/hive -e 'select*from student;' > /opt/module/hive/data/export/student4.txt

1.4【export】--export导出到hdfs

export和import主要用于两个Hadoop平台集群之间Hive表迁移,不能直接导出的本地

案例
export table default.student to '/user/hive/warehouse/export/student';

1.5【sqoop】--工具导出

posted @ 2020-06-28 18:03  来自遥远的水星  阅读(252)  评论(0编辑  收藏  举报