Hive-DML

数据操作语言(Data manipulation language),主要是数据库增删改三种操作,DML包括:INSERT插入、UPDATE新、DELETE删除。

  • Load

在将数据加载到表中时,Hive不会进行任何转换。加载操作是将数据文件移动到与Hive表对应的位置的纯复制或移动操作。
语法结构:

LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO
TABLE tablename [PARTITION (partcol=val1, partcol=val2...)]

说明:

  1. filepath
    相对路径,如:project/data1
    绝对路径,如: /user/hive/project/data1
    完整URL,如:hdfs://namenode:9000/user/hive/project/data1
    filepath可以引用一个文件(在这种情况下,Hive将文件移动到
    表中),或者它可以是一个目录(在这种情况下,Hive将把该目录
    的所有文件移动到表中)
  2. Local
    如果指定了Local,load命令将在本地linux系统中查找文件路径;
    load命令会将filepath中的文件复制到目标文件系统中。目标文件
    系统由表的位置属性决定,被复制的数据文件移动到表的数据对应
    的位置。
  3. OVERWRITE
    如果使用了OVERWRITE关键字,则目标表(或者分区)中的内 容会被删除,然后将filepath中指向的文件或目录中的内容添加到表/分区中。
    如果目标表(或者分区)已经有一个文件,并且文件名和filepath中的文件名冲突,那么现有的文件将会被新的文件所替代。
--加载本地
LOAD DATA LOCAL INPATH './examples/files/kv1.txt' OVERWRITE INTO TABLE pokes;
--加载HDFS数据,同时给定分区信息
LOAD DATA INPATH '/user/myname/kv2.txt' OVERWRITE INTO TABLE invites PARTITION (ds='2008-08-15');
  • Insert

Hive中insert主要是结合select查询语句使用,将查询结果插入到表中,如:

insert overwrite table stu_buck select * from student cluster by(Sno);
Multi Insert多重插入
from source_table
insert overwrite table tablename1 [partition (partcol1=val1,partcol2=v2)]
select_statement11
insert overwrite table tablename2 [partition (partcol1=val1,partcol2=v2)]
select_statement12...
create table source_table(id int, name string) row format delimited fields terminated by ',';
create table test_insert1(id int) row format delimited fields terminated by ',';
create table test_insert2(name string) row format delimited fields terminated by ',';
--多重插入
from source_table
insert overwrite table test_insert1 
select id
insert overwrite table test_insert2 
select name;
Dynamic partition inserts动态分区插入:

INSERT OVERWRITE TABLE tablename PARTITION (partcol[=val1],partcol[=val2]...)select_statement FROM from_statement
动态分区是通过位置来对应分区值的,原始表select出来的值和输出partition的值的关系仅仅是通过位置来确定的,和名字没有关系。
配置动态分区插入功能

set hive.exec.dynamic.partition=true; #是否开启动态分区功能,默认false关闭
set hive.exec.dynamic.partition.mode=nonstrict; #动态分区的模式,默认strict,表示必须制定至少一个分区为静态分区,nonstrict模式表示允许所有的分区字段都可以使用动态分区。
将dynamic_partition_table中的数据按照时间(day),插入到目标表d_p_t的相应分区中
create table dynamic_partition_table(day string, ip string) row format delimited fields terminated by ','; #创建原始表
create table d_p_t(ip string) partitioned by (month string, day string); #创建目标表
insert overwrite table d_p_t partition(month,day) select ip,substr(day,1,7) as month,day from dynamic_partition_table;

导出数据

语法结构

INSERT OVERWRITE [LOCAL] DIRECTORY directory1 SELECT ... FROM ... 
multiple inserts
FROM from_statement
INSERT OVERWRITE [LOCAL] DIRECTORY directory1 select_statement1
[INSERT OVERWRITE [LOCAL] DIRECTORY directory2 select_statement2]...

数据写入到文件系统时进行文本序列化,且每列用^A来区分,\n为换行符

insert overwrite和insert into的区别:

insert overwrite 会覆盖已经存在的数据,假如原始表使用overwrite 上述的数据,先现将原始表的数据remove,再插入新数据。
insert into 只是简单的插入,不考虑原始表的数据,直接追加到表中。最后表的数据是原始数据和新插入数据。

你可能感兴趣的:(Hive-DML)