MapReduce功能实现十---倒排索引(Inverted Index)

MapReduce功能实现系列:

MapReduce功能实现一---Hbase和Hdfs之间数据相互转换

MapReduce功能实现二---排序

MapReduce功能实现三---Top N

MapReduce功能实现四---小综合(从hbase中读取数据统计并在hdfs中降序输出Top 3)

MapReduce功能实现五---去重(Distinct)、计数(Count)

MapReduce功能实现六---最大值(Max)、求和(Sum)、平均值(Avg)

MapReduce功能实现七---小综合(多个job串行处理计算平均值)

MapReduce功能实现八---分区(Partition)

MapReduce功能实现九---Pv、Uv

MapReduce功能实现十---倒排索引(Inverted Index)

MapReduce功能实现十一---join


前言:"倒排索引"是文档检索系统中最常用的数据结构,被广泛地应用于全文搜索引擎。它主要是用来存储某个单词(或词组)在一个文档或一组文档中的存储位置的映射,即提供了一种根据内容来查找文档的方式。由于不是根据文档来确定文档所包含的内容,而是进行相反的操作,因而称为倒排索引(Inverted Index)


1.模拟数据:
[hadoop@h71 q1]$ vi file1.txt
mapreduce is simple

[hadoop@h71 q1]$ vi file2.txt
mapreduce is powerful is simple

[hadoop@h71 q1]$ vi file3.txt
hello mapreduce bye mapreduce


补充:
(1)这里存在两个问题:第一,<key,value>对只能有两个值,在不使用Hadoop自定义数据类型的情况下,需要根据情况将其中两个值合并成一个值,作为key或value值;第二,通过一个Reduce过程无法同时完成词频统计和生成文档列表,所以必须增加一个Combine过程完成词频统计。
(2)这里讲单词和URL组成key值(如"MapReduce:file1.txt"),将词频作为value,这样做的好处是可以利用MapReduce框架自带的Map端排序,将同一文档的相同单词的词频组成列表,传递给Combine过程,实现类似于WordCount的功能。
(3)Combine过程:经过map方法处理后,Combine过程将key值相同的value值累加,得到一个单词在文档在文档中的词频,如果直接输出作为Reduce过程的输入,在Shuffle过程时将面临一个问题:所有具有相同单词的记录(由单词、URL和词频组成)应该交由同一个Reducer处理,但当前的key值无法保证这一点,所以必须修改key值和value值。这次将单词作为key值,URL和词频组成value值(如"file1.txt:1")。这样做的好处是可以利用MapReduce框架默认的HashPartitioner类完成Shuffle过程,将相同单词的所有记录发送给同一个Reducer进行处理。


2.将数据上传到hdfs上:
[hadoop@h71 q1]$ hadoop fs -mkdir /user/hadoop/index_in

[hadoop@h71 q1]$ hadoop fs -put file1.txt /user/hadoop/index_in
[hadoop@h71 q1]$ hadoop fs -put file2.txt /user/hadoop/index_in
[hadoop@h71 q1]$ hadoop fs -put file3.txt /user/hadoop/index_in


3.[hadoop@h71 q1]$ vi InvertedIndex.java

