在使用复合键Hadoop时,在遍历值时部分键会发生更改

在使用复合键Hadoop时,在遍历值时部分键会发生更改,hadoop,secondary-sort,Hadoop,Secondary Sort,我已经在Hadoop上实现了二级排序,但我并不真正理解框架的行为 我创建了一个复合键,其中包含原始键和部分值,用于排序 为了实现这一点,我实现了自己的partitioner public class CustomPartitioner extends Partitioner<CoupleAsKey, LongWritable>{ @Override public int getPartition(CoupleAsKey couple, LongWritable value, int

我已经在Hadoop上实现了二级排序,但我并不真正理解框架的行为

我创建了一个复合键,其中包含原始键和部分值,用于排序

为了实现这一点,我实现了自己的partitioner

public class CustomPartitioner extends Partitioner<CoupleAsKey, LongWritable>{

@Override
public int getPartition(CoupleAsKey couple, LongWritable value, int numPartitions) {

    return Long.hashCode(couple.getKey1()) % numPartitions;
}
}

并用以下方式定义了这对夫妇

public class CoupleAsKey implements WritableComparable<CoupleAsKey>{

private long key1;
private long key2;

public CoupleAsKey() {
}

public CoupleAsKey(long key1, long key2) {
    this.key1 = key1;
    this.key2 = key2;
}

public long getKey1() {
    return key1;
}

public void setKey1(long key1) {
    this.key1 = key1;
}

public long getKey2() {
    return key2;
}

public void setKey2(long key2) {
    this.key2 = key2;
}

@Override
public void write(DataOutput output) throws IOException {

    output.writeLong(key1);
    output.writeLong(key2);

}

@Override
public void readFields(DataInput input) throws IOException {

    key1 = input.readLong();
    key2 = input.readLong();
}

@Override
public int compareTo(CoupleAsKey o2) {

    int cmp = Long.compare(key1, o2.getKey1());

    if(cmp != 0)
        return cmp;

    return Long.compare(key2, o2.getKey2());
}

@Override
public String toString() {
    return key1 + ","  + key2 + ",";
}
现在,这是可行的,但真正奇怪的是,当在reducer中迭代一个键时,键的第二部分,值部分在每次迭代中都会发生变化。为什么和如何

 @Override
protected void reduce(CoupleAsKey key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {

    for (LongWritable value : values) {

        //key.key2 changes during iterations, why?
        context.write(key, value);
    }

}
定义说,如果您希望将数据分区中的所有相关行发送到单个reducer,则必须实现分组比较器。这只确保这些密钥集将被发送到单个reduce调用,而不是密钥将从composite或其他类型更改为仅包含已进行分组的密钥部分的内容

但是,当您在值上迭代时,相应的键也将更改。我们通常不会观察到这种情况,因为默认情况下,值分组在同一个非复合键上,因此,即使值发生变化,-key的值也保持不变

您可以尝试打印键的对象引用,您应该注意到,每次迭代时,键的对象引用也会发生如下变化:

IntWritable@1235ft
IntWritable@6635gh
IntWritable@9804as
或者,您也可以尝试在IntWritable上应用组比较器,方法如下:您必须编写自己的逻辑才能这样做:

Group1:    
1        a    
1        b    
2        c

Group2:
3        c
3        d
4        a
你将看到,随着价值的每一次迭代,你的关键也在改变

IntWritable@1235ft
IntWritable@6635gh
IntWritable@9804as
Group1:    
1        a    
1        b    
2        c

Group2:
3        c
3        d
4        a