黑马程序员技术交流社区

标题: 【上海校区】MapReduce功能实现十---倒排索引(Inverted Index) [打印本页]

作者: 不二晨    时间: 2018-8-22 10:04
标题: 【上海校区】MapReduce功能实现十---倒排索引(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



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编程进行数据分析,测试数据来源于美国专利文献数据



数据源:


解答代码:
运行结果:

[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



作者: 不二晨    时间: 2018-8-23 17:07
奈斯
作者: 不二晨    时间: 2018-8-30 17:17
奈斯,加油加油




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2