Merge small files

Updated at:

A distributed file system stores data in blocks. Files smaller than the 64 MB block size are considered small files. Distributed systems inevitably generate small files from sources such as the output of SQL jobs, other distributed engines, or data collected through Tunnel. Merging these small files optimizes system performance. This topic describes how to merge small files in MaxCompute.

Background information

An excessive number of small files can cause the following problems:

  • MaxCompute processes a single large file more efficiently than it processes multiple small files. An excessive number of small files can degrade overall execution performance.

  • Too many small files can strain the Pangu file system and reduce storage efficiency.

Therefore, it is important to merge small files that are generated during computation to optimize both storage and performance. MaxCompute provides several powerful features for handling small files:

  • By default, after a job is complete, the system automatically assigns a Fuxi task to merge small files if certain conditions are met. This process is known as a MergeTask.

  • By default, a Fuxi instance can process up to 100 small files. The odps.sql.mapper.merge.limit.size parameter controls the total size of the files to read.

  • MaxCompute periodically scans the metadatabase in the background and merges small files for tables or partitions that contain many them. This process is transparent to users.

However, metadata discovery may still reveal many unmerged small files. For example, if a table is continuously being written to, the automatic merge operation cannot run. In this case, you must first stop the write job and then manually merge the small files.

Precautions

  • Merging small files consumes computing resources. If your instance uses the pay-as-you-go billing method, you are charged for this operation. The billing rules are the same as those for pay-as-you-go SQL jobs. For more information, see SQL jobs (Pay-as-you-go).

  • The command to merge small files does not support transactional tables. To merge small files in a transactional table, see COMPACTION.

Check the number of files in a table

  • Syntax

    DESC EXTENDED <table_name> [PARTITION (<pt_spec>)];
  • Parameters

    • table_name

      Required. The name of the table to check.

    • pt_spec

      Optional. The partition to check. The format is (partition_col1 = partition_col_value1, partition_col2 = partition_col_value2, ...).

  • Example

    A sample partition of the odl_bpm_wfc_task_log table has 3,607 files. The partition size is 274 MB (287,869,658 bytes), and the average file size is approximately 0.07 MB. The small files in this partition need to be merged.

    odps@ admin_task_project>desc extended jxbwarehouse.odl_bpm_wfc_task_log partition(new_dts_sync_modifytime_year='2022',new_dts_sync_modifytime_month='11',new_dts_sync_modifytime_day='27');
    +--------------------------------------------------------------------------------------------+
    | PartitionSize: 287869658                                                                   |
    +--------------------------------------------------------------------------------------------+
    | CreateTime:               2022-11-27 00:00:46                                              |
    | LastDDLTime:              2022-11-27 00:00:46                                              |
    | LastModifiedTime:         2022-11-27 23:59:47                                              |
    +--------------------------------------------------------------------------------------------+
    | IsExstore:                false                                                            |
    | IsArchived:               false                                                            |
    | PhysicalSize:             863608974                                                        |
    | FileNum:                  3607                                                             |
    +--------------------------------------------------------------------------------------------+

Solutions

Metadata detection can identify partitions that are suitable for a file merge. A merge is recommended if a partition contains more than 100 files and the average file size is less than 64 MB. Two solutions are available.

  • Immediate merge

    You can use the following command to perform an immediate merge.

    ALTER TABLE <table_name> [partition (<pt_spec>)] MERGE SMALLFILES;

    After you run the immediate merge operation on the odl_bpm_wfc_task_log table, the number of files is reduced to 19 and the storage size is reduced to 37 MB. This demonstrates that merging small files also significantly improves storage efficiency.

    In most cases, the default parameters are sufficient to merge small files. However, MaxCompute provides several parameters to meet custom requirements. The following are common parameters:

    • SET odps.merge.cross.paths=true|false

      Specifies whether to merge files across paths. If a table has multiple partitions, the merge process generates a separate MergeAction for each partition. Therefore, setting odps.merge.cross.paths to true does not change the number of paths. It only merges the small files within each path separately.

    • SET odps.merge.smallfile.filesize.threshold = 64

      Specifies the threshold, in MB, for the size of small files to be merged. Files larger than this threshold are not merged. You do not need to set this parameter. If this parameter is not set, the global variable odps_g_merge_filesize_threshold is used, which has a default value of 32 MB. If you set this parameter, its value must be greater than 32 MB.

    • SET odps.merge.maxmerged.filesize.threshold = 500

      Specifies the size of the output file after the merge, in MB. If an output file exceeds this threshold, a new output file is created. You do not need to set this parameter. If this parameter is not set, the global variable odps_g_max_merged_filesize_threshold is used, which has a default value of 500 MB. If you set this parameter, its value must be greater than 500 MB.

  • Merge using a PyODPS script

    You can use PyODPS to asynchronously submit a task that merges the small files generated by the previous day's jobs. The following code provides an example script:

    import os
    from odps import ODPS
    
    # Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID environment variable is set to your Access Key ID.
    # Make sure that the ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variable is set to your Access Key Secret.
    # Do not use the Access Key ID and Access Key Secret strings directly.
    o = ODPS(
        os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID'),
        os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET'),
        project='your-default-project',
        endpoint='your-end-point',
    )
    
    # Note: Replace $table_name with the name of your table.
    table_name = $table_name
    t = o.get_table(table_name)
    
    # Set merge options.
    hints = {'odps.merge.maxmerged.filesize.threshold': 256}
    
    # Examples for multiple partitions
    insts = []
    # iterate_partitions lists all partitions under ds=$datetime. The partition format may vary.
    for partition in t.iterate_partitions(spec="ds=%s" % $datetime):
        instance=o.run_merge_files(table_name, str(partition), hints=hints)
    		# Click the Waiting Queue in this Logview to find the Logview for the actual execution.
        print(instance.get_logview_address())
        insts.append(instance)
    
    # Wait for the partition results.
    for inst in insts:
        inst.wait_for_completion()

    To run this script, you must first install PyODPS. For installation instructions, see PyODPS.

Use case

tbcdm.dwd_tb_log_pv_di is a physical table that the data stability system identified as requiring a small file merge. According to the metadata table tbcdm.dws_rmd_merge_task_1d, most partitions of this table contain more than 1,000 files — some even exceed 7,000 — yet the average file size is less than 1 MB.

Query the file statistics for the subpartitions of the dwd_tb_log_pv_di table under the ds=20151114 partition, grouped by combinations of visitor_type and url_type. The results show that pangu_file_num (the number of files) is generally high, with values such as 7384, 7018, 6818, and 5384, whereas avg_pangu_file_size (the average file size) is small. This indicates a significant small-file problem.

You can use the following commands to merge the small files using the immediate merge solution.

SET odps.merge.cross.paths=true;
SET odps.merge.smallfile.filesize.threshold=128;
SET odps.merge.max.filenumber.per.instance = 2000;
ALTER TABLE tbcdm.dwd_tb_log_pv_di PARTITION (ds='20151116') MERGE smallfiles;

After you run the merge commands, the merge results for each partition are as follows. The file count drops significantly from thousands to tens or hundreds, matching the instance count for each partition.

Summary:
table name: dwd_tb_log_pv_di /ds=20151116/visitor_type=uid/url_type=other/company=c  instance count: 442  run time: 182
  before merge, file count:     8285  file size: 226272202K  file physical size: 678816607K
   after merge, file count:      442  file size: 226193505K  file physical size: 678580517K
table name: dwd_tb_log_pv_di /ds=20151116/visitor_type=mid/url_type=other/company=c  instance count: 50  run time: 136
  before merge, file count:     8285  file size: 25174441K  file physical size: 75523325K
   after merge, file count:       50  file size: 24979902K  file physical size: 74939708K
table name: dwd_tb_log_pv_di /ds=20151116/visitor_type=mid/url_type=ipv/company=c  instance count: 48  run time: 183
  before merge, file count:     7888  file size: 24452025K  file physical size: 73356075K
   after merge, file count:       48  file size: 24328967K  file physical size: 72986902K
table name: dwd_tb_log_pv_di /ds=20151116/visitor_type=uid/url_type=ipv/company=c  instance count: 131  run time: 125
  before merge, file count:     7620  file size: 66788449K  file physical size: 200365347K
   after merge, file count:      131  file size: 66660873K  file physical size: 199982619K
table name: dwd_tb_log_pv_di /ds=20151116/visitor_type=uid/url_type=search/company=c  instance count: 45  run time: 115
  before merge, file count:     6285  file size: 22863879K  file physical size: 68591639K
   after merge, file count:       45  file size: 22732543K  file physical size: 68197630K
table name: dwd_tb_log_pv_di /ds=20151116/visitor_type=uid/url_type=shop/company=c  instance count: 50  run time: 104
  before merge, file count:     6285  file size: 25156741K  file physical size: 75470224K
   after merge, file count:       50  file size: 25029475K  file physical size: 75088426K
table name: dwd_tb_log_pv_di /ds=20151116/visitor_type=mid/url_type=search/company=c  instance count: 15  run time: 130
  before merge, file count:     6285  file size: 7265051K  file physical size: 21795153K
   after merge, file count:       15  file size: 7148859K  file physical size: 21446577K
table name: dwd_tb_log_pv_di /ds=20151116/visitor_type=mid/url_type=shop/company=c  instance count: 12  run time: 140
  before merge, file count:     6285  file size: 5861160K  file physical size: 17583481K
   after merge, file count:       12  file size: 5734710K  file physical size: 17204132K