任务描述:
有一批电话清单,记录了用户A拨打给用户B的记录
做一个倒排索引,记录拨打给用户B所有的用户A、
example data:
13614004876 110
18940084808 10086
13342445911 10001
13614004876 120
18940084808 1008611
13342445911 110
15847985621 10000
code:
<span style="font-size:14px;">package mrTest;
import java.io.IOException;
import java.util.Date;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import com.ibm.icu.text.SimpleDateFormat;
public class daopaisuoyin {
enum Counter{
LINESKIP, //出错的行
}
public static class Map extends Mapper<Object, Text, Text, Text>{
public void map(Object key,Text value,Context context){
String line = value.toString();
try{
String[] lineSplit = line.split(" ");
String newKey = lineSplit[0];
String newValue = lineSplit[1];
context.write(new Text(newKey), new Text(newValue));
}catch(Exception e){
context.getCounter(Counter.LINESKIP).increment(1);
return;
}
}
}
public static class Reduce extends Reducer<Text, Text, Text, Text>{
public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException{
String result = "";
for (Text value : values) {
result += value.toString() + " # ";
}
context.write(key, new Text(result));
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
// TODO Auto-generated method stub
Job job = new Job(new Configuration(), " 倒排索引 ");
job.setJarByClass(daopaisuoyin.class);
job.setNumReduceTasks(1);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
//记录时间
SimpleDateFormat sdf = new SimpleDateFormat();
Date start = new Date(); //开始时间
int result = job.waitForCompletion(true)? 0 : 1; //任务开始
Date end = new Date(); //结束时间
float time = (float)((end.getTime() - start.getTime()) / 60000.0); //任务开始到结束经历的时间
System.out.println("Job 开始的时间为:" + start);
System.out.println("Job 结束的时间为:" + end);
System.out.println("Job 经历的时间为:" + time + "分钟");
System.out.println("Job 的名字:" + job.getJobName());
System.out.println("Job 是否成功:" + job.isSuccessful() );
System.out.println("Job 输入的行数:" + job.getCounters().findCounter("org.apache.hadoop.mapred.Task$Counter", "MAP_INPUT_RECORDS").getValue());
System.out.println("Job 输出的行数:" + job.getCounters().findCounter("org.apache.hadoop.mapred.Task$Counter", "MAP_OUTPUT_RECORDS").getValue());
System.exit(result); //判断是否结束
}
}
</span>
结果显示:
扫一扫 关注微信公众号!号主 专注于搜索和推荐系统,尝试使用算法去更好的服务于用户,包括但不局限于机器学习,深度学习,强化学习,自然语言理解,知识图谱,还不定时分享技术,资料,思考等文章!
【技术服务】,详情点击查看:https://mp.weixin.qq.com/s/PtX9ukKRBmazAWARprGIAg