在 hive external table 中添加一个新分区,并将 table 的现有分区更新为非分区列

Add a new partition in hive external table and update the existing partition to column of the table to non-partition column

我有以下现有 table emp,分区列为 as_of_date(current_date -1).

CREATE EXTERNAL TABLE IF NOT EXISTS emp(
  student_ID INT, 
  name STRING)
  partitioned by (as_of_date date)
  ROW FORMAT DELIMITED
  FIELDS TERMINATED BY ','
  STORED AS TEXTFILE
  LOCATION '/user/emp';

下面是已有的分区路径

user/emp/as_of_date=2021-09-02
user/emp/as_of_date=2021-09-03
user/emp/as_of_date=2021-09-04

在 emp table 中,我必须添加新的分区列作为 businessdate(current_date) 并将分区列 (as_of_date) 更改为非分区列。

预期输出应如下所示。

describe table emp;
CREATE EXTERNAL TABLE IF NOT EXISTS emp(
student_ID INT, 
Name STRING, 
as_of_date date)
  partitioned by (businessdate date)
  ROW FORMAT DELIMITED
  FIELDS TERMINATED BY ','
  STORED AS TEXTFILE
  LOCATION '/user/emp';

更新后,下面是hdfs路径

user/emp/buinessdate=2021-09-03
user/emp/buinessdate=2021-09-04
user/emp/businessdate=2021-09-05

预期输出table:

|student_ID |name |as_of_date | business_date |
|--| --- | --- |----|
|1 | Sta |2021-09-02| 2021-09-03 |
|2 |Danny|2021-09-03| 2021-09-04 |
|3 |Elle |2021-09-04| 2021-09-05 |

创建新的 table,从旧的 table 加载数据,删除旧的 table,重命名新的 table。

--1 创建新的table emp1

CREATE EXTERNAL TABLE emp1(
student_ID INT, 
Name STRING, 
as_of_date date)
  partitioned by (businessdate date)
  ROW FORMAT DELIMITED
  FIELDS TERMINATED BY ','
  STORED AS TEXTFILE
  LOCATION '/user/emp1';

--2 从计算出的新分区列的emp中加载数据到emp1

--dynamic partition mode
SET hive.exec.dynamic.partition=true;
SET hive.exec.dynamic.partition.mode=nonstrict;

insert overwrite table emp1 partition (business_date)
select 
     student_ID, 
     Name, 
     as_of_date,
     date_add(as_of_date,1) as business_date
 from emp;

现在您可以删除旧的(使其首先管理以删除位置)并在必要时重命名新的 table。