[java]  view plain  copy
  1. import java.io.IOException;  
  2. import java.util.StringTokenizer;  
  3.   
  4. import org.apache.hadoop.conf.Configuration;  
  5. import org.apache.hadoop.fs.Path;  
  6. import org.apache.hadoop.io.Text;  
  7. import org.apache.hadoop.mapreduce.Job;  
  8. import org.apache.hadoop.mapreduce.Mapper;  
  9. import org.apache.hadoop.mapreduce.Reducer;  
  10. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;  
  11. import org.apache.hadoop.mapreduce.lib.input.FileSplit;  
  12. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;  
  13. import org.apache.hadoop.util.GenericOptionsParser;  
  14.    
  15. public class InvertedIndex {  
  16.    
  17.     public static class Map extends Mapper<Object, Text, Text, Text> {  
  18.         private Text keyInfo = new Text(); // 存储单词和URL组合  
  19.         private Text valueInfo = new Text(); // 存储词频  
  20.         private FileSplit split; // 存储Split对象  
  21.         // 实现map函数  
  22.         public void map(Object key, Text value, Context context) throws IOException, InterruptedException {  
  23.             // 获得<key,value>对所属的FileSplit对象  
  24.             split = (FileSplit) context.getInputSplit();  
  25.             StringTokenizer itr = new StringTokenizer(value.toString());  
  26.             while (itr.hasMoreTokens()) {  
  27.                 // key值由单词和URL组成,如"MapReduce:file1.txt"  
  28.                 // 获取文件的完整路径  
  29.                 // keyInfo.set(itr.nextToken()+":"+split.getPath().toString());  
  30.                 // 这里为了好看,只获取文件的名称。  
  31.                 int splitIndex = split.getPath().toString().indexOf("file");  
  32.                 keyInfo.set(itr.nextToken() + ":" + split.getPath().toString().substring(splitIndex));  
  33.                 // 词频初始化为1  
  34.                 valueInfo.set("1");   
  35.                 context.write(keyInfo, valueInfo);  
  36.             }  
  37.         }  
  38.     }  
  39.   
  40.     public static class Combine extends Reducer<Text, Text, Text, Text> {  
  41.         private Text info = new Text();  
  42.         // 实现reduce函数  
  43.         public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {  
  44.             // 统计词频  
  45.             int sum = 0;  
  46.             for (Text value : values) {  
  47.                 sum += Integer.parseInt(value.toString());  
  48.             }  
  49.             int splitIndex = key.toString().indexOf(":");  
  50.             // 重新设置value值由URL和词频组成  
  51.             info.set(key.toString().substring(splitIndex + 1) + ":" + sum);  
  52.             // 重新设置key值为单词  
  53.             key.set(key.toString().substring(0, splitIndex));  
  54.             context.write(key, info);  
  55.         }  
  56.     }  
  57.   
  58.     public static class Reduce extends Reducer<Text, Text, Text, Text> {  
  59.         private Text result = new Text();  
  60.         // 实现reduce函数  
  61.         public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {  
  62.             // 生成文档列表  
  63.             String fileList = new String();  
  64.             for (Text value : values) {  
  65.                 fileList += value.toString() + ";";  
  66.             }   
  67.             result.set(fileList);  
  68.             context.write(key, result);  
  69.         }  
  70.     }  
  71.   
  72.     public static void main(String[] args) throws Exception {  
  73.         Configuration conf = new Configuration();  
  74.         conf.set("mapred.jar""ii.jar");  
  75.   
  76.         String[] ioArgs = new String[] { "index_in""index_out" };  
  77.         String[] otherArgs = new GenericOptionsParser(conf, ioArgs).getRemainingArgs();  
  78.   
  79.         if (otherArgs.length != 2) {  
  80.             System.err.println("Usage: Inverted Index <in> <out>");  
  81.             System.exit(2);  
  82.         }  
  83.   
  84.         Job job = new Job(conf, "Inverted Index");  
  85.         job.setJarByClass(InvertedIndex.class);  
  86.           
  87.         // 设置Map、Combine和Reduce处理类  
  88.         job.setMapperClass(Map.class);  
  89.         job.setCombinerClass(Combine.class);  
  90.         job.setReducerClass(Reduce.class);  
  91.   
  92.         // 设置Map输出类型  
  93.         job.setMapOutputKeyClass(Text.class);  
  94.         job.setMapOutputValueClass(Text.class);  
  95.   
  96.         // 设置Reduce输出类型  
  97.         job.setOutputKeyClass(Text.class);  
  98.         job.setOutputValueClass(Text.class);  
  99.   
  100.         // 设置输入和输出目录  
  101.         FileInputFormat.addInputPath(job, new Path(otherArgs[0]));  
  102.         FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));  
  103.         System.exit(job.waitForCompletion(true) ? 0 : 1);  
  104.     }  
  105. }  

