目的:
产生一个数据集的索引以便提供更快的搜索或数据丰富能力。
动机:
对大的数据集建立一个关键字的索引,通常可以方便通过指定关键字搜索到其包含特定值的对应记录。尽管创建倒排索引的过程需要预先进行额外的处理,但花费时间做预处理可以极大地缩减查询时所需要的时间。
适用场景:
倒排索引通常用在需要快速搜索查询响应的场景。可以对一个查询的结果进行预处理并存入数据库中。
真实场景:
搜索引擎通过创建索引来提高搜索性能。
假设输入一个关键字,让搜索引擎的爬虫去抓取网上的数据并创建一个页面的列表返回给你,这样的查询将花费非常长的时间才能完成。通过建立倒排索引,搜索引擎可以预先知道关键字所对应的网页,因此只要简单地将相关内容展示给用户就可以了。这样的索引通常也会存储在一个数据库中来提高检索的效率。建立一个倒排索引的工程对MapReduce来说非常简单,因为MapReduce框架将负责处理大部分工作。
我们创建测试数据如下:
www.baidu.com zhangsan lisi wangwu renliu
www.google.com zhangsan lisi wangwu
www.sohu.com zhangsan lisi
www.163.com zhangsan
每行数据在模拟一个网页,我们约定第一个field代表url,后面字段代表该网页中出现的关键字
通过倒排索引我们将得到如下结果:
zhangsan www.baidu.com www.google.com www.sohu.com www.163.com
lisi www.baidu.com www.google.com www.sohu.com
wangwu www.baidu.com www.google.com
renliu www.baudu.com
我们可以看出,数据本来是以url作为索引、关键字为值的,经过倒排关键字称为了索引、url为值。这样就可以快速查到关键字对应的url。
package com.mr.invertedIndex;
import java.io.IOException;
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;
/**
* 倒排索引
*
* @author luobao
*
*/
public class inverteIndex {
public static class MyMapper extends Mapper<Object, Text, Text, Text> {
public void map(Object key, Text value, Context context)
throws IOException, InterruptedException {
String[] arrStr = value.toString().split(" ");
for (int i = 1; i < arrStr.length; i++) {
context.write(new Text(arrStr[i]), new Text(arrStr[0]));
}
}
}
public static class MyReducer extends Reducer<Text, Text, Text, Text> {
public void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Text val : values) {
if (first) {
result.append(val.toString());
first = false;
} else {
result.append(" " + val.toString());
}
}
context.write(key, new Text(result.toString()));
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf);
job.setJarByClass(inverteIndex.class);
job.setMapperClass(MyMapper.class);
job.setCombinerClass(MyReducer.class);
job.setReducerClass(MyReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job, new Path(
"hdfs://192.168.40.186:9000/input/invertedIndex"));
FileOutputFormat.setOutputPath(job, new Path(
"hdfs://192.168.40.186:9000/output"));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}