MapReduce 在把資料餵給 reducer 之前會對 map output 的 key 排序,這保證了每個 reducer 局部有序。Hadoop 預設的 partitioner 是 HashPartitioner,它依 key 的 hashcode 決定去哪個 reducer,相同 key 一定進同一個 reducer,但不保證全域有序。若你要的是全域排序結果(例如 top N、bottom N),就需要 TotalOrderPartitioner。
public class HashPartitioner<K, V> extends Partitioner<K, V> {
/** Use {@link Object#hashCode()} to partition. */
public int getPartition(K key, V value, int numReduceTasks) {
return (key.hashCode() & Integer.MAX_VALUE) % numReduceTasks;
}
}
/**
* Partitioner effecting a total order by reading split points from
* an externally generated source.
*/
@InterfaceAudience.Public
@InterfaceStability.Stable
public class TotalOrderPartitioner<K extends WritableComparable<?>, V>
extends Partitioner<K, V> implements Configurable {
public int getPartition(K key, V value, int numPartitions) {
return partitions.findPartition(key);
}
}
TotalOrderPartitioner 依賴一個预先計算好的 partition file 來分配 key。這是一個 SequenceFile,若 reducer 數為 N,它包含 N-1 個 key 分割點,且已依 key comparator 排好序。每個 key 來到時,partitioner 判斷它落在哪個區間,就分給對應的 reducer。因為區間是全域有序的,N 個 reducer 的輸出接起來也就是全域有序。
建立 partition file 的是 InputSampler 的 writePartitionFile 方法,它對輸入取樣,有三種策略:
partition file 可透過 TotalOrderPartitioner.setPartitionFile(conf, path) 設定。建立 instance 時會呼叫 setConf 讀入分割點,接著依 key 型別選不同的查找結構:
boolean natOrder = conf.getBoolean(NATURAL_ORDER, true);
if (natOrder && BinaryComparable.class.isAssignableFrom(keyClass)) {
partitions = buildTrie((BinaryComparable[]) splitPoints, 0,
splitPoints.length, new byte[0],
conf.getInt(MAX_TRIE_DEPTH, 200));
} else {
partitions = new BinarySearchNode(splitPoints, comparator);
}
若 key 是 BinaryComparable(可視為字串型別)且採用自然序,會建構 trie,查詢複雜度 O(n),n 是樹的深度;否則建 BinarySearchNode 做二分搜尋,複雜度 O(log n),n 是 reducer 數。MAX_TRIE_DEPTH 預設 200,是為了在分割點很長且高度相似這種病态情況下,避免堆疊溢出與節點膨脹。
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.KeyValueTextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.partition.InputSampler;
import org.apache.hadoop.mapreduce.lib.partition.InputSampler.RandomSampler;
import org.apache.hadoop.mapreduce.lib.partition.TotalOrderPartitioner;
public class TotalSortMR {
public static int runTotalSortJob(String[] args) throws Exception {
Path inputPath = new Path(args[0]);
Path outputPath = new Path(args[1]);
Path partitionFile = new Path(args[2]);
int reduceNumber = Integer.parseInt(args[3]);
// 三個參數:key 被選中的機率、取樣數上限、最大讀取的 split 數
RandomSampler<Text, Text> sampler =
new InputSampler.RandomSampler<Text, Text>(0.1, 10000, 10);
Configuration conf = new Configuration();
TotalOrderPartitioner.setPartitionFile(conf, partitionFile);
Job job = new Job(conf);
job.setJobName("Total-Sort");
job.setJarByClass(TotalSortMR.class);
job.setInputFormatClass(KeyValueTextInputFormat.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(Text.class);
job.setNumReduceTasks(reduceNumber);
job.setPartitionerClass(TotalOrderPartitioner.class); // 重點
FileInputFormat.setInputPaths(job, inputPath);
FileOutputFormat.setOutputPath(job, outputPath);
outputPath.getFileSystem(conf).delete(outputPath, true);
InputSampler.writePartitionFile(job, sampler); // 產生 partition file
return job.waitForCompletion(true) ? 0 : 1;
}
public static void main(String[] args) throws Exception {
System.exit(runTotalSortJob(args));
}
}
除了 InputSampler,也可以用一個 MapReduce 工作來產生 partition file:自訂 InputFormat 取樣,把 output key 全部送到單一 reducer 排序輸出,這種做法在資料分布極度不均時比取樣更準確。
使用 TotalOrderPartitioner 時有兩個實務陷阱要注意。第一,取樣是「估計」,若資料分布與取樣樣本差異大,某些 reducer 會嚴重資料倾斜,全域排序名存實亡;此時可增大取樣數或改用自訂 sampler。第二,partition file 必須在每個節點都讀得到,通常放在 HDFS 上並在所有 container 都能存取;若放在本機,非分散式環境才可行。
另外,Hive 0.12 實作了平行版的 ORDER BY(HIVE-1402),底層正是 TotalOrderPartitioner,對需要全域排序的查詢是一項很實用的改進。
更多 Hadoop 相關資訊可參考 Hadoop 專題頁面。