4.知识点延伸:
(1)int indexOf(String str) :返回第一次出现的指定子字符串在此字符串中的索引。 
(2)int indexOf(String str, int startIndex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。 
(3)int lastIndexOf(String str) :返回在此字符串中最右边出现的指定子字符串的索引。 
(4)int lastIndexOf(String str, int startIndex) :从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。
(5)indexOf("a")是从字符串的0个位置开始查找的。比如你的字符串:"abca",那么程序将会输出0,之后的a是不判断的。
(6)str=str.substring(int beginIndex);截取掉str从首字母起长度为beginIndex的字符串,将剩余字符串赋值给str
(7)str=str.substring(int beginIndex,int endIndex);截取str中从beginIndex开始至endIndex结束时的字符串,并将其赋值给str


5.执行:
[hadoop@h71 q1]$ /usr/jdk1.7.0_25/bin/javac InvertedIndex.java
[hadoop@h71 q1]$ /usr/jdk1.7.0_25/bin/jar cvf xx.jar InvertedIndex*class
[hadoop@h71 q1]$ hadoop jar xx.jar InvertedIndex


6.查看结果:
[hadoop@h71 q1]$ hadoop fs -cat /user/hadoop/index_out/part-r-00000
bye     file3.txt:1;
hello   file3.txt:1;
is      file1.txt:1;file2.txt:2;
mapreduce       file2.txt:1;file3.txt:2;file1.txt:1;
powerful        file2.txt:1;
simple  file2.txt:1;file1.txt:1;


号外:有一网友给我发私信说遇到了个问题,让我帮一下他

题目:将数据源文件上传到HDFS系统进行存储,然后基于MapReduce编程进行数据分析,测试数据来源于美国专利文献数据



数据源:

[plain]  view plain  copy
  1. 5855015,1998,14242,1995,"US","CA",715526,2,38,707,2,22,5,4,1,0.5,0.32,2,3.8,0,0,0,0  
  2. 5855016,1998,14242,1995,"US","CA",147695,2,2,707,2,22,8,0,1,,0.5938,,12.375,0,0,,  
  3. 5855018,1998,14242,1996,"IL","",636865,3,18,707,2,22,5,0,1,,0.72,,2.6,0,0,,  
  4. 5855019,1998,14242,1997,"US","CA",280070,2,18,707,2,22,7,0,1,,0,,5.4286,0.1429,0.1429,,  
  5. 5855020,1998,14242,1996,"US","CA",732759,2,10,707,2,22,5,1,1,0,0.48,1,0.4,0.25,0.2,0,0  
  6. 5855021,1999,14249,1996,"US","MI",,1,,2,6,63,9,0,0.5556,,0,,40.5556,,,,  
  7. 5855022,1999,14249,1998,"US","IL",,1,,2,6,63,9,0,0.8889,,0.375,,18.8889,,,,  
  8. 5855023,1999,14249,1996,"US","PA",,1,,2,6,63,13,0,0.1538,,0,,63.6154,,,,  
  9. 5855024,1999,14249,1997,"US","NJ",749658,2,,4,6,65,2,0,0,,,,94.5,0,0,,  
  10. 5855025,1999,14249,1997,"US","CA",,1,,4,6,65,9,0,0.8889,,0.2188,,18.4444,,,,  
  11. 5855026,1999,14249,1997,"US","KS",,1,,2,6,63,5,0,0.4,,0,,30.6,,,,  
  12. 5855027,1999,14249,1998,"GB","",,1,,4,6,65,10,0,0.4,,0.625,,33,,,,  
解答代码:

[java]  view plain  copy
  1. import java.io.IOException;  
  2.   
  3. import org.apache.hadoop.conf.Configuration;  
  4. import org.apache.hadoop.fs.Path;  
  5. import org.apache.hadoop.io.Text;  
  6. import org.apache.hadoop.mapreduce.Job;  
  7. import org.apache.hadoop.mapreduce.Mapper;  
  8. import org.apache.hadoop.mapreduce.Reducer;  
  9. import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;  
  10. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;  
  11. import org.apache.hadoop.util.GenericOptionsParser;  
  12.      
  13. public class InvertedIndex {    
  14.       
  15.     public static class Map extends Mapper<Object, Text, Text, Text> {    
  16.         private final static Text one = new Text("1");    
  17.         private Text word = new Text();  
  18.         public void map(Object key, Text value, Context context) throws IOException, InterruptedException {    
  19.             String line[] = value.toString().split(",");    
  20.             word.set(line[4].substring(1, line[4].length()-1)+":"+line[1]);    
  21.             context.write(word, one);  
  22.         }  
  23.     }    
  24.     
  25.     public static class Combine extends Reducer<Text, Text, Text, Text> {    
  26.         private Text info = new Text();    
  27.         // 实现reduce函数    
  28.         public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {    
  29.             // 统计词频    
  30.             int sum = 0;    
  31.             for (Text value : values) {    
  32.                 sum += Integer.parseInt(value.toString());    
  33.             }    
  34.             int splitIndex = key.toString().indexOf(":");    
  35.             // 重新设置value值由URL和词频组成    
  36.             info.set("<"+key.toString().substring(splitIndex + 1) + ":" + sum+">");    
  37.             // 重新设置key值为单词    
  38.             key.set(key.toString().substring(0, splitIndex));    
  39.             context.write(key, info);    
  40.         }    
  41.     }    
  42.     
  43.     public static class Reduce extends Reducer<Text, Text, Text, Text> {    
  44.         private Text result = new Text();    
  45.         // 实现reduce函数    
  46.         public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {    
  47.             // 生成文档列表    
  48.             String fileList = new String();    
  49.             for (Text value : values) {  
  50.                 fileList += value.toString() + ",";  
  51.             }     
  52.             result.set(fileList.substring(0,fileList.length()-1));    
  53.             context.write(key, result);    
  54.         }    
  55.     }    
  56.     
  57.     public static void main(String[] args) throws Exception {    
  58.         Configuration conf = new Configuration();    
  59.         conf.set("mapred.jar""ii.jar");    
  60.     
  61.         String[] ioArgs = new String[] { "index_in""index_out" };    
  62.         String[] otherArgs = new GenericOptionsParser(conf, ioArgs).getRemainingArgs();    
  63.     
  64.         if (otherArgs.length != 2) {    
  65.             System.err.println("Usage: Inverted Index <in> <out>");    
  66.             System.exit(2);    
  67.         }    
  68.     
  69.         Job job = new Job(conf, "Inverted Index");    
  70.         job.setJarByClass(InvertedIndex.class);    
  71.             
  72.         // 设置Map、Combine和Reduce处理类    
  73.         job.setMapperClass(Map.class);    
  74.         job.setCombinerClass(Combine.class);    
  75.         job.setReducerClass(Reduce.class);    
  76.     
  77.         // 设置Map输出类型    
  78.         job.setMapOutputKeyClass(Text.class);    
  79.         job.setMapOutputValueClass(Text.class);    
  80.     
  81.         // 设置Reduce输出类型    
  82.         job.setOutputKeyClass(Text.class);    
  83.         job.setOutputValueClass(Text.class);    
  84.     
  85.         // 设置输入和输出目录    
  86.         FileInputFormat.addInputPath(job, new Path(otherArgs[0]));    
  87.         FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));    
  88.         System.exit(job.waitForCompletion(true) ? 0 : 1);    
  89.     }    
  90. }  
运行结果:

[hadoop@h40 hui]$ hadoop fs -cat /user/hadoop/index_out/part-r-00000
GB      <1999:1>
IL      <1998:1>
US      <1998:4>,<1999:6>


版权声明:本文为博主原创文章,请尊重劳动成果,觉得不错就在文章下方顶一下呗,转载请标明原地址。 https://blog.csdn.net/m0_37739193/article/details/76572512
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值