python導(dǎo)出hive數(shù)據(jù)表的schema實例代碼
本文研究的主要問題是python語言導(dǎo)出hive數(shù)據(jù)表的schema,分享了實現(xiàn)代碼,具體如下。
為了避免運營提出無窮無盡的查詢需求,我們決定將有查詢價值的數(shù)據(jù)從mysql導(dǎo)入hive中,讓他們使用HUE這個開源工具進行查詢。想必他們對表結(jié)構(gòu)不甚了解,還需要為之提供一個表結(jié)構(gòu)說明,于是編寫了一個腳本,從hive數(shù)據(jù)庫中將每張表的字段即類型查詢出來,代碼如下:
#coding=utf-8
import pyhs2
from xlwt import *
hiveconn = pyhs2.connect(host='10.46.77.120',
port=10000,
authMechanism='PLAIN',
user='hadoop',
database='hibiscus_data',
)
def create_excel():
sql = 'show tables'
tables = []
with hiveconn.cursor() as cursor:
cursor.execute(sql)
res = cursor.fetch()
for table in res:
tables.append(table[0])
tableinfo = []
for table in tables:
tableinfo.append(get_column_info(table))
create_excel_ex(tableinfo)
def create_excel_ex(tableinfo):
w = Workbook()
sheet = w.add_sheet(u'表結(jié)構(gòu)')
row = 0
for info in tableinfo:
row = write_tale_info(info,sheet,row)
w.save('hive_schema.xls')
def write_tale_info(tableinfo,sheet,row):
print row
sheet.write_merge(row,row,0,2,tableinfo['table'])
row += 1
sheet.write(row,0,u'名稱')
sheet.write(row,1,u'類型')
sheet.write(row,2,u'解釋')
row += 1
fields = tableinfo['fields']
for field in fields:
sheet.write(row,0,field['name'])
sheet.write(row,1,field['type'])
row += 1
return row + 1
def get_column_info(table):
sql = 'desc {table}'.format(table=table)
info = {'table':table,'fields':[]}
with hiveconn.cursor() as cursor:
cursor.execute(sql)
res = cursor.fetch()
for item in res:
if item[0] == '':
break
info['fields'].append({'name':item[0],'type':item[1]})
return info
if __name__ == '__main__':
create_excel()
其實,我們的hive數(shù)據(jù)庫將所有的元數(shù)據(jù)存儲在了mysql當中,分析這些元數(shù)據(jù)也可以獲得表結(jié)構(gòu)信息。
總結(jié)
以上就是本文關(guān)于python導(dǎo)出hive數(shù)據(jù)表的schema實例代碼的全部內(nèi)容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
相關(guān)文章
利用python將json數(shù)據(jù)轉(zhuǎn)換為csv格式的方法
下面小編就為大家分享一篇利用python將json數(shù)據(jù)轉(zhuǎn)換為csv格式的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03
python3實現(xiàn)的zip格式壓縮文件夾操作示例
這篇文章主要介紹了python3實現(xiàn)的zip格式壓縮文件夾操作,結(jié)合實例形式分析了Python3基于zipfile模塊實現(xiàn)zip格式文件壓縮的相關(guān)操作技巧,需要的朋友可以參考下2019-08-08
python實現(xiàn)人機對戰(zhàn)的井字棋游戲
這篇文章主要為大家詳細介紹了python實現(xiàn)人機對戰(zhàn)的井字棋游戲,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04
關(guān)于Pycharm配置翻譯插件Translation報錯更新TTK失敗不能使用的問題
這篇文章主要介紹了關(guān)于Pycharm配置翻譯插件Translation報錯更新TTK失敗不能使用的問題,本文通過圖文并茂的形式給大家分享解決方案,需要的朋友可以參考下2022-04-04
使用Python快速打開一個百萬行級別的超大Excel文件的方法
這篇文章主要介紹了使用Python快速打開一個百萬行級別的超大Excel文件的方法,本文通過實例代碼給大家介紹的非常想詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03

