从mapper输出中获取前n项-mapreduce

v6ylcynt  于 2021-05-29  发布在  Hadoop
关注(0)|答案(2)|浏览(277)

我的Map器任务返回以下输出:

2   c
2   g
3   a
3   b
6   r

我已经编写了reducer代码和keycomparator来生成正确的输出,但是如何获得Map器输出的前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
voj3qocg

voj3qocg1#

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

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) .

hs1rzwqc

hs1rzwqc2#

如果您的前n个元素可以存储在内存中,那么您可以使用树Map来存储前n个元素,并且如果您的进程可以仅使用一个reducer进行聚合。
在reducer的setup()方法中示例化示例变量treemap。
在reducer()方法中,应该聚合keygroup的所有值,然后将结果与树中的第一个(最低)键进行比较, map.firstKey() . 如果当前值大于树中的最低值,则将当前值插入树Map中, map.put(value, Item) 然后从树中删除最小值 map.remove(value) .
在reducer的cleanup()方法中,按所需顺序将树Map的所有元素写入输出。
注意:比较记录的值必须是树Map中的键。树形图的值应该是描述、标签、字母等;与号码有关。

相关问题