从映射器输出中获取前 N 个项目 - Mapreduce

Get Top N items from mapper output - Mapreduce

我的 Mapper 任务 returns 我的输出如下:

2   c
2   g
3   a
3   b
6   r

我已经编写了生成正确输出的 reducer 代码和 keycomparator,但是我如何获得 Mapper 输出的前 3 名(按计数排名前 N):

public static class WLReducer2 extends
        Reducer<IntWritable, Text, Text, IntWritable> {

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

        for (Text x : values) {
            context.write(new Text(x), key);
        }

    };

}

public static class KeyComparator extends WritableComparator {
    protected KeyComparator() {
        super(IntWritable.class, true);
    }

    @Override
    public int compare(WritableComparable w1, WritableComparable w2) {
        // TODO Auto-generated method stub

        // Logger.error("--------------------------> writing Keycompare data = ----------->");
        IntWritable ip1 = (IntWritable) w1;
        IntWritable ip2 = (IntWritable) w2;
        int cmp = -1 * ip1.compareTo(ip2);

        return cmp;
    }
}

这是减速器输出:

r   6
b   3
a   3
g   2
c   2

reducer 的预期输出是计数前 3 的:

r   6
b   3
a   3

限制减速器的输出。像这样。

public static class WLReducer2 extends
        Reducer<IntWritable, Text, Text, IntWritable> {
    int count=0;
    @Override
    protected void reduce(IntWritable key, Iterable<Text> values,
            Context context) throws IOException, InterruptedException {

        for (Text x : values) {
            if (count > 3)
            context.write(new Text(x), key);
            count++;
        }

    };
}

将减速器数量设置为 1。job.setNumReduceTasks(1)

如果您的 Top-N 元素可以存储在内存中,您可以使用 TreeMap 来存储 Top-N 元素,并且如果您的进程可以仅使用 一个 reducer 进行聚合.

  1. 在你的 reducer 的 setup() 方法中实例化一个实例变量 TreeMap。
  2. 在您的 reducer() 方法中,您应该聚合键组的所有值,然后将结果与树中的第一个(最低)键进行比较,map.firstKey().如果您的当前值大于树中的最低值,则将当前值插入树图中,map.put(value, Item),然后从树中删除最低值 map.remove(value)
  3. 在 reducer 的 cleanup() 方法中,按要求的顺序将所有 TreeMap 的元素写入输出。

注意:要比较记录的value必须是TreeMap中的key .而你的TreeMap的value应该是描述,标签,字母等;与数字有关。