前言:
从IT跨度到DT,如今的数据每天都在海量的增长。面对如此巨大的数据,如何能让搜索引擎更好的工作呢?本文作为Hadoop系列的第二篇,将介绍分布式情况下搜索引擎的基础实现,即“倒排索引”。 1.问题描述
将所有不同文件里面的关键词进行存储,并实现快速检索。下面假设有3个文件的数据如下:
file1.txt:MapReduce is simplefile2.txt:mapReduce is powerful is simplefile3.txt:Hello MapReduce bye MapReduce
最终应生成如下索引结果:
Hello file3.txt:1MapReduce file3.txt:2;file2.txt:1;file1.txt:1bye file3.txt:1is file2.txt:2;file1.txt:1powerful file2.txt:1simple file2.txt:1;file1.txt:1
--------------------------------------------------------
2.设计
首先,我们对读入的数据利用Map操作进行预处理,如图1:
对比之前的单词计数(WorldCount.java),要实现倒排索引单靠Map和Reduce操作明显无法完成,因此中间我们加入'Combine',即合并操作;具体如图2:
--------------------------------------------------------------
3.代码实现
1 package pro; 2 3 import java.io.IOException; 4 import java.util.StringTokenizer; 5 import org.apache.hadoop.conf.Configuration; 6 import org.apache.hadoop.fs.Path; 7 import org.apache.hadoop.io.IntWritable; 8 import org.apache.hadoop.io.Text; 9 import org.apache.hadoop.mapreduce.Job; 10 import org.apache.hadoop.mapreduce.Mapper; 11 import org.apache.hadoop.mapreduce.Reducer; 12 import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; 13 import org.apache.hadoop.mapreduce.lib.input.FileSplit; 14 import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; 15 import org.apache.hadoop.util.GenericOptionsParser; 16 17 public class InvertedIndex { 18 final static String INPUT_PATH = "hdfs://hadoop0:9000/index_in"; 19 final static String OUTPUT_PATH = "hdfs://hadoop0:9000/index_out"; 20 21 public static class Map extends Mapper
4.测试结果
Hello file3.txt:1;MapReduce file3.txt:2;file1.txt:1;file2.txt:1;bye file3.txt:1;is file1.txt:1;file2.txt:2;powerful file2.txt:1;simple file2.txt:1;file1.txt:1;
Reference:
[1]Hadoop权威指南【A】Tom Wbite
[2]深入云计算·Hadoop应用开发实战详解【A】万川梅 谢正兰
--------------
结语:
从上面的Map---> Combine ----> Reduce操作过程中,我们可以体会到“倒排索引”的过程其实也就是不断组合并拆分字符串的过程,而这也就是Hadoop中MapReduce并行计算的体现。在现今的大部分企业当中,Hadoop主要应用之一就是针对日志进行处理,所以想进军大数据领域的朋友,对于Hadoop的Map/Reduce实现原理可以通过更多的实战操作加深理解。本文仅仅只是牛刀小试,对于Hadoop的深层应用本人也正在慢慢摸索~~