保留Hive分区的最新文件

写在前面:
目前生产上有一个场景就是有一张HIVE的分区表,每5分钟就会有一个任务往 当天的分区里面写数据,但是本身也只需要当天最新的数据,这样下来,小文件就会巨巨巨多,所以不得避免就需要删除之前的文件了,这样也能提升查询速度。

方案:用Python执行Bash HDFS命令
代码如下:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import warnings
warnings.filterwarnings("ignore")


def RmHdfsFile():
    print(f'[START DELETE]')
    try:
        cmd ="""hdfs dfs -count /data/student/ts_date=$(date "+%Y%m%d")  | awk -F" " '{print $2}'"""
        print(cmd)
        return_count = os.popen(cmd).read()
        print("文件数:" + str(return_count))
        return_count = int(return_count)
        if return_count <= 9:
            # 不跑删除语句
            pass
        else:
            cmd2 ="""hdfs dfs -rm -r  `hdfs dfs -ls -h -t  /data/student/ts_date=$(date "+%Y%m%d") | tail -n +10 |  awk -F" " '{print $9}'` """
            print(cmd2)
            return_ = os.popen(cmd2).read()
            print(return_)
    except Exception:
        print(Exception)
    print(f'[END DELETE]')


if __name__ == '__main__':
    RmHdfsFile()

猜你喜欢

转载自blog.csdn.net/liuge36/article/details/121201759