hive 表总共分为四类,分别内部表、外部表、分区表、桶表
首先,未被external修饰的是内部表(managed table),被external修饰的为外部表(external table); 区别:
- 内部表数据由Hive自身管理,外部表数据由HDFS管理;
- 内部表数据存储的位置是hive.metastore.warehouse.dir(默认:/user/hive/warehouse),外部表数据的存储位置由自己制定;
- 删除内部表会直接删除元数据(metadata)及存储数据;
- 删除外部表仅仅会删除元数据,HDFS上的文件并不会被删除;
- 对内部表的修改会将修改直接同步给元数据,而对外部表的表结构和分区进行修改,则需要修复(MSCK REPAIR TABLE table_name;)
表字段操作
1)修改表名:
alter table table_old_name rename to table_new_name
2)修改列名、列类型
ALTER TABLE table_name [PARTITION partition_spec] CHANGE [COLUMN] col_old_name col_new_name column_type [COMMENT col_comment] [FIRST|AFTER column_name] [CASCADE|RESTRICT];
alter table table_name change column_old_name column_new_name column_new_type
--修改列名的同时,还可以修改注释,或者列的位置,[ ]之内均为可选项
alter table table_name change column_new_name column_new_name column_new_type [comment 'alter column name for test' ] [first | after column_num]
3)增加列
alter table table_name add columns (column_new_name column_new_type [comment 'comment'])
4)更新列
alter table table_name replace columns (column_new_name new_type)
5)更改表的属性
alter table table_name set TBLPROPERTIES ('EXTERNAL'='TRUE') --内部表转外部表
alter table table_name set TBLPROPERTIES ('EXTERNAL'='FALSE') --外部表转内部表
分区操作
1)修改分区名
alter table table_name partition(dt='partition_old_name') rename to partition(dt='partition_new_name')
2)修改分区属性
alter table table_name partition column (dt partition_new_type)
3)修改分区位置
alter table table_name partition (createtime='20190301') set location "new_location"
4)添加分区
alter table table_name add partition (partition_name = 'value') location '***'
--示例
alter table table_name add IF NOT EXISTS partition (createtime='20190301') location '/user/hive/warehouse/testdw/js_nk_wn'
--还可以同时添加多个分区,只需要在后面继续追加就行
alter table table_name add partition (createtime='20190301') location '/user/hive/warehouse/dept_part' partition (createtime='20190228') location '/user/hive/warehouse/dept_part'
5)删除分区
--删除一级分区
alter table table_name drop if exists partition(createtime='20190301')
--删除二级分区
alter table table_name drop if exists partition (month='02',day='12')
6)修改表的字节编码
alter table table_name set serdeproperties ('serialization.encoding'='utf-8');