Hive, 大数据

hive-05 DML 数据操作

数据导入 Load

向表中装载数据(Load)

load data [local] inpath '数据的path' [overwrite] into table table_name [partition (partcol=val1,...)];
  • load data 表示加载数据
  • local 表示从本地加载数据到hive表,否则从HDFS加载数据到hive表
    • hdfs加载数据 实质是mv操作
      • hadoop修改namenode元数据,物理文件地址不变
    • 本地文件是copy操作
  • inpath 表示加载数据的路径
  • overwrite 表示覆盖表中已有数据,否则表示追加
  • into table 表示加载到哪张表
  • table_name 表示具体的表
  • partition表示上传到指定分区

insert 语句插入数据会走mr任务 会修改元数据中TABLE_PARAMS表 numFiles和numRows数据

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

  • 创建一张表
create table student2(
    id int, 
    name string
) 
row format delimited 
fields terminated by '\t';

基本插入数据

insert into table student2 values (1, 'tom'), (2, 'lili');
  • 基本模式插入(根据单张表查询结果)
    • insert into 以追加的方式插入数据到表或分区,原有数据不会删除
    • insert overwrite 会覆盖表中已存在的数据
    • insert不支持插入部分字段
insert overwrite table student2
select id, name from student where month='202101'

多表(多分区)插入模式(根据多张表查询结果)

from student
insert overwrite table student partition(month='202101')
select id, name where month='202103'
insert overwrite table student partition(month='202102')
select id, name where month='202103';

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

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

create table if not exixts student2
as select id, name from student;

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

create table student(id int, name string)
location "/test/student/";

Import数据到指定Hive表中

先用export导出后,再将数据导入

  • 空表或者导入不存在的表可以导入成功
import table student2 from '/user/hive/warehouse/export/student';

数据导出

insert导出

  • 将查询的结果导出到本地
insert overwrite local directory '/home/test_data/student' select * from student;

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

insert overwrite local directory '/home/test_data/student' 
row format delimited fields terminated by '\t'
select * from student;
  • 将查询的结果导出到hdfs上
    • 没有local
insert overwrite directory '/test/export_data/student2'
row format delimited
fields terminated by '\t'
select * from student;

hadoop命令导出到本地

dfs -get /user/hive/warehouse/student/student.txt /home/data/student.txt

hive shell命令导出

bin/hive -e 'select * from default.student;' > /home/data/student1.txt

export 导出到hdfs上

  • export 和hive主要用于两个hadoop平台集群之间hive表迁移
  • 导出文件会增加_metadata文件夹
export table dafault.student to '/test/export_data/student3';

sqoop导出

清除表中数据 truncate

  • truncate只能删除管理表,不能删除外部表中数据
truncate table student;