hive 表总共分为四类,分别内部表、外部表、分区表、桶表

首先,未被external修饰的是内部表(managed table),被external修饰的为外部表(external table); 区别:

  • 内部表数据由Hive自身管理,外部表数据由HDFS管理;
  • 内部表数据存储的位置是hive.metastore.warehouse.dir(默认:/user/hive/warehouse),外部表数据的存储位置由自己制定;
  • 删除内部表会直接删除元数据(metadata)及存储数据;
  • 删除外部表仅仅会删除元数据,HDFS上的文件并不会被删除;
  • 对内部表的修改会将修改直接同步给元数据,而对外部表的表结构和分区进行修改,则需要修复(MSCK REPAIR TABLE table_name;)

表字段操作

  1. 1)修改表名:
  2. alter table table_old_name rename to table_new_name
  3. 2)修改列名、列类型
  4. 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];
  5. alter table table_name change column_old_name column_new_name column_new_type
  6. --修改列名的同时,还可以修改注释,或者列的位置,[ ]之内均为可选项
  7. alter table table_name change column_new_name column_new_name column_new_type [comment 'alter column name for test' ] [first | after column_num]
  8. 3)增加列
  9. alter table table_name add columns (column_new_name column_new_type [comment 'comment'])
  10. 4)更新列
  11. alter table table_name replace columns (column_new_name new_type)
  12. 5)更改表的属性
  13. alter table table_name set TBLPROPERTIES ('EXTERNAL'='TRUE') --内部表转外部表
  14. alter table table_name set TBLPROPERTIES ('EXTERNAL'='FALSE') --外部表转内部表

分区操作

  1. 1)修改分区名
  2. alter table table_name partitiondt='partition_old_name' rename to partition(dt='partition_new_name')
  3. 2)修改分区属性
  4. alter table table_name partition column (dt partition_new_type)
  5. 3)修改分区位置
  6. alter table table_name partition (createtime='20190301') set location "new_location"
  7. 4)添加分区
  8. alter table table_name add partition (partition_name = 'value') location '***'
  9. --示例
  10. alter table table_name add IF NOT EXISTS partition (createtime='20190301') location '/user/hive/warehouse/testdw/js_nk_wn'
  11. --还可以同时添加多个分区,只需要在后面继续追加就行
  12. alter table table_name add partition (createtime='20190301') location '/user/hive/warehouse/dept_part' partition (createtime='20190228') location '/user/hive/warehouse/dept_part'
  13. 5)删除分区
  14. --删除一级分区
  15. alter table table_name drop if exists partition(createtime='20190301')
  16. --删除二级分区
  17. alter table table_name drop if exists partition (month='02',day='12')
  18. 6)修改表的字节编码
  19. alter table table_name set serdeproperties ('serialization.encoding'='utf-8');