Hive表增加字段并指定字段位置

Hive表增加字段并指定字段位置

在Hive中,不能直接新增字段并指定位置,否则会报错。需要先增加字段,再指定位置。

1
2
alter table test_01 add columns(company string comment '');
alter table test_01 change company company string after id;

同时,我们也需要考虑字段位置的移动对数据造成的影响
下面是简单测试。

数据校验

查看改动前目标表字段顺序以及相关数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
--查看表结构
0: jdbc:hive2://bd12:10000> desc test_01;
+-----------+------------+----------+
| col_name  | data_type  | comment  |
+-----------+------------+----------+
id    | int     |     |
name     | string   |      |
+-----------+------------+----------+
--查看表数据
0: jdbc:hive2://bd12:10000> select * from test_01;
+-------------+---------------+
| test_01.id  | test_01.name  |
+-------------+---------------+
| 1      | Jack Ma   | 
| 2      | Pony Ma    | 
| 3      | Robin Li   | 
+-------------+---------------+

直接新增并指定位置(报错)

1
2
0: jdbc:hive2://bd12:10000> alter table test_01 add columns(company string comment '') after name;
Error: Error while compiling statement: FAILED: ParseException line 1:55 missing EOF at 'after' near ')'

先增加字段,再修改位置,注意数据影响(正确)

先增加字段,再修改位置(默认新增字段在最后位置)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
alter table test_01 add columns(company string comment '');
--数据查看
select * from test_01;
+-------------+---------------+------------------+
| test_01.id  | test_01.name  | test_01.company  |
+-------------+---------------+------------------+
| 1      | Jack Ma    | NULL       |
| 2      | Pony Ma    | NULL       |
| 3      | Robin Li    | NULL       |
+-------------+---------------+------------------+
--注意:如果表中有数据,字段位置的修改会导致字段对应的数据发生改变。这里本来name字段有值,结果位置修改之后name变为空值,company有值。
-- 修改字段位置并查看数据。
alter table test_01 change company company string after id;
select * from test_01;
+-------------+------------------+---------------+
| test_01.id  | test_01.company  | test_01.name  |
+-------------+------------------+---------------+
| 1      | Jack Ma      | NULL      |
| 2      | Pony Ma      | NULL      |
| 3      | Robin Li     | NULL      |
+-------------+------------------+---------------+

原因分析:
这是由于HDFS底层文件映射成Hive表的特性决定。
同理,如果字段类型与底层文件对应不上,查询数据时会被空值覆盖,这里我们将id字段往后移动一位。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
alter table test_01 change id id int after company;
desc test_01;
+-----------+------------+----------+
| col_name  | data_type  | comment  |
+-----------+------------+----------+
| company  | string   |      |
id     | int     |      |
name    | string   |      |
+-----------+------------+----------+
select * from test_01;
+------------------+-------------+---------------+
| test_01.company  | test_01.id  | test_01.name  |
+------------------+-------------+---------------+
| 1         | NULL     | NULL      |
| 2         | NULL     | NULL      |
| 3         | NULL     | NULL      |
+------------------+-------------+---------------+

考虑到Hive表的特性,不建议在已有数据的情况下还进行字段新增和位置调整。如果非要这么做,可以考虑新建表再进行数据导入。

打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2015-2023 henrrywan

请我喝杯咖啡吧~

支付宝
微信