Что если не использовать метод setup () и closeup () в MapReduce? - PullRequest
1 голос
/ 08 ноября 2019

Скажем, у меня есть маппер, как показано ниже, класс Mapper получает локальные топ-10 для каждого маппера

public class TopTenMapper extends Mapper<LongWritable, Text, Text, LongWritable> {

    private TreeMap<Long, String> tmap;
    // Called once in the beginning before each map method
    @Override
    public void setup(Context context) throws IOException, InterruptedException {
        tmap = new TreeMap<Long, String>();
    }

    // Called once for each key/value pair in the input split
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        String[] tokens = value.toString().split("\\t");
        String streetName = tokens[0];
        Long numCrimes = Long.parseLong(tokens[1]);
        tmap.put(numCrimes, streetName);
        if(tmap.size() > 10){
            tmap.remove(tmap.firstKey());
        }
    }

    // Called once at the end of the task
    @Override
    protected void cleanup(Context context) throws IOException, InterruptedException {
        for(Map.Entry<Long, String> entry : tmap.entrySet()){
            context.write(new Text(entry.getValue()), new LongWritable(entry.getKey()));
        }
    }
}

Я получил, что setup() вызывается один раз перед map(), а cleanup() вызывается один раз перед выходом из задачи карты. Но можно ли просто поместить код setup () в начале карты (), добавить код cleanup () в конец карты ()?

public class TopTenMapper extends Mapper<LongWritable, Text, Text, LongWritable> {

    private TreeMap<Long, String> tmap;

    // Called once for each key/value pair in the input split
    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        tmap = new TreeMap<Long, String>();

        String[] tokens = value.toString().split("\\t");
        String streetName = tokens[0];
        Long numCrimes = Long.parseLong(tokens[1]);
        tmap.put(numCrimes, streetName);
        if(tmap.size() > 10){
            tmap.remove(tmap.firstKey());
        }

        for(Map.Entry<Long, String> entry : tmap.entrySet()){
            context.write(new Text(entry.getValue()), new LongWritable(entry.getKey()));
        }
    }
}

Я думаю, что tmap все еще инициализируется при каждом запуске задачи карты, не так ли? По каким причинам и сценариям я должен использовать методы setup() и cleanup()?

1 Ответ

0 голосов
/ 08 ноября 2019

map() вызывается один раз для каждой входной пары ключ-значение. Сам класс TopTenMapper (и, следовательно, setup()) инициализируется только один раз для каждой задачи карты.

Во втором примере с tmap = new TreeMap<Long, String>(); внутри map() вы никогда не получите верхдесять, у этой карты будет только одно значение.

...