Reputation: 55
My reducer gives this o/p
Country-Year,Medals
India-2008,60
United States-2008,1237
Zimbabwe-2008, 2
Namibia-2009,22
China-2009,43
United States-2009,54
And i want this, sorting should happen based on medals and top three should be shown.
Country-Year,Medals
United States-2008,1237
India-2008,60
United States-2009,54
Someone suggested me to do this sorting in custom recordreader(understood that it is used in mapper part) and i browsed through some resources but couldn't find much on sorting. Please share any ideas or link to resources. Advance thanks !
Upvotes: 0
Views: 8395
Reputation: 306
When you aggregate the result of mapper in Reducer class rather than writing it to output take it into a map then sort the map and display result accordingly.
Key = Country-Year , Value = Medals Dummy code to showcase how to implement
public class Medal_reducer extends Reducer<Text,IntWritable, Text , IntWritable> {
// Change access modifier as per your need
public Map<String , Integer > map = new HashMap<String , Integer>();
public void reduce(Text key , Iterable<IntWritable> values ,Context context )
{
// write logic for your reducer
// Enter reduced values in map for each key
for (IntWritable value : values ){
// calculate count
}
map.put(key.toString() , count);
}
public void cleanup(Context context){
//Cleanup is called once at the end to finish off anything for reducer
//Here we will write our final output
Map<String , Integer> sortedMap = new HashMap<String , Integer>();
sortedMap = sortMap(map);
for (Map.Entry<String,Integer> entry = sortedMap.entrySet()){
context.write(new Text(entry.getKey()),new IntWritable(entry.getValue()));
}
}
public Map<String , Integer > sortMap (Map<String,Integer> unsortMap){
Map<String ,Integer> hashmap = new HashMap<String,Integer>();
int count=0;
List<Map.Entry<String,Integer>> list = new LinkedList<Map.Entry<String,Integer>>(unsortMap.entrySet());
//Sorting the list we created from unsorted Map
Collections.sort(list , new Comparator<Map.Entry<String,Integer>>(){
public int compare (Map.Entry<String , Integer> o1 , Map.Entry<String , Integer> o2 ){
//sorting in descending order
return o2.getValue().compareTo(o1.getValue());
}
});
for(Map.Entry<String, Integer> entry : list){
// only writing top 3 in the sorted map
if(count>2)
break;
hashmap.put(entry.getKey(),entry.getValue());
}
return hashmap ;
}
}
Hopefully this will help.
Upvotes: 0
Reputation: 1002
You can implement Map Reduce Top K Design pattern to achieve your objective.
Top K Design pattern will sort your records on values and picks the top k records.
You can go through this link for implementing Top K Design pattern on your data.
Upvotes: 2