hive--新增字段,数据重跑坑

场景:

当我们建表完成并按照时间分区插入数据,之后我们发现需要增加一个字段。

办法:

我们首先想到的是先在表中增加字段。

     1)alter table table_name add columns(new_attr string);

然后重跑数据

     2)insert overwrite table table_name partition(pattr='20181029')

这种后果是,我们新增的字段new_attr的值为空。

解决办法:

    在insert之前,一定记得删该分区

    1.5)alter table table_name drop partition(pattr='20181029');

补充:(最近发现另一种可以解决同样问题的方法)

      alter table table_name replace columns(, , , , ,new_attr string) cascade;

实例:

原始数据,

hive> select *from xunying where inc_day='1123'
    > ;
OK
1    12.100000000000000000    1123
1    -12.100000000000000000    1123
2    15.528450000000000000    1123
2    -15.528450000000000000    1123
3    -6.010000000000000000    1123
3    6.010000000000000000    1123
4    2.000000000000000000    1123
4    -1.000000000000000000    1123
5    0.000000000000000000    1123
6    0.000000000000000000    1123
6    0.000000000000000000    1123

若按照add新增字段,结果为

>> alter table xunying add colums(name string);

>>hive> insert overwrite table xunying partition(inc_day='1123') select id,amt,'1' name from tb_xunying;

hive> select *from xunying where inc_day='1123';
OK
1    12.100000000000000000    NULL    1123
1    -12.100000000000000000    NULL    1123
2    15.528450000000000000    NULL    1123
2    -15.528450000000000000    NULL    1123
3    -6.010000000000000000    NULL    1123
3    6.010000000000000000    NULL    1123
4    2.000000000000000000    NULL    1123
4    -1.000000000000000000    NULL    1123
5    0.000000000000000000    NULL    1123
6    0.000000000000000000    NULL    1123
6    0.000000000000000000    NULL    1123

通过replace columns cascade解决

>>alter table xunying replace columns(id string,amt string,name string,name2 string) cascade;

>>insert overwrite  table xunying partition(inc_day='1123') select id,amt,'1' name,'2' name2 from tb_xunying;

hive> select *from xunying where inc_day='1123';
OK
1    12.100000000000000000    1    2    1123
1    -12.100000000000000000    1    2    1123
2    15.528450000000000000    1    2    1123
2    -15.528450000000000000    1    2    1123
3    -6.010000000000000000    1    2    1123
3    6.010000000000000000    1    2    1123
4    2.000000000000000000    1    2    1123
4    -1.000000000000000000    1    2    1123
5    0.000000000000000000    1    2    1123
6    0.000000000000000000    1    2    1123
6    0.000000000000000000    1    2    1123
原文地址:https://www.cnblogs.com/xunyingFree/p/9879148.html