Как найти топ-N записей с помощью MapReduce
Поиск 10 или 20 лучших записей из большого набора данных - это сердце многих систем рекомендаций, а также важный атрибут для анализа данных. Здесь мы обсудим два метода поиска топ-N записей следующим образом.
Метод 1. Сначала давайте определим топ-10 самых просматриваемых фильмов, чтобы понять методы, а затем обобщим его для n записей.
Формат данных:
movie_name и no_of_views (разделены табуляцией)
Используемый подход: Использование TreeMap. Здесь идея состоит в том, чтобы использовать Mappers для поиска локальных топ-10 записей, поскольку может быть много Mappers, работающих параллельно с разными блоками данных файла. И затем все эти 10 лучших локальных записей будут агрегированы в Reducer, где мы найдем 10 лучших глобальных записей для файла.
Пример: Предположим, что файл (30 ТБ) разделен на 3 блока по 10 ТБ каждый, и каждый блок обрабатывается Mapper параллельно, поэтому мы находим 10 лучших записей (локальных) для этого блока. Затем эти данные перемещаются в редуктор, где мы находим актуальные 10 лучших записей из файла movie.txt .
Файл Movie.txt: вы можете просмотреть весь файл, щелкнув здесь
Mapper code:
| importjava.io.*;importjava.util.*;importorg.apache.hadoop.io.Text;importorg.apache.hadoop.io.LongWritable;importorg.apache.hadoop.mapreduce.Mapper; publicclasstop_10_Movies_Mapper extendsMapper<Object,                            Text, Text, LongWritable> {     privateTreeMap<Long, String> tmap;     @Override    publicvoidsetup(Context context) throwsIOException,                                     InterruptedException    {        tmap = newTreeMap<Long, String>();    }     @Override    publicvoidmap(Object key, Text value,       Context context) throwsIOException,                       InterruptedException    {         // input data format => movie_name            // no_of_views  (tab seperated)        // we split the input data        String[] tokens = value.toString().split("	");         String movie_name = tokens[0];        longno_of_views = Long.parseLong(tokens[1]);         // insert data into treeMap,        // we want top 10  viewed movies        // so we pass no_of_views as key        tmap.put(no_of_views, movie_name);         // we remove the first key-value        // if it"s size increases 10        if(tmap.size() > 10)        {            tmap.remove(tmap.firstKey());        }    }     @Override    publicvoidcleanup(Context context) throwsIOException,                                       InterruptedException    {        for(Map.Entry<Long, String> entry : tmap.entrySet())         {             longcount = entry.getKey();            String name = entry.getValue();             context.write(newText(name), newLongWritable(count));        }    }} | 
Объяснение: здесь важно отметить, что мы используем « context.write () » в методе cleanup (), который запускается только один раз в конце жизненного цикла Mapper. Mapper обрабатывает одну пару "ключ-значение" за раз и записывает их как промежуточные выходные данные на локальный диск. Но мы должны обработать весь блок (все пары ключ-значение), чтобы найти top10, перед записью вывода, поэтому мы используем context.write () в cleanup ().
Reducer code:
| importjava.io.IOException;importjava.util.Map;importjava.util.TreeMap; importorg.apache.hadoop.io.LongWritable;importorg.apache.hadoop.io.Text;importorg.apache.hadoop.mapreduce.Reducer; publicclasstop_10_Movies_Reducer extendsReducer<Text,                     LongWritable, LongWritable, Text> {     privateTreeMap<Long, String> tmap2;     @Override    publicvoidsetup(Context context) throwsIOException,                                     InterruptedException    {        tmap2 = newTreeMap<Long, String>();    }     @Override    publicvoidreduce(Text key, Iterable<LongWritable> values,      Context context) throwsIOException, InterruptedException    {         // input data from mapper        // key                values        // movie_name         [ count ]        String name = key.toString();        longcount = 0;         for(LongWritable val : values)        {            count = val.get();        }         // insert data into treeMap,        // we want top 10 viewed movies        // so we pass count as key        tmap2.put(count, name);         // we remove the first key-value        // if it"s size increases 10        if(tmap2.size() > 10)        {            tmap2.remove(tmap2.firstKey());        }    }     @Override    publicvoidcleanup(Context context) throwsIOException,                                       InterruptedException    {         for(Map.Entry<Long, String> entry : tmap2.entrySet())         {             longcount = entry.getKey();            String name = entry.getValue();            context.write(newLongWritable(count), newText(name));        }    }} | 
Объяснение: Та же логика, что и у mapper. Reducer обрабатывает одну пару ключ-значение за раз и записывает их в качестве окончательного вывода в HDFS. Но мы должны обработать все пары ключ-значение, чтобы найти top10, перед записью вывода, поэтому мы используем cleanup () .
Код драйвера:
| importorg.apache.hadoop.conf.Configuration;importorg.apache.hadoop.fs.Path;importorg.apache.hadoop.io.LongWritable;importorg.apache.hadoop.io.Text;importorg.apache.hadoop.mapreduce.Job;importorg.apache.hadoop.mapreduce.lib.input.FileInputFormat;importorg.apache.hadoop.mapreduce.lib.output.FileOutputFormat;importorg.apache.hadoop.util.GenericOptionsParser; publicclassDriver {     publicstaticvoidmain(String[] args) throwsException    {        Configuration conf = newConfiguration();        String[] otherArgs = newGenericOptionsParser(conf,                                  args).getRemainingArgs();         // if less than two paths         // provided will show error        if(otherArgs.length < 2)         {            System.err.println("Error: please provide two paths");            System.exit(2);        }         Job job = Job.getInstance(conf, "top 10");        job.setJarByClass(Driver.class);         job.setMapperClass(top_10_Movies_Mapper.class);        job.setReducerClass(top_10_Movies_Reducer.class);         job.setMapOutputKeyClass(Text.class);        job.setMapOutputValueClass(LongWritable.class);         job.setOutputKeyClass(LongWritable.class);        job.setOutputValueClass(Text.class);         FileInputFormat.addInputPath(job, newPath(otherArgs[0]));        FileOutputFormat.setOutputPath(job, newPath(otherArgs[1]));         System.exit(job.waitForCompletion(true) ? 0: 1);    }} | 
Running the jar file:
- We export all the classes as jar files.
- We move our file movie.txt from local file system to /geeksInput in HDFS.bin/hdfs dfs -put ../Desktop/movie.txt /geeksInput 
- We now run the yarn services to run the jar file.bin/yarn jar jar_file_location package_Name.Driver_classname input_path output_path  Code running:  Output: In ascending order  Method 2: This method is based on the property that output from Mapper is sorted based on key before going to the reducer. Let’s print in descending order this time. Now to do so we just multiply the key with -1 in mapper, so that after sorting higher numbers appears on top (magnitude wise). And now we just print the 10 records removing the -ve sign from keys. Example: At reducer Keys After sorting: 23 25 28 .. If key multiplied with -1 Keys After sorting: -28 -25 -23 .. Mapper Code: importjava.io.*;importorg.apache.hadoop.io.Text;importorg.apache.hadoop.io.LongWritable;importorg.apache.hadoop.mapreduce.Mapper;publicclasstop_10_Movies2_MapperextendsMapper<Object,Text, LongWritable, Text> {// data format => movie_name// no_of_views (tab seperated)@Overridepublicvoidmap(Object key, Text value,Context context)throwsIOException,InterruptedException{String[] tokens = value.toString().split(" ");String movie_name = tokens[0];longno_of_views = Long.parseLong(tokens[1]);no_of_views = (-1) * no_of_views;context.write(newLongWritable(no_of_views),newText(movie_name));}}Reducer Code: importjava.io.*;importorg.apache.hadoop.io.Text;importorg.apache.hadoop.io.LongWritable;importorg.apache.hadoop.mapreduce.Reducer;publicclasstop_10_Movies2_ReducerextendsReducer<LongWritable,Text, LongWritable, Text> {staticintcount;@Overridepublicvoidsetup(Context context)throwsIOException,InterruptedException{count =0;}@Overridepublicvoidreduce(LongWritable key, Iterable<Text> values,Context context)throwsIOException, InterruptedException{// key values//-ve of no_of_views [ movie_name ..]longno_of_views = (-1) * key.get();String movie_name =null;for(Text val : values){movie_name = val.toString();}// we just write 10 records as outputif(count <10){context.write(newLongWritable(no_of_views),newText(movie_name));count++;}}}Explanation: Here, setup() method is the method which runs only once at the beginning 
 in the life time of a Reducer/Mapper. Since we want to print only 10 records we define the count variable in setup() method.Driver Code: importorg.apache.hadoop.conf.Configuration;importorg.apache.hadoop.fs.Path;importorg.apache.hadoop.io.LongWritable;importorg.apache.hadoop.io.Text;importorg.apache.hadoop.mapreduce.Job;importorg.apache.hadoop.mapreduce.lib.input.FileInputFormat;importorg.apache.hadoop.mapreduce.lib.output.FileOutputFormat;importorg.apache.hadoop.util.GenericOptionsParser;publicclassDriver {publicstaticvoidmain(String[] args)throwsException{Configuration conf =newConfiguration();String[] otherArgs =newGenericOptionsParser(conf, args).getRemainingArgs();// if less than two paths// provided will show errorif(otherArgs.length <2){System.err.println("Error: please provide two paths");System.exit(2);}Job job = Job.getInstance(conf,"top_10 program_2");job.setJarByClass(Driver.class);job.setMapperClass(top_10_Movies2_Mapper.class);job.setReducerClass(top_10_Movies2_Reducer.class);job.setMapOutputKeyClass(LongWritable.class);job.setMapOutputValueClass(Text.class);job.setOutputKeyClass(LongWritable.class);job.setOutputValueClass(Text.class);FileInputFormat.addInputPath(job,newPath(otherArgs[0]));FileOutputFormat.setOutputPath(job,newPath(otherArgs[1]));System.exit(job.waitForCompletion(true) ?0:1);}}Running the jar file: We now run the yarn services to run the jar file  Code running:  Output:  Note: One important thing to observe is that though Method-2 is easy to implement but it is not very efficient compared to Method-1 as we are passing all key-value pairs to reducer i.e. there is a lot of data movement which may lead to bottleneck situations. But in Method-1 we are only passing 10 key-value pairs to the reducer. Generalizing it for ‘n’ records: Lets modify our second program for some ‘n’ records whose value we may pass at runtime. First some points to observe: 
- We make our custom parameter using set() method
configuration_object.set(String name, String value) 
- This value can be accessed in any Mapper/Reducer by using get() method
Configuration conf = context.getConfiguration(); // we will store value in String variable String value = conf.get(String name); Mapper code: The Mapper code will remain same as we are not using the value there. Reducer code: Here we make some changes in the setup() method. importjava.io.IOException;importorg.apache.hadoop.io.LongWritable;importorg.apache.hadoop.io.Text;importorg.apache.hadoop.mapreduce.Reducer;importorg.apache.hadoop.conf.Configuration;publicclasstop_n_ReducerextendsReducer<LongWritable,Text, LongWritable, Text> {staticintcount;@Overridepublicvoidsetup(Context context)throwsIOException,InterruptedException{Configuration conf = context.getConfiguration();// we will use the value passed in myValue at runtimeString param = conf.get("myValue");// converting the String value to integercount = Integer.parseInt(param);}@Overridepublicvoidreduce(LongWritable key, Iterable<Text> values,Context context)throwsIOException, InterruptedException{longno_of_views = (-1) * key.get();String movie_name =null;for(Text val : values) {movie_name = val.toString();}/
- We make our custom parameter using set() method