import java.io.IOException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; 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.input.FileSplit; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; public class InvertedIndex { public static class InvertedMap extends Mapper<LongWritable, Text, Text, IntWritable> { private Text kText = new Text(); private IntWritable vIntWritable = new IntWritable(1); private FileSplit split; @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String line = value.toString(); String[] lineSplit = line.split("\t"); // 获取文档名称 split = (FileSplit) context.getInputSplit(); int indexOfFile = split.getPath().toString().indexOf("file"); String fileName = split.getPath().toString().substring(indexOfFile); for (int i = 0; i < lineSplit.length; i++) { kText.set(lineSplit[i] + ":" + fileName); context.write(kText, vIntWritable); } } } public static class InvertedConbine extends Reducer<Text, IntWritable, Text, Text> { private Text kText = new Text(); private Text vText = new Text(); protected void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException { // 词频统计 int sum = 0; for (IntWritable v : values) { sum += v.get(); } int indexOf = key.toString().indexOf(":"); kText.set(key.toString().substring(0, indexOf)); vText.set(key.toString().substring(indexOf + 1) + ":" + sum); context.write(kText, vText); } } public static class InvertedReduce extends Reducer<Text, Text, Text, Text> { private Text vText = new Text(); protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { String filelist = new String(); for (Text v : values) { filelist += v.toString() + ";"; } vText.set(filelist); context.write(key, vText); } } public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException { Configuration conf = new Configuration(); Job job = Job.getInstance(conf); job.setJarByClass(InvertedIndex.class); job.setMapperClass(InvertedMap.class); job.setMapOutputKeyClass(Text.class); job.setMapOutputValueClass(IntWritable.class); job.setCombinerClass(InvertedConbine.class); job.setReducerClass(InvertedReduce.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); FileInputFormat.setInputPaths(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true)? 0:1); } }