2012-02-29 100 views
3

那么,排序顺序与Hadoop MapRed

我想知道如何更改减少任务后,我简单的WordCount程序的排序顺序?我已经制作了另一张地图,通过按键进行价值排序,但仍然按升序排列。 有没有一个简单的方法来做到这一点(改变排序顺序)?

感谢 Vellozo

+0

解决! http://hadoop.sourcearchive.com/documentation/0.20.2plus-pdfsg1-1/TestComparators_8java-source.html – Vellozo 2012-02-29 06:03:58

回答

7

如果您使用的是较旧的API(mapred.*),然后设置OutputKeyComparatorClass作业的conf:

jobConf.setOutputKeyComparatorClass(ReverseComparator.class); 

ReverseComparator可以是这样的:

static class ReverseComparator extends WritableComparator { 
     private static final Text.Comparator TEXT_COMPARATOR = new Text.Comparator(); 

     public ReverseComparator() { 
      super(Text.class); 
     } 

     @Override 
     public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { 
      try { 
       return (-1)* TEXT_COMPARATOR 
         .compare(b1, s1, l1, b2, s2, l2); 
      } catch (IOException e) { 
       throw new IllegalArgumentException(e); 
      } 
     } 

     @Override 
     public int compare(WritableComparable a, WritableComparable b) { 
      if (a instanceof Text && b instanceof Text) { 
       return (-1)*(((Text) a) 
         .compareTo((Text) b))); 
      } 
      return super.compare(a, b); 
     } 
    } 

在新的API(mapreduce.*)中,我认为您需要使用Job.setSortComparator()方法。

+0

小错误...您没有定义“firstL1”和“firstL2”变量。我想你的意思是说'l1'和'l2' ​​ – 2012-03-01 04:53:20

+0

Thx家伙......我找到的解决方案几乎与这个Raze2dust相同! 谢谢你! – Vellozo 2012-03-01 10:32:35

+0

@PradeepGollakota谢谢,修正了它.. – 2012-03-01 13:34:51

2

这一个几乎是和上面一样,只是看起来有点简单

class MyKeyComparator extends WritableComparator { 
    protected DescendingKeyComparator() { 
     super(Text.class, true); 
    } 

    @SuppressWarnings("rawtypes") 
    @Override 
    public int compare(WritableComparable w1, WritableComparable w2) { 
     Text key1 = (Text) w1; 
     Text key2 = (Text) w2;   
     return -1 * key1.compareTo(key2); 
    } 
} 

然后将其添加到工作

job.setSortComparatorClass(MyKeyComparator.class);

Text key1 = (Text) w1; 
      Text key2 = (Text) w2; 

您可以根据您的使用更改上述文本类型。