hive全库数据及表结构的备份与恢复

在之前的文章中介绍了hive的export和import的使用方式,下面提供一个简单的脚本实现对指定的库列表做全库的数据及元数据的备份以及恢复。

hive的数据导入导出,备份恢复

很简单,是利用了awk和sed命令结合hive命令行。

首先传入库名列表,再遍历库名使用hive查看该库下所有表,然后拼接字符串到export文件内,前面介绍了export和import的命令仅仅是export和import以及to 和from的区别,所以这里直接对export文件处理得到import文件,然后读取export文件里的命令,使用hive命令行执行。这里推荐改为使用beeline更安全。备份之后的元数据以及数据都在/tmp/warehouse_bak 下,参考下面的代码即可写出批量import的脚本:传入库名列表,读取import文件,使用hive执行。

如不想使用python也可以将代码改为shell,思路同上,这里就不提供shell代码了。

import subprocess

schema_list=['dh_party','dh_sales','dh_t3_group_index','dh_t3_group_index_pre','dl_h_nccp','dl_h_noahwm_trans','dl_h_noahwm_cbs','dh_t3_mutual_fund','dh_t3_report_hlwpp','dh_event','dh_t3_report_crm']
# schema_list=['dh_party','dh_sales','dh_t3_group_index','dh_t3_group_index_pre','dh_t3_mutual_fund','dh_t3_report_hlwpp','dh_event']
for s in schema_list:
    try:
        print('----------start: '+s+' --------------------')
        hive_export_cmd=r"""hive -e 'use """+s+r""";show tables;' | awk '{printf "export table """+s+r""".%s to |/tmp/warehouse_bak/"""+s+r"""/%s|;\n",$1,$1}' | sed "s/|/'/g" > /home/tools/warehouse_bak/"""+s+r"""_export.hql"""
        subprocess.getstatusoutput(hive_export_cmd)
        cp_cmd = r"""cp /home/tools/warehouse_bak/{}_export.hql /home/tools/warehouse_bak/{}_import.hql""".format(s,s)
        subprocess.getstatusoutput(cp_cmd)
        sed1 = r"""sed -i 's/export table/import table/g' /home/tools/warehouse_bak/{}_import.hql""".format(s)
        sed2 = r"""sed -i 's/ to / from /g' /home/tools/warehouse_bak/{}_import.hql""".format(s)
        subprocess.getstatusoutput(sed1)
        subprocess.getstatusoutput(sed2)

        #export

        with open(r"""/home/tools/warehouse_bak/{}_export.hql""".format(s),'r') as f:
            cmd_list = f.readlines()
        print(cmd_list)
        for i in range(cmd_list.__len__()-2):
            hive_tbl_export = r""" hive -e "{}" """.format(cmd_list[i].replace(r'\n',''))
            try:
                subprocess.getstatusoutput(hive_tbl_export)
            except Exception as e:
                print(e)
                pass
        # hive_export = r"""hive -f /home/tools/warehouse_bak/{}_export.hql""".format(s)
        # subprocess.getstatusoutput(hive_export)

        print('----------end: '+s+' --------------------')
    except Exception as e:
        print(e)
        pass
#!/bin/bash
nohup /home/tools/python3/python36/bin/python3 /home/tools/warehouse_bak/hive_backup.py > /home/tools/warehouse_bak/log/backup_log.out 2>&1 &

猜你喜欢

转载自blog.csdn.net/wsdc0521/article/details/105403033