拒絕手敲,hive創建表只需要輸入表名和字段即可自動建表(shell腳本實現)

問題描述

如果 hive 表有100個字段,一天建20張表,一直敲 Ctrl C Ctrl V ....(20年單身手速也不能對自己這麼狠吧!!)

問題解決

h1“”傳入的第一個參數 $1 和 create table 字符拼接

h2:傳入的參數 $2 $3 和 partition by 字符串拼接

h3:傳入的之後的參數 $* 通過 for 循環和 varchar(255) ,字符拼接

hive -e "$h1$h2$h3" 實現通過shell腳本自動創建hive表

 代碼實現

#!/bin/bash

# $1:表名 $2:分區1 $3:分區2 $4-$n:基礎字段
# 數據庫名稱,這裏不作爲參數用自變量寫了
database="observation"
# hive 拼接語句,分爲h1,h2,h3 
# h1是建表語句的前半部,h2是參數列表中間部分,h3是建表語句的後半部
h1="create external table $database.$1("
# 在當前目錄下創建文本文件temp,如果文件存在則清空文件
$(> temp)
# for 循環將參數追加到當前目錄的temp文件,逗號分隔,echo -n 不換行
for i in $*;do
	((n++))
	if [[ n -gt 3 ]];then
		echo -n $i" varchar(255)," >> temp
	fi
done
# h2取temp文本里的字符串
temp=$(cat temp)
# 將字符串最後的一個逗號去掉
h2="${temp%*,} )"
#echo $h2
# h3是建表語句的後半部
h3="
partitioned by ($2 string,$3 string)
row format delimited 
fields terminated by ','
lines terminated by '\n'
stored as textfile
location '/user/hive/warehouse/$database.db/$1';
"
echo $h1$h2$h3

$(hive -e "$h1$h2$h3")

代碼實現2

#!/bin/bash

#string="tablename;field1,field2,field3,field4;partition1,partition2,partition3"
string=$*
group=(${string//;/ })
for i in ${group[@]};do
    ((m++))
    if [[ m -eq 1 ]];then
        tables=$i
    elif [[ m -eq 2 ]];then
        fields=$i
    else partitions=$i
    fi
done
# echo "tables:" $tables
# echo "fileds:" $fields
# echo "partitions:" $partitions
# echo "-----------------"
field=(${fields//,/ })
partition=(${partitions//,/ })

# 創建表目錄
$(mkdir /home/hive/observation/$tables)

# 數據庫名稱,這裏不作爲參數用自變量寫了
database="observation"
# hive 拼接語句,分爲h1,h2,h3
# h1是建表語句的前半部,h2是參數列表中間部分,h3是建表語句的後半部
h1="create external table $database.tables"
# 在當前目錄下創建文本文件temp,如果文件存在則清空文件
$(> temp)
# for 循環將參數追加到當前目錄的temp文件,逗號分隔,echo -n 不換行
for i in ${field[@]};do
	echo -n $i" varchar(255)," >> temp
done
# h2取temp文本里的字符串
temp=$(cat temp)
# 將字符串最後的一個逗號去掉
h2="( ${temp%*,} )"
# 在當前目錄下創建文本文件tmp,如果文件存在則清空文件
$(> tmp)
# for 循環將參數追加到當前目錄的temp文件,逗號分隔,echo -n 不換行
for i in ${partition[@]};do
	$(mkdir /home/hive/observation/$tables/$i)
	echo -n $i" varchar(255)," >> tmp
done
# h3取temp文本里的字符串
tmp=$(cat tmp)
# 將字符串最後的一個逗號去掉
# h3是建表語句的後半部
h3="
partitioned by
( ${tmp%*,} )
row format delimited 
fields terminated by ','
lines terminated by '\n'
stored as textfile
location '/user/hive/warehouse/$database.db/tables';
"
echo $h1$h2$h3
#$(hive -e "$h1$h2$h3")
#$(rm -rf tmp temp)

注意事項

第一個參數是表名
第二個參數是分區
第三個參數是分區
之後參數爲表字段

hive表類型:external
普通字段:varchar(255)
分區字段:string
換行分隔符: \n
字段分隔符:,
存儲格式:textfile

用 shell 寫的原因是方便任務調度框架 oozie、anzkaban 定時調度

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章