Hive中有時候會遇到復制表的需求,復制表指的是復制表結構和數據。
如果是針對非分區表,那很簡單,可以使用CREATE TABLE new_table AS SELECT * FROM old_table;
那么如果是分區表呢?
首先想到的辦法可能是:
先創建一張和old_table結構相同的new_table,包括分區;可以使用CREATE TABLE new_table LIKE old_table;
接下來使用動態分區,把old_table的數據INSERT到new_table中。
這個方法當然可以,但可能不是最快的。
其實可以這樣做:
1. CREATE TABLE new_table LIKE old_table;
2. 使用hadoop fs -cp 命令,把old_table對應的HDFS目錄的文件夾全部拷貝到new_table對應的HDFS目錄下;
3. 使用MSCK REPAIR TABLE new_table;修復新表的分區元數據;
看例子:
有一張分區表t1,只有兩個分區,每個分區中都有一條數據,如下:
hive> show partitions t1; OK pt=2015-09-11 pt=2015-09-12 Time taken: 0.11 seconds, Fetched: 2 row(s) hive> desc t1; OK id string pt string # Partition Information # col_name data_type comment pt string Time taken: 0.123 seconds, Fetched: 7 row(s) hive> select * from t1; OK X 2015-09-11 Y 2015-09-12 Time taken: 0.095 seconds, Fetched: 2 row(s) hive>
創建一張相同表結構的新表t2;
hive> create table t2 like t1; OK Time taken: 0.162 seconds hive> desc t2; OK id string pt string # Partition Information # col_name data_type comment pt string Time taken: 0.139 seconds, Fetched: 7 row(s) hive> show partitions t2; OK Time taken: 0.082 seconds
使用hadoop fs -cp命令把t1對應HDFS目錄的所有文件夾復制到t2對應的HDFS目錄下:
- [liuxiaowen@dev ~]$ hadoop fs -cp /hivedata/warehouse/liuxiaowen.db/t1/* /hivedata/warehouse/liuxiaowen.db/t2/
- [liuxiaowen@dev ~]$ hadoop fs -ls /hivedata/warehouse/liuxiaowen.db/t2/
- Found 2 items
- drwxr-xr-x - liuxiaowen liuxiaowen 0 2015-09-11 17:17 /hivedata/warehouse/liuxiaowen.db/t2/pt=2015-09-11
- drwxr-xr-x - liuxiaowen liuxiaowen 0 2015-09-11 17:17 /hivedata/warehouse/liuxiaowen.db/t2/pt=2015-09-12
在Hive用使用MSCK REPAIR TABLE t2;修復新表t2的分區元數據;
hive> show partitions t2; OK Time taken: 0.082 seconds hive> MSCK REPAIR TABLE t2; OK Partitions not in metastore: t2:pt=2015-09-11 t2:pt=2015-09-12 Repair: Added partition to metastore t2:pt=2015-09-11 Repair: Added partition to metastore t2:pt=2015-09-12 Time taken: 0.249 seconds, Fetched: 3 row(s) hive> show partitions t2; OK pt=2015-09-11 pt=2015-09-12 Time taken: 0.068 seconds, Fetched: 2 row(s) hive> select * from t2; OK X 2015-09-11 Y 2015-09-12 Time taken: 0.123 seconds, Fetched: 2 row(s) hive>
OK,新表t2已經復制好了,它和t1有着相同的表結構,分區結構,分區以及數據。