倒排索引是文件檢索系統裡最常用的資料結構,全文搜索引擎幾乎都建立在它之上。
通常它由「一個單詞或詞組」加上「相關的文件列表」組成,列表中的元素可能是文件 ID,也可能是文件所在位置的 URI。實務上往往還會為每個文件加上權值,用來表示該文件與搜尋內容的相關程度。
假設輸入是兩三個小文件:
/user/root/in1/words.txt → mapreduce is simple /user/root/in1/words1.txt → mapreduce is powerfull and is simple
期望的輸出是每個單字對應到「在哪些文件、各出現幾次」:
and words1.txt:1; is words.txt:1;words1.txt:2; mapreduce words1.txt:1;words.txt:1; powerfull words1.txt:1; simple words1.txt:1;words.txt:1;
關鍵在於 Map 階段要把「文件名稱」一起編進 key 裡,讓同一個單字在不同文件中的計數不會互相混掉;到了 Reduce 階段再把 key 拆開,分組彙整成最終樣子。
public class indexSum {
private static final Log log = LogFactory.getLog(LogCount.class);
/** Map:以「單字:檔案名」為 key,值固定為 1 */
public static class TokenizerMapper1 extends
Mapper<Object, Text, Text, Text> {
private Text key1 = new Text();
private Text value1 = new Text();
public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
FileSplit split = (FileSplit) context.getInputSplit();
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
key1.set(itr.nextToken() + ":" + split.getPath().getName());
value1.set("1");
context.write(key1, value1);
}
}
}
/** Combiner:把 "單字:檔案" 的 1 加總,並還原成 "檔案:次數" */
public static class IntSumReducer extends Reducer<Text, Text, Text, Text> {
private Text result = new Text();
public void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
int sum = 0;
for (Text val : values) sum += Integer.parseInt(val.toString());
int splitIndex = key.toString().indexOf(":");
result.set(key.toString().substring(splitIndex + 1) + ":" + sum);
key.set(key.toString().substring(0, splitIndex));
context.write(key, result);
}
}
/** 真正的 Reducer:把同一單字的 "檔案:次數" 串起來 */
public static class IntSumReducer3 extends Reducer<Text, Text, Text, Text> {
private Text result = new Text();
public void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
String valueArray = new String();
for (Text value : values) valueArray += value.toString() + ";";
result.set(valueArray);
context.write(key, result);
}
}
public static void main(String[] args) throws Exception {
log.info("===============Begin at : " + new Date());
String[] argsTemp = { "hdfs://hadoop11:8020/user/root/in1", "out4" };
args = argsTemp;
File jarFile = EJob.createTempJar("bin");
Configuration conf = new Configuration();
conf.set("hadoop.job.ugi", "root,root");
conf.set("fs.default.name", "hdfs://hadoop11:8020/");
conf.set("mapred.job.tracker", "hadoop11:8021");
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("Usage: wordcount <in> <out>");
System.exit(2);
}
Job job = new Job(conf, "word count");
job.setJarByClass(LogCount.class);
((JobConf) job.getConfiguration()).setJar(jarFile.toString());
job.setMapperClass(TokenizerMapper1.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer3.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
System.exit(job.waitForCompletion(true) ? 0 : 1);
log.info("===============End at : " + new Date());
}
}
第一,FileSplit 是取得「目前這筆資料來自哪個檔案」的正規途徑,比在 value 裡塞檔名乾淨得多。第二,Combiner 在這裡不只是效能優化,它保證了「同一檔案同一單字」在送到 Reducer 前就已經完成局部加總,語意上和 Reducer 一致,所以拿來當 Combiner 是安全的。第三,範例中的 IntSumReducer3 用字串串接累加,資料量一大就會變成 O(n²) 的效能陷阱,正式寫法該改用 StringBuilder。