多重插入
在将数据加载到表中时,Hive不会进行任何转换。加载操作是讲数据文件移动到与Hive表对应的位置的纯复制操作。
#创建三张表,source_table表有id,name两个字段,test_insert1表只有id字段,test_insert2表只有name字段
hive (xiaoliu)> create table source_table(id int,name string)
> row format delimited
> fields terminated by ',';
hive (xiaoliu)> create table test_insert1(id int)
> row format delimited
> fields terminated by ',';
hive (xiaoliu)> create table test_insert2(name string)
> row format delimited
> fields terminated by ',';
hive (xiaoliu)> show tables;
source_table
test_insert1
test_insert2
[xiaokang@hadoop hive_data]$ vi a.txt
1,allen
2,tom
3,jery
#将a.txt中传到source_table表中
hive (xiaoliu)> load data local inpath '/home/xiaokang/hive_data/a.txt'
> into table source_table;
hive (xiaoliu)> select * from source_table;
source_table.id source_table.name
1 allen
2 tom
3 jery
# 将source_table表的id字段插入到test_insert1表的id字段中,
# 将source_table表的name字段插入到test_insert2表的name字段中
hive (xiaoliu)> from source_table
> insert overwrite table test_insert1
> select id
> insert overwrite table test_insert2
> select name;
hive (xiaoliu)> select * from test_insert1;
test_insert1.id
1
2
3
hive (xiaoliu)> select * from test_insert2;
test_insert2.name
allen
tom
jery
动态分区插入
需求:
将dynamic_partition_table中的数据按照day属性,插入到目标表d_p_t的相应分区中。
原始表:
#是否开启动态分区功能,默认false关闭。
hive (xiaoliu)> set hive.exec.dynamic.partition=true;
#动态分区的模式,
#默认strict,表示必须指定至少一个分区为动态分区,
#nonstrict模式表示允许所有的分区字段都可以使用动态分区。
hive (xiaoliu)> set hive.exec.dynamic.partition.mode=nonstrict;
hive (xiaoliu)> create table dynamic_partition_table(day string,ip string)
> row format delimited
> fields terminated by ',';
[xiaokang@hadoop hive_data]$ vi dynamic_partition_table.txt
2020-09-15,ip1
2020-09-15,ip2
2020-10-16,ip3
2020-10-16,ip4
2020-11-17,ip1
2020-11-17,ip2
hive (xiaoliu)> load data local inpath '/home/xiaokang/hive_data/dynamic_partition_table.txt'
> into table dynamic_partition_table;
hive (xiaoliu)> select * from dynamic_partition_table;
OK
dynamic_partition_table.day dynamic_partition_table.ip
2020-09-15 ip1
2020-09-15 ip2
2020-10-16 ip3
2020-10-16 ip4
2020-11-17 ip1
2020-11-17 ip2
目标表:
hive (xiaoliu)> create table d_p_t(ip string)
> partitioned by (month string,day string);
动态插入:
substr(字符串,要分割的起始字符的位置,分割长度)
hive (xiaoliu)> insert overwrite table d_p_t partition(month,day)
> select ip,substr(day,6,2)as month,substr(day,9,2)
> from dynamic_partition_table;
hive (xiaoliu)> select * from d_p_t;
OK
d_p_t.ip d_p_t.month d_p_t.day
ip1 09 15
ip2 09 15
ip3 10 16
ip4 10 16
ip1 11 17
ip2 11 17
动态分区是通过位置来对应分区值的。原始表select出来的值和输出的partition的值的关系仅仅是通过位置来确定的,和名字并没有关系。