hadoop倒排索引实验报告

合集下载

实验倒排索引的构建及向量空间的模型检索

实验倒排索引的构建及向量空间的模型检索

实验倒排索引的构建及向量空间的模型检索下载提示:该文档是本店铺精心编制而成的,希望大家下载后,能够帮助大家解决实际问题。

文档下载后可定制修改,请根据实际需要进行调整和使用,谢谢!本店铺为大家提供各种类型的实用资料,如教育随笔、日记赏析、句子摘抄、古诗大全、经典美文、话题作文、工作总结、词语解析、文案摘录、其他资料等等,想了解不同资料格式和写法,敬请关注!Download tips: This document is carefully compiled by this editor. I hope that after you download it, it can help you solve practical problems. The document can be customized and modified after downloading, please adjust and use it according to actual needs, thank you! In addition, this shop provides you with various types of practical materials, such as educational essays, diary appreciation, sentence excerpts, ancient poems, classic articles, topic composition, work summary, word parsing, copy excerpts, other materials and so on, want to know different data formats and writing methods, please pay attention!实验倒排索引的构建及向量空间的模型检索一、引言在信息检索领域,倒排索引是一种重要的数据结构,被广泛应用于搜索引擎和文本检索系统中。

Hadoop中的数据索引和查询优化技术解析

Hadoop中的数据索引和查询优化技术解析

Hadoop中的数据索引和查询优化技术解析Hadoop是一种开源的分布式计算框架,被广泛应用于大数据处理和分析。

在Hadoop中,数据索引和查询优化是关键的技术,它们可以提高数据的访问效率和查询性能。

本文将对Hadoop中的数据索引和查询优化技术进行解析。

一、数据索引技术数据索引是一种用于加速数据访问的技术,它通过建立索引结构来提供快速的数据定位和检索能力。

在Hadoop中,常用的数据索引技术包括B树索引、倒排索引和压缩索引。

1. B树索引B树是一种多路平衡查找树,它可以在有序数据上进行高效的查找操作。

在Hadoop中,B树索引常被用于加速数据的范围查询。

通过将数据按照某个属性进行排序,并构建B树索引,可以使得范围查询的性能得到显著提升。

2. 倒排索引倒排索引是一种常用的文本检索技术,它将文档中的每个单词映射到包含该单词的文档列表中。

在Hadoop中,倒排索引常被用于加速文本数据的关键词搜索。

通过构建倒排索引,可以快速定位包含指定关键词的文档。

3. 压缩索引压缩索引是一种将索引数据进行压缩存储的技术,它可以减小索引的存储空间,并提高索引的读取性能。

在Hadoop中,由于数据量庞大,索引的存储和读取成本往往较高。

通过采用压缩索引技术,可以在一定程度上减小存储空间,提高索引的读取效率。

二、查询优化技术查询优化是指通过改变查询的执行方式,使得查询的执行效率得到提升的一种技术。

在Hadoop中,常用的查询优化技术包括查询重写、查询优化器和查询计划生成器。

1. 查询重写查询重写是指对用户提交的查询进行改写,以使得查询的执行效率得到提升。

在Hadoop中,查询重写常用于优化复杂查询和多表关联查询。

通过改变查询的语法结构或者调整查询的执行顺序,可以减少查询的执行时间和资源消耗。

2. 查询优化器查询优化器是一种自动化工具,用于选择最优的查询执行计划。

在Hadoop中,查询优化器可以根据查询的特点和数据的分布情况,选择最适合的查询执行计划。

hadoop分析

hadoop分析

1.前言学习hadoop的童鞋,倒排索引这个算法还是挺重要的。

这是以后展开工作的基础。

首先,我们来认识下什么是倒拍索引:倒排索引简单地就是:根据单词,返回它在哪个文件中出现过,而且频率是多少的结果。

这就像百度里的搜索,你输入一个关键字,那么百度引擎就迅速的在它的服务器里找到有该关键字的文件,并根据频率和其他一些策略(如页面点击投票率)等来给你返回结果。

这个过程中,倒排索引就起到很关键的作用。

2.分析设计倒排索引涉及几个过程:Map过程,Combine过程,Reduce过程。

下面我们来分析以上的过程。

2.1Map过程当你把需要处理的文档上传到hdfs时,首先默认的TextInputFormat类对输入的文件进行处理,得到文件中每一行的偏移量和这一行内容的键值对<偏移量,内容>做为map的输入。

在改写map函数的时候,我们就需要考虑,怎么设计key和value的值来适合MapReduce框架,从而得到正确的结果。

由于我们要得到单词,所属的文档URL,词频,而<key,value>只有两个值,那么就必须得合并其中得两个信息了。

这里我们设计key=单词+URL,value=词频。

即map得输出为<单词+URL,词频>,之所以将单词+URL做为key,时利用MapReduce框架自带得Map端进行排序。

下面举个简单得例子:图1 map过程输入/输出2.2 Combine过程combine过程将key值相同得value值累加,得到一个单词在文档上得词频。

但是为了把相同得key交给同一个reduce处理,我们需要设计为key=单词,value=URL+词频图2 Combin过程输入/输出2.3Reduce过程reduce过程其实就是一个合并的过程了,只需将相同的key值的value值合并成倒排索引需要的格式即可。

图3 reduce过程输入/输出。

Hadoop实现对Value倒序排序

Hadoop实现对Value倒序排序

Hadoop实现对Value倒序排序数据源A 2B 9C 4D 9Z 42要实现的输出Z 42D 9B 9C 4A 2看字符顺序,其实什么也没有,只是按照后⾯的数字进⾏⼀次倒序排序,实现思路,1利⽤hadoop⾃带的排序功能,2.KV互换实现代码public class SVJob {public static void main(String[] args) throws IOException,InterruptedException, ClassNotFoundException {Configuration conf = new Configuration();conf.set("mapred.job.tracker", "192.168.9.181:9001");String[] ars = new String[] {"hdfs://192.168.9.181:9000/user/hadoop/input/examples/SortByValue/","hdfs://192.168.9.181:9000/user/hadoop/output/examples/SortByValue" };String[] otherArgs = new GenericOptionsParser(conf, ars).getRemainingArgs();if (otherArgs.length != 2) {System.err.println("SortByValue: <in> <out>");System.exit(2);}Job job = new Job(conf, "SortByValue");job.setJarByClass(SVJob.class);job.setMapperClass(SVMapper.class);job.setReducerClass(SVReducer.class);job.setMapOutputKeyClass(IntWritable.class);job.setMapOutputValueClass(Text.class);job.setOutputKeyClass(Text.class);job.setOutputValueClass(IntWritable.class);job.setSortComparatorClass(IntWritableDecreasingComparator.class);FileInputFormat.addInputPath(job, new Path(otherArgs[0]));FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));System.exit(job.waitForCompletion(true) ? 0 : 1);}}public class SVMapper extends Mapper<Object, Text, IntWritable, Text> {protected void map(Object key, Text value, Context context)throws IOException, InterruptedException {String line = value.toString();String[] keyValueStrings = line.split("\t");if(keyValueStrings.length != 2){//新⼿,不知道怎么记录⽇志,也不清楚怎么退出各位⼤神如果知道请通知我,谢谢System.err.println("string format error");return;}int outkey = Integer.parseInt(keyValueStrings[1]);String outvalue = keyValueStrings[0];context.write(new IntWritable(outkey), new Text(outvalue));}}public class SVReducer extends Reducer<IntWritable, Text, Text, IntWritable> {protected void reduce(IntWritable key, Iterable<Text> values,Context context)throws IOException, InterruptedException {for(Text value : values){context.write(value, key);}}}因为我们要实现倒序排序要有⾃定义的排序⽅法public class IntWritableDecreasingComparator extends Comparator { @SuppressWarnings("rawtypes")public int compare( WritableComparable a,WritableComparable b){ return pare(a, b);}public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { return pare(b1, s1, l1, b2, s2, l2);}}这样就完成了,可以⾃定义排序了。

hadoop倒排索引实验报告

hadoop倒排索引实验报告

大数据技术概论实验报告作业三姓名:郭利强专业:工程管理专业学号: 2015E8009064028目录1.实验要求 (3)2.环境说明 (4)2.1系统硬件 (4)2.2系统软件 (4)2.3集群配置 (4)3.实验设计 (4)3.1第一部分设计 (4)3.2第二部分设计 (6)4.程序代码 (11)4.1第一部分代码 (11)4.2第二部分代码 (17)5.实验输入和结果 (21)实验输入输出结果见压缩包中对应目录 (21)1.实验要求第一部分:采用辅助排序的设计方法,对于输入的N个IP网络流量文件,计算得到文件中的各个源IP地址连接的不同目的IP地址个数,即对各个源IP地址连接的目的IP地址去重并计数举例如下:第二部分:输入N个文件,生成带详细信息的倒排索引举例如下,有4个输入文件:– d1.txt: cat dog cat fox– d2.txt: cat bear cat cat fox– d3.txt: fox wolf dog– d4.txt: wolf hen rabbit cat sheep要求建立如下格式的倒排索引:– cat —>3: 4: {(d1.txt,2,4),(d2.txt,3,5),(d4.txt,1,5)}–单词—>出现该单词的文件个数:总文件个数: {(出现该单词的文件名,单词在该文件中的出现次数,该文件的总单词数),……}2.环境说明2.1系统硬件处理器:Intel Core i3-2350M CPU@2.3GHz×4 内存:2GB磁盘:60GB2.2系统软件操作系统:Ubuntu 14.04 LTS操作系统类型:32位Java版本:1.7.0_85Eclipse版本:3.8Hadoop插件:hadoop-eclipse-plugin-2.6.0.jar Hadoop:2.6.12.3集群配置集群配置为伪分布模式,节点数量一个3.实验设计3.1第一部分设计利用两个Map/Reduce过程,在第一个MR中,读取记录并去除重复记录,第二个MR按照辅助排序设计方法,根据源地址进行分组,统计目的地址数量。

Mapreduce实例——倒排索引

Mapreduce实例——倒排索引

Mapreduce实例——倒排索引实验⽬的1.了解倒排索引的使⽤场景2.准确理解倒排索引的设计原理3.熟练掌握MapReduce倒排索引程序代码编写实验原理"倒排索引"是⽂档检索系统中最常⽤的数据结构,被⼴泛地应⽤于全⽂搜索引擎。

它主要是⽤来存储某个单词(或词组)在⼀个⽂档或⼀组⽂档中的存储位置的映射,即提供了⼀种根据内容来查找⽂档的⽅式。

由于不是根据⽂档来确定⽂档所包含的内容,⽽是进⾏相反的操作,因⽽称为倒排索引(Inverted Index)。

实现"倒排索引"主要关注的信息为:单词、⽂档URL及词频。

下⾯以本实验goods3、goods_visit3、order_items3三张表的数据为例,根据MapReduce的处理过程给出倒排索引的设计思路:(1)Map过程⾸先使⽤默认的TextInputFormat类对输⼊⽂件进⾏处理,得到⽂本中每⾏的偏移量及其内容。

显然,Map过程⾸先必须分析输⼊的<key,value>对,得到倒排索引中需要的三个信息:单词、⽂档URL和词频,接着我们对读⼊的数据利⽤Map操作进⾏预处理,如下图所⽰:这⾥存在两个问题:第⼀,<key,value>对只能有两个值,在不使⽤Hadoop⾃定义数据类型的情况下,需要根据情况将其中两个值合并成⼀个值,作为key或value值。

第⼆,通过⼀个Reduce过程⽆法同时完成词频统计和⽣成⽂档列表,所以必须增加⼀个Combine过程完成词频统计。

这⾥将商品ID和URL组成key值(如"1024600:goods3"),将词频(商品ID出现次数)作为value,这样做的好处是可以利⽤MapReduce 框架⾃带的Map端排序,将同⼀⽂档的相同单词的词频组成列表,传递给Combine过程,实现类似于WordCount的功能。

(2)Combine过程经过map⽅法处理后,Combine过程将key值相同的value值累加,得到⼀个单词在⽂档中的词频,如下图所⽰。

文华学院hadoop系统应用实训报告

文华学院hadoop系统应用实训报告

文华学院hadoop系统应用实训报告1.前言通过基于MapReduce云计算平台的海量数据处理实验,我们了解了Hadoop的基本架构,已经如何编写MapReduce程序,本实验中我主要使用到的两个程序分别是WordCount(词频统计)和InvertedIndex(反向索引)。

在将这两个程序之前,我会介绍我对Hadoop的理解。

2.Hadoop简介及特性2.1.Hadoop分布式文件系统(HDFS)Hadoop分布式文件系统(HDFS)被设计成适合运行在通用硬件(commodity hardware)上的分布式文件系统。

它和现有的分布式文件系统有很多共同点。

但同时,它和其他的分布式文件系统的区别也是很明显的。

HDFS是一个高度容错性的系统,适合部署在廉价的机器上。

HDFS能提供高吞吐量的数据访问,非常适合大规模数据集上的应用。

HDFS放宽了一部分POSIX约束,来实现流式读取文件系统数据的目的。

2.2.简单的一致性模型HDFS应用需要一个“一次写入多次读取”的文件访问模型。

一个文件经过创建、写入和关闭之后就不需要改变。

这一假设简化了数据一致性问题,并且使高吞吐量的数据访问成为可能。

Map/Reduce 应用或者网络爬虫应用都非常适合这个模型。

目前还有计划在将来扩充这个模型,使之支持文件的附加写操作。

2.3.“移动计算比移动数据更划算”一个应用请求的计算,离它操作的数据越近就越高效,在数据达到海量级别的时候更是如此。

因为这样就能降低网络阻塞的影响,提高系统数据的吞吐量。

将计算移动到数据附近,比之将数据移动到应用所在显然更好。

HDFS为应用提供了将它们自己移动到数据附近的接口。

2.4.数据复制HDFS被设计成能够在一个大集群中跨机器可靠地存储超大文件。

它将每个文件存储成一系列的数据块,除了最后一个,所有的数据块都是同样大小的。

为了容错,文件的所有数据块都会有副本。

每个文件的数据块大小和副本系数都是可配置的。

实操18-MapReduce操作实例-倒排索引

实操18-MapReduce操作实例-倒排索引
public class InvertedIndexMapper extends Mapper<LongWritable, Text, Text, Text>{
private static Text keyinfo = new Text(); private static final Text valueinfo = new Text("1"); @Override /**
//获取单词 key.set(key.toString().substring(0, indexOf));
//写入上下文中 context.write(key, info);
}
} 3. 创建 Reducer 类 package com.itcast.mr.InvertedIndex;
import java.io.IOException;
//设置 job 对象 job.setJarByClass(InvertedIndexDriver.class); job.setMapperClass(InvertedIndexMapper.class);
job.setCombinerClass(InvertedIndexCombiner.class); job.setReducerClass(InvertedIndexReducer.class);
public class InvertedIndexDriver {
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
//获取 job 对象 Configuration conf = new Configuration(); Job job = Job.getInstance(conf);
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

大数据技术概论实验报告作业三姓名:郭利强专业:工程管理专业学号: 2015E8009064028目录1.实验要求 (3)2.环境说明 (4)2.1系统硬件 (4)2.2系统软件 (4)2.3集群配置 (4)3.实验设计 (4)3.1第一部分设计 (4)3.2第二部分设计 (6)4.程序代码 (11)4.1第一部分代码 (11)4.2第二部分代码 (17)5.实验输入和结果 (21)实验输入输出结果见压缩包中对应目录 (21)1.实验要求第一部分:采用辅助排序的设计方法,对于输入的N个IP网络流量文件,计算得到文件中的各个源IP地址连接的不同目的IP地址个数,即对各个源IP地址连接的目的IP地址去重并计数举例如下:第二部分:输入N个文件,生成带详细信息的倒排索引举例如下,有4个输入文件:– d1.txt: cat dog cat fox– d2.txt: cat bear cat cat fox– d3.txt: fox wolf dog– d4.txt: wolf hen rabbit cat sheep要求建立如下格式的倒排索引:– cat —>3: 4: {(d1.txt,2,4),(d2.txt,3,5),(d4.txt,1,5)}–单词—>出现该单词的文件个数:总文件个数: {(出现该单词的文件名,单词在该文件中的出现次数,该文件的总单词数),……}2.环境说明2.1系统硬件处理器:Intel Core i3-2350M CPU@2.3GHz×4 内存:2GB磁盘:60GB2.2系统软件操作系统:Ubuntu 14.04 LTS操作系统类型:32位Java版本:1.7.0_85Eclipse版本:3.8Hadoop插件:hadoop-eclipse-plugin-2.6.0.jar Hadoop:2.6.12.3集群配置集群配置为伪分布模式,节点数量一个3.实验设计3.1第一部分设计利用两个Map/Reduce过程,在第一个MR中,读取记录并去除重复记录,第二个MR按照辅助排序设计方法,根据源地址进行分组,统计目的地址数量。

第一个MR设计:自定义StringPair{源地址,目的地址}类型,实现WritableComparable,在map过程读取文件,输出<StringPair,NullWritable>,reduce过程去除重复记录输出<StringPair.toString, NullWritable >。

在第二个MR设计:1.在Map过程读取第一个MR的输出,对value值进行拆分,并以拆分得到的源地址和目的地址初始化StringPair对象作为输出键,输出值为1。

public void map(Object key, Text value, Context context)throws IOException, InterruptedException {String[] records = value.toString().split("\t");String sourceip = records[0];String desip=records[1];context.write(new StringPair(sourceip,desip),one);}2.定义GroupComparator类,继承WritableComparator类,并重载compare方法,对Map过程输出按照StringPair.first排序,完成按照源地址分组。

public static class GroupComparator extends WritableComparator {protected GroupComparator() {super(StringPair.class, true);}@Overridepublic int compare(WritableComparable w1,WritableComparable w2) {StringPair ip1=(StringPair)w1;StringPair ip2=(StringPair)w2;return ip1.getFirst().compareTo(ip2.getFirst());}}3.在Reduce过程统计分组中的所有值,得到源地址连接不同目的地址数量。

public void reduce( StringPair key, Iterable<IntWritable> values, Context context)throws IOException, InterruptedException {int sum = 0;for (IntWritable val:values) {sum += val.get();}statistic.set(sum);context.write(key.getFirst(), statistic);}}3.2第二部分设计利用两个Map/Reduce过程,第一个MR统计各个文件中的所有单词的出现次数,以及各个文件单词总数,第二个MR根据统计结果处理加工得到单词倒排索引。

第一个MR设计:1.在Map过程中,重写map类,利用StringTokenizer类,将map 方法中的value值中存储的文本,拆分成一个个的单词,并获取文件名,以两种格式进行输出< filename+word,1>或者<filename,1>。

public void map(Object key, Text value, Context context)throws IOException, InterruptedException {//获取文件名FileSplit fileSplit= (FileSplit)context.getInputSplit();String fileName = fileSplit.getPath().getName();//获取单词在单个文件中出现次数,及文件单词总数StringTokenizer itr= new StringTokenizer(value.toString());for(; itr.hasMoreTokens(); ) {String word =removeNonLetters( itr.nextToken().toLowerCase());String fileWord = fileName+"\001"+word;if(!word.equals("")){context.write(new Text(fileWord), new IntWritable(1));context.write(new Text(fileName), new IntWritable(1));}}}2.在Reduce过程中,统计得到每个文件中每个单词的出现次数,以及每个文件的单词总数,输出<key,count>。

public void reduce(Text key, Iterable<IntWritable> values, Context context)throws IOException, InterruptedException {int sum = 0;for (IntWritable val : values) {sum += val.get();}context.write(key,new IntWritable(sum));}}第二个MR设计:1.Map过程读取第一个MR的输出,对value值进行拆分,重新组合后输出键为固定Text类型值index,值为filename+word+count或者filename+count。

public void map(Object key, Text value, Context context)throws IOException, InterruptedException {String valStr = value.toString();String[] records = valStr.split("\t");context.write(new Text("index"),new Text(records[0]+"\001"+records[1]));}}2.Reduce过程中定义四个HashMap,Map<String,Integer> wordinfilescount,key为单词+文件名,value为单词在该文件中出现的次数;Map<String,Integer> filescount ,key为文件名,value为文件的单词总数;Map<String,Integer> wordinfiles,key为单词,value为单词在多少个文件中出现;Map<String,String> indexes,key为单词,value为倒排索引。

读取values值,根据设定分隔符拆分,判断拆分后长度如果为2,则该值为文件名+文件单词总数,将拆分后的文件名及文件单词总数,组成键值对放入Map<String,Integer> filescount;拆分后长度如果为3,则该值为文件名+单词+单词在该文件中出现次数,将拆分后的文件名+单词及单词在该文件中出现次数组成键值对放入Map<String,Integer> wordinfilescount,同时统计单词在多少个文件中出现,并组成键值对放入Map<String,Integer> wordinfiles。

遍历Map<String,Integer> wordinfilescount,将单词作为键,“单词->出现该单词的文件个数:总文件个数:{(出现该单词的文件名,单词在该文件中的出现次数,该文件的总单词数)”作为值,放入Map<String,String> indexes中。

遍历Map<String,String> indexes获取倒排索引并输出全部索引。

public void reduce( Text key, Iterable<Text> values, Context context)throws IOException, InterruptedException {//拆分输入,获取单词出现在几个文件中以及在该文件中出现次数,各个文件的单词总数,总文件数for (Text val : values) {String valStr = val.toString();String[] records = valStr.split("\001");switch(records.length){case 2:filescount.put(records[0], Integer.parseInt(records[1]));break;case 3:{wordinfilescount.put(valStr, Integer.parseInt(records[2]));if(!wordinfiles.containsKey(records[1])){wordinfiles.put(records[1], 1);}else{wordinfiles.put(records[1], wordinfiles.get(records[1])+1);}};break;}}//处理获取倒排索引for (Entry<String, Integer> entry : wordinfilescount.entrySet()) {String valStr = entry.getKey();String[] records = valStr.split("\001");String word = records[1];if(!indexes.containsKey(word)){StringBuilder sb = new StringBuilder();sb.append(word).append("->").append(wordinfiles.get(word)).append(":").append(filescount.size()).append(":").append("{(").append( records[0]).append(",").append(entry.getValue()).append(",").append(filescount.get( records[0])).append(")");indexes.put(word,sb.toString() );}else{StringBuilder sb = new StringBuilder();sb.append(",(").append( records[0]).append(",").append(entry.getValue()).append(",").append(filescount.get( records[0])).append(")");indexes.put(word,indexes.get(word)+sb.toString() ); }}for (Entry<String, String> entry : indexes.entrySet()) {context.write(new Text(entry.getValue()+"}"), NullWritable.get());}}}4.程序代码4.1第一部分代码1.IpStatistics.java/*** Licensed to the Apache Software Foundation (ASF) under one* or more contributor license agreements. See the NOTICE file* distributed with this work for additional information* regarding copyright ownership. The ASF licenses this file* to you under the Apache License, Version 2.0 (the* "License"); you may not use this file except in compliance* with the License. You may obtain a copy of the License at** /licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/import java.io.IOException;import java.util.ArrayList;import java.util.Collections;import parator;import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.Map.Entry;import java.util.StringTokenizer;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.NullWritable;import org.apache.hadoop.io.Text;import org.apache.hadoop.io.WritableComparable;import org.apache.hadoop.io.WritableComparator;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;import org.apache.hadoop.util.GenericOptionsParser;import org.apache.hadoop.fs.Path;public class IpStatistics {//第一个Map/Reduce的map类,用于去重public static class RemoveMapper extendsMapper<Object, Text, StringPair, NullWritable> {public void map(Object key, Text value, Context context)throws IOException, InterruptedException {StringTokenizer itr = new StringTokenizer(value.toString());while (itr.hasMoreTokens()) {String nextToken =itr.nextToken();String[] records = nextToken.split(",");String sourceip = records[0].replace("<", "");String destinationip = records[1].replace(">", "");context.write(newStringPair(sourceip,destinationip),NullWritable.get() );}}}//第二个Map/Reduce过程map类,用于统计public static class StatisticsMapper extendsMapper<Object, Text, StringPair, IntWritable> {IntWritable one=new IntWritable(1);public void map(Object key, Text value, Context context)throws IOException, InterruptedException {String[] records = value.toString().split("\t");String sourceip = records[0];String desip=records[1];context.write(new StringPair(sourceip,desip),one);}}//按照源地址分组public static class GroupComparator extends WritableComparator {protected GroupComparator() {super(StringPair.class, true);}@Overridepublic int compare(WritableComparable w1,WritableComparable w2) {StringPair ip1=(StringPair)w1;StringPair ip2=(StringPair)w2;return ip1.getFirst().compareTo(ip2.getFirst());}}//第一个Map/Reduce过程reduce过程,去重public static class RemoveReducer extendsReducer<StringPair, IntWritable, Text, NullWritable> {public void reduce( StringPair key, Iterable<IntWritable> values, Context context)throws IOException, InterruptedException {context.write(new Text(key.toString()), NullWritable.get());}}//第二个Map/Reduce过程reduce过程,统计public static class StatisticsReducer extendsReducer<StringPair, IntWritable, Text, IntWritable> {private IntWritable statistic = new IntWritable();public void reduce( StringPair key, Iterable<IntWritable> values, Context context)throws IOException, InterruptedException {int sum = 0;for (IntWritable val:values) {sum += val.get();}statistic.set(sum);context.write(key.getFirst(), statistic);}}//去重任务public static void RemoveTask(String[] args) throws Exception{Configuration conf = new Configuration();String master="127.0.0.1";conf.set("fs.defaultFS", "hdfs://127.0.0.1:9000");conf.set("er", "hadoop");conf.set("","yarn");conf.set("yarn.resourcemanager.address", master+":8032");conf.set("yarn.resourcemanager.scheduler.address", master+":8030");conf.set("mapred.jar","ipstatistics.jar");String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();if (otherArgs.length < 3) {System.err.println("Usage: ipstatistics <in> [<in>...] <out>");System.exit(2);}Job job = new Job(conf, "ipstatisticsRemoving");job.setMapperClass(RemoveMapper.class);job.setReducerClass(RemoveReducer.class);job.setOutputKeyClass(StringPair.class);job.setOutputValueClass(NullWritable.class);FileInputFormat.addInputPath(job, new Path(otherArgs[0]));FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));job.waitForCompletion(true) ;}//统计任务public static void StatisticsTask(String[] args) throws Exception{ Configuration conf = new Configuration();String master="127.0.0.1";conf.set("fs.defaultFS", "hdfs://127.0.0.1:9000");conf.set("er", "hadoop");conf.set("","yarn");conf.set("yarn.resourcemanager.address", master+":8032");conf.set("yarn.resourcemanager.scheduler.address", master+":8030");conf.set("mapred.jar","ipstatistics.jar");String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();if (otherArgs.length < 3) {System.err.println("Usage: ipstatistics <in> [<in>...] <out>");System.exit(2);}Job job = new Job(conf, "ipstatisticsStatistics");job.setMapperClass(StatisticsMapper.class);job.setGroupingComparatorClass(GroupComparator.class);job.setReducerClass(StatisticsReducer.class);job.setOutputKeyClass(StringPair.class);job.setOutputValueClass(IntWritable.class);FileInputFormat.addInputPath(job, new Path(otherArgs[1]));FileOutputFormat.setOutputPath(job, new Path(otherArgs[2]));System.exit(job.waitForCompletion(true) ? 0 : 1);}public static void main(String[] args) throws Exception {RemoveTask(args);StatisticsTask(args);}}2.StringPair.javaimport org.apache.hadoop.io.Text;import org.apache.hadoop.io.WritableComparable;import java.io.DataInput;import java.io.DataOutput;import java.io.IOException;public class StringPair implements WritableComparable<StringPair> {private Text first;private Text second;public StringPair() {this.first = new Text();this.second = new Text();}public StringPair(String first, String second) {set(new Text(first), new Text(second));}public StringPair(Text first, Text second) {set(first, second);}public void set(Text first, Text second) {this.first = first;this.second = second;}public Text getFirst() {return first;}public Text getSecond() {return second;}public void write(DataOutput out) throws IOException {first.write(out);second.write(out);}public void readFields(DataInput in) throws IOException {first.readFields(in);second.readFields(in);}@Overridepublic int hashCode() {return first.hashCode() * 163 + second.hashCode();}@Overridepublic boolean equals(Object obj) {if (obj instanceof StringPair) {StringPair ip = (StringPair) obj;return first.toString().equals(ip.first.toString())&& second.toString().equals(ip.second.toString());}4.2第二部分代码import java.io.IOException;import java.util.HashSet;import java.util.Map;import java.util.Set;import java.util.StringTokenizer;import java.util.HashMap;import java.util.Map.Entry;import org.apache.hadoop.conf.Configuration;import org.apache.hadoop.fs.Path;import org.apache.hadoop.io.IntWritable;import org.apache.hadoop.io.NullWritable;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.Mapper.Context;import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;import org.apache.hadoop.mapreduce.lib.input.FileSplit;import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;import org.apache.hadoop.util.GenericOptionsParser;public class InverseV3 {/** 第一个mr的map类,获取每个单词在单个文件中出现次数,输入为每个文件行偏移量,输出为<word+filename,1>* 或<filename,1>*/public static class statisticsMap extendsMapper<Object, Text, Text, IntWritable> {private Text mapKey = new Text("key");@Overridepublic void map(Object key, Text value, Context context)throws IOException, InterruptedException {//获取文件名FileSplit fileSplit= (FileSplit)context.getInputSplit();String fileName = fileSplit.getPath().getName();//获取单词在单个文件中出现次数,及文件单词总数StringTokenizer itr= new StringTokenizer(value.toString());for(; itr.hasMoreTokens(); ) {String word =removeNonLetters( itr.nextToken().toLowerCase());String fileWord = fileName+"\001"+word;if(!word.equals("")){context.write(new Text(fileWord), new IntWritable(1));context.write(new Text(fileName), new IntWritable(1));}}}//去掉字符串非字母字符public static String removeNonLetters(String original){StringBuffer aBuffer=new StringBuffer(original.length());char aCharacter;for(int i=0;i<original.length();i++){aCharacter=original.charAt(i);if(Character.isLetter(aCharacter)){aBuffer.append(aCharacter);}}return new String(aBuffer);}}//第一个mr的reduce类,统计汇总出现单词的文件个数,及每个文件中单词出现个数及每个文件单词个数,public static class statisticsReduce extendsReducer<Text, IntWritable, Text, IntWritable> {@Overridepublic void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {int sum = 0;for (IntWritable val : values) {sum += val.get();}context.write(key,new IntWritable(sum));}}public static class InverseMapper extendsMapper<Object, Text, Text, Text> {public void map(Object key, Text value, Context context)throws IOException, InterruptedException {String valStr = value.toString();String[] records = valStr.split("\t");context.write(new Text("index"),new Text(records[0]+"\001"+records[1]));}}public static class InverseReducer extendsReducer<Text, Text, Text, NullWritable> {private Map<String,Integer> wordinfilescount = newHashMap<String,Integer>();//key为单词+文件名,value为单词在该文件中出现的次数private Map<String,Integer> filescount = new HashMap<String,Integer>();//key为文件名,value为文件的单词总数private Map<String,Integer> wordinfiles = new HashMap<String,Integer>();//key为单词,value为单词在多少的文件中出现private Map<String,String> indexes = new HashMap<String,String>();//key为单词,value为倒排索引public void reduce( Text key, Iterable<Text> values, Context context)throws IOException, InterruptedException {//拆分输入,获取单词出现在几个文件中以及在该文件中出现次数,各个文件的单词总数,总文件数for (Text val : values) {String valStr = val.toString();String[] records = valStr.split("\001");switch(records.length){case 2:filescount.put(records[0], Integer.parseInt(records[1]));break;case 3:{wordinfilescount.put(valStr, Integer.parseInt(records[2]));if(!wordinfiles.containsKey(records[1])){wordinfiles.put(records[1], 1);}else{wordinfiles.put(records[1], wordinfiles.get(records[1])+1);}};break;}}//处理获取倒排索引for (Entry<String, Integer> entry : wordinfilescount.entrySet()) {String valStr = entry.getKey();String[] records = valStr.split("\001");String word = records[1];if(!indexes.containsKey(word)){StringBuilder sb = new StringBuilder();sb.append(word).append("->").append(wordinfiles.get(word)).append(":").append(filescount.size()).append(":").append("{(").append( records[0]).append(",").append(entry.getValue()).append(",").append(filescount.get( records[0])).append(")");indexes.put(word,sb.toString() );}else{StringBuilder sb = new StringBuilder();sb.append(",(").append( records[0]).append(",").append(entry.getValue()).append(",").append(filescount.get( records[0])).append(")");indexes.put(word,indexes.get(word)+sb.toString() );}}for (Entry<String, String> entry : indexes.entrySet()) {context.write(new Text(entry.getValue()+"}"), NullWritable.get());}}}//统计单词在文件中出现次数及单个文件单词总数public static void StatisticsTask(String[] args) throws Exception{ Configuration conf = new Configuration();String master="127.0.0.1";conf.set("fs.defaultFS", "hdfs://127.0.0.1:9000");conf.set("er", "hadoop");conf.set("","yarn");conf.set("yarn.resourcemanager.address", master+":8032");conf.set("yarn.resourcemanager.scheduler.address", master+":8030");conf.set("mapred.jar","invertdindex.jar");String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();if (otherArgs.length < 3) {System.err.println("Usage: ipstatistics <in> [<in>...] <out>");System.exit(2);}Job job = new Job(conf, "invertd index1");job.setMapperClass(statisticsMap.class);job.setReducerClass(statisticsReduce.class);job.setOutputKeyClass(Text.class);job.setOutputValueClass(IntWritable.class);FileInputFormat.addInputPath(job, new Path(otherArgs[0]));FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));job.waitForCompletion(true) ;}//根据统计结果输出倒排索引public static void InverseTask(String[] args) throws Exception{ Configuration conf = new Configuration();String master="127.0.0.1";conf.set("fs.defaultFS", "hdfs://127.0.0.1:9000");conf.set("er", "hadoop");conf.set("","yarn");conf.set("yarn.resourcemanager.address", master+":8032");conf.set("yarn.resourcemanager.scheduler.address", master+":8030");conf.set("mapred.jar","invertdindex.jar");String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();if (otherArgs.length < 3) {System.err.println("Usage: ipstatistics <in> [<in>...] <out>");System.exit(2);}Job job = new Job(conf, "invertd index2");job.setMapperClass( InverseMapper.class);job.setReducerClass( InverseReducer.class);job.setOutputKeyClass(Text.class);job.setOutputValueClass(Text.class);FileInputFormat.addInputPath(job, new Path(otherArgs[1]));FileOutputFormat.setOutputPath(job, new Path(otherArgs[2]));System.exit(job.waitForCompletion(true) ? 0 : 1);}public static void main(String[] args) throws Exception {StatisticsTask(args);InverseTask(args);}}5.实验输入和结果实验输入输出结果见压缩包中对应目录。

相关文档
最新文档