Hadoop reducer中的多个for-each循环

时间:2014-01-23 13:11:25

标签: java hadoop mapreduce

我遇到了Hadoop中多个for-each循环的问题,它甚至可能吗?

我现在有什么代码用于reducer类:

public class R_PreprocessAllSMS extends Reducer<Text, Text, Text, Text>{
private final static Text KEY = new Text();
private final static Text VALUE = new Text();

    @Override
    public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
        int sum = 0;
        for (Text value : values) {
            String[] splitString = value.toString().split("\t");
            sum += Integer.parseInt(splitString[1]);
        }
        if (sum > 100) {
            for (Text value : values) {
                String[] splitString = value.toString().split("\t");
                System.out.println(key.toString() + splitString[0] + " " + splitString[1]);
                KEY.set(key);
                VALUE.set(splitString[0] + "\t" + splitString[1]);
                context.write(KEY, VALUE);
            }
        }
    }
}

但是我想有可能第二次搜索给定的值并发出我们需要的值。如果不可能,那么在Hadoop中你建议的方法是什么? 感谢。

2 个答案:

答案 0 :(得分:0)

也许使用两对Mappres和Reducers?你可以一个接一个地打电话给他们。 例如,在一个main中创建两个作业。第二个得到第一个结果。

JobConf jobConf1 = new JobConf();  
JobConf jobConf2 = new JobConf();  

Job job1 = new Job(jobConf1);  

Job job2 = new Job(jobConf2);

或者可以看看:http://hadoop.apache.org/docs/current/api/org/apache/hadoop/mapred/lib/ChainReducer.html

答案 1 :(得分:0)

除了循环两次之外,您可以延迟写入值,直到您知道总和足够高,例如:

    int sum = 0;
    List list = new ArrayList<String>();
    KEY.set(key);

    for (Text value : values) {
        String[] splitString = value.toString().split("\t");
        String line = splitString[0] + "\t" + splitString[1];

        sum += Integer.parseInt(splitString[1]);

        if (sum < 100) {
            list.add(line);
        } else {
            if (!list.isEmpty()) {
                for (String val: list) {
                   VALUE.set(val);
                   context.write(KEY, VALUE);
                }
                list.clear();
            }
            VALUE.set(line);
            context.write(KEY, VALUE);
        }
    }
相关问题