天天看點

合并HDFS和本地檔案系統中的小檔案

衆所周知,HDFS中過多的小檔案,會給NameNode造成很大的壓力,所謂的小檔案,是指遠遠小于檔案塊大小的檔案。

在使用HDFS的過程中,應盡量避免生成過多的小檔案。

本文以TextFile為例,介紹一下從本地–>HDFS、HDFS–>本地、以及HDFS–>HDFS的檔案上傳下載下傳移動過程中,對小檔案的合并方法

将本地的小檔案合并,上傳到HDFS

假設存放在本地的資料由很多個小檔案組成,需要上傳到HDFS。一般的做法是在本地使用腳本、程式先把小檔案合并後再上傳。

其實沒有必要,HDFS中提供了一個很有用的指令 appendToFile,就可以解決這個問題。

假設本地有兩個小檔案1.txt和2.txt,裡面内容如下:

  1. [[email protected] ~]$ cat 1.txt
  2. 111111
  3. 111111
  4. 111111
  5. 111111
  6. [[email protected] ~]$ cat 2.txt
  7. 222222
  8. 222222
  9. 222222
  10. 222222

使用下面的指令,可以将1.txt和2.txt合并,并上傳到HDFS:

  1. [[email protected] ~]$ hadoop fs -appendToFile 1.txt2.txt hdfs://cdh5/tmp/lxw1234.txt
  2. [[email protected] ~]$ hadoop fs -cat hdfs://cdh5/tmp/lxw1234.txt
  3. 111111
  4. 111111
  5. 111111
  6. 111111
  7. 222222
  8. 222222
  9. 222222
  10. 222222

下載下傳HDFS的小檔案到本地,合并成一個大檔案

假設在HDFS的/tmp/lxw1234/目錄下,有兩個小檔案1.txt和2.txt

需要将它們下載下傳到本地的一個檔案中。

  1. [[email protected] ~]$ hadoop fs -cat /tmp/lxw1234/1.txt
  2. 111111
  3. 111111
  4. 111111
  5. 111111
  6. [[email protected] ~]$ hadoop fs -cat /tmp/lxw1234/2.txt
  7. 222222
  8. 222222
  9. 222222
  10. 222222

使用下面的指令:

  1. [[email protected] ~]$ hadoop fs -getmerge hdfs://cdh5/tmp/lxw1234/*.txt local_largefile.txt
  2. [[email protected] ~]$ cat local_largefile.txt
  3. 111111
  4. 111111
  5. 111111
  6. 111111
  7. 222222
  8. 222222
  9. 222222
  10. 222222

合并HDFS上的小檔案

如果需要合并HDFS上的某個目錄下有很多小檔案,可以嘗試使用下面的指令:

  1. [[email protected] ~]$ hadoop fs -cat hdfs://cdh5/tmp/lxw1234/*.txt | hadoop fs -appendToFile - hdfs://cdh5/tmp/hdfs_largefile.txt
  2. [[email protected] ~]$ hadoop fs -cat hdfs://cdh5/tmp/hdfs_largefile.txt
  3. 111111
  4. 111111
  5. 111111
  6. 111111
  7. 222222
  8. 222222
  9. 222222
  10. 222222

注意:這種處理方法在資料量非常大的情況下可能不太适合,最好使用MapReduce來合并。

本文轉載:http://lxw1234.com/archives/2015/09/481.htm

繼續閱讀