1 问题背景

目前集群存于一个非常不健康的状态,主要问题是小文件太多,单个DataNode的block数量阈值是500,000,而现在单个DataNode的block为2,631,218,约为阈值的5倍,现在所有DataNode都处于黄色不健康状态。

小文件问题会直接带来NameNode的压力巨大,从而导致HDFS的稳定性,同时对HDFS日常的数据读写带来性能下降。目前已可以看到集群的NameNode频繁出现检查点告警问题。

通过对集群中目前目录个数,文件大小,文件数量,Hive表数量,Hive数据库数量,Hive分区数量进行了详细的数据采集。发现主要是HDFS目录中的小文件太多,大量1KB的文件,甚至是小于1KB的文件;具体表现为:不论表与分区的数据量大小,当有分区时每个分区具有200个文件,当没有分区时每个表有200个文件,而许多表是小表,所以造成严重的小文件问题。

解决此问题的方法主要为两个方面;一是从源头解决小文件问题,在导数的过程中对作业进行优化,以减少小文件的输出,此方法需要业务方解决;二是合并平台上已有的小文件;本问描写合并平台小文件的方案。

2 原表情况

通过对集群内的文件数量以及文件大小进行分析,小文件问题基本出现在hive表中;经过近一步分析,发现每个分区存在着200个小文件,可以将这些文件合并减少小文件数量从而缓解小文件问题。

示例表test_part一共20行数据,以字段date_str为分区

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_表名

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_表名_02

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_表数据_03

共有五个分区

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_表数据_04

每个分区分别四个文件

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_表数据_05

3 执行流程

执行流程总体如下:

1、使用create table name like tb_name创建备用表,使得表结构保持一致;

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_hive_06

2、配置支持merge等参数,并使用insert overwrite语句读取原表数据插入到备用表。

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_表名_07

3、确认表数据一致后,删除原表,使用alter语句将备用表的表名修改为原表的表名。

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_表名_08

4 方案描述

新建备表,表结构与原表保持一致

create table test_part_bak like test_part;

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_表名_09

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_表名_10


设置如下参数,使支持合并

SET hive.merge.mapfiles = true;
SET hive.merge.mapredfiles = true;
SET hive.merge.size.per.task = 256000000;
SET hive.merge.smallfiles.avgsize = 134217728;
SET hive.exec.compress.output = true;
SET parquet.compression = snappy;
SET hive.exec.dynamic.partition.mode = nonstrict;
SET hive.exec.dynamic.partition = true;

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_表名_11


使用insert overwrite语句查询原表数据覆盖备表

insert overwrite table test_part_bak partition(date_str) select * from test_part;

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_表数据_12

备用表数据和原表一致

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_表名_13


删除原表,将备用表表名修改为原表名

alter table test_part_bak rename to test_part;

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_hive_14


合并后表数据没有变化

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_表名_15

表结构一致

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_hive_16


从HDFS文件系统可以看出,分区数量没有改变,每个分区的几个小文件已经合并为一个文件。

hive设置小文件合并 combinehiveinputformat hive小文件合并命令_hive_17