Hadoop 的默认分区器 : HashPartitioner - How it calculates hash-code of a key?

标签 hadoop mapreduce hadoop2 hashcode reducers

我试图了解 MapReduce 中的分区,我了解到 Hadoop 有一个默认的分区程序,称为 HashPartitioner,分区程序有助于在决定给定键将转到哪个 reducer 时。

从概念上讲,它是这样工作的:

hashcode(key) % NumberOfReducers, where `key` is the key in <key,value> pair.

我的问题是:

HashPartitioner 如何计算 key 的哈希码?是简单地调用 key 的 hashCode() 还是此 HashPartitioner 使用一些其他逻辑来计算 key 的哈希码?

谁能帮我理解一下?

最佳答案

默认的分区器简单地使用键的hashcode() 方法并计算分区。这使您有机会实现 hascode() 来调整键的分区方式。

来自javadoc :

public int getPartition(K key,
               V value,
               int numReduceTasks)
Use Object.hashCode() to partition.

对于实际代码,它只是返回 (key.hashCode() & Integer.MAX_VALUE) % numReduceTasks:

 public int More ...getPartition(K key, V value,
                          int numReduceTasks) {
    return (key.hashCode() & Integer.MAX_VALUE) % numReduceTasks;
 }

编辑:添加自定义分区程序的详细信息

您可以为分区程序添加不同的逻辑,甚至可能根本不使用 hashcode()

自定义分区器可以通过扩展Partitioner

来编写
public class CustomPartitioner extends Partitioner<Text, Text>

一个这样的例子,它作用于自定义键对象的属性:

public static class CustomPartitioner extends Partitioner<Text, Text>{
@Override
public int getPartition(Text key, Text value, int numReduceTasks){
    String emp_dept = key.getDepartment();
    if(numReduceTasks == 0){
        return 0;
    }

    if(key.equals(new Text(“IT”))){
        return 0;
    }else if(key.equals(new Text(“Admin”))){
        return 1 % numReduceTasks;
    }else{
        return 2 % numReduceTasks;
    }
}

关于Hadoop 的默认分区器 : HashPartitioner - How it calculates hash-code of a key?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49180132/

相关文章:

hadoop - 处理增量数据 - Hadoop

hadoop - 用什么代替 mrunit withInputValue deprecated

hadoop - Hive 比 Spark 快吗?

c# - 提交 C# MapReduce 作业 Windows Azure HDInsight - 响应状态代码不表示成功 : 500 (Server Error)

hadoop - 如何使用 hadoop Map reduce 处理/提取 .pst

java - 使用Hadoop/HDFS进行100万个生物特征(小型)文件比较

Hadoop - 当多个进程试图同时写入同一个文件时会发生什么?

WebHDFS 的 Hadoop 名称节点 URL

hadoop - Fiware-Cosmos MapReduce

hadoop - 配置单元失败的SemanticException