设为首页 收藏本站
查看: 748|回复: 0

[经验分享] Hadoop下进行反向索引(Inverted Index)操作

[复制链接]

尚未签到

发表于 2015-7-13 09:50:44 | 显示全部楼层 |阅读模式
0.参考资料:
  代码参考1:http://www.pudn.com/downloads212/sourcecode/unix_linux/detail999273.html
  理论参考2:http://zhangyu8374.javaeye.com/blog/86307,http://nything.javaeye.com/blog/411787

1.分析
  假如有file0,file1,file2三个文件,这些文件中都保存了一些文本内容,比如在file0中只有一个句子,内容为"we are happy"。一般的索引都是记录在这个文件中没有一个单词的索引号。比如file0的索引可以是(we,0),(are,1),(happy,2)。这样的键值对中key是单词,value是这个单词在这个文件中的位置。但是,反向索引刚好相反,对应于多个文件,我们要求出某一个单词在所有这些文件中出现的位置。我们可以按如下操作进行实验:
  在本地创建文件夹IndexTest并在里面创建3个文件,每个文件中的内容如下。
  * T0 = "it is what it is"
    * T1 = "what is it"
    * T2 = "it is a banana"
  其中T0,T1,T2分别是文件名,后面为文件内容。将IndexTest文件夹上传到DFS中。然后运行反向索引程序。反向索引程序见代码示例。
  最后输出结果为:



a     (T2, 3)
banana     (T2, 4)
is     (T2, 2) (T0, 2) (T0, 5) (T1, 2)
it     (T1, 3) (T2, 1) (T0, 1) (T0, 4)
what     (T0, 3) (T1, 1)
2.代码示例

InvertedIndex.java


DSC0000.gif DSC0001.gif View Code


/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pa4;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
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;
import org.apache.hadoop.util.GenericOptionsParser;
/**
*
* @author Ming
*/
public class InvertedIndex {
public static class TokenizerMapper
extends Mapper {
@Override
public void map(Text key, ValuePair value, Context context) throws IOException, InterruptedException {
// TokenInputFormat has generate (word, (fileID, wordPosition))
// so mapper just spill it to reducer
        key.set(key.toString().toLowerCase());
context.write(key, value);
}
}
public static class IndexReducer
extends Reducer {
private Text postings = new Text();
@Override
public void reduce(Text key, Iterable values,
Context context) throws IOException, InterruptedException {
String list = "";
for (ValuePair val : values) {
list += " " + val.toString();
}
postings.set(list);
context.write(key, postings);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("Usage: InvertedIndex  ");
System.exit(2);
}
// remove the old output dir
FileSystem.get(conf).delete(new Path(otherArgs[1]), true);
Job job = new Job(conf, "Inverted Indexer");
job.setJarByClass(InvertedIndex.class);
job.setInputFormatClass(TokenInputFormat.class);
job.setMapperClass(InvertedIndex.TokenizerMapper.class);
//job.setCombinerClass(InvertedIndex.IndexReducer.class);
job.setReducerClass(InvertedIndex.IndexReducer.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(ValuePair.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
TokenInputFormat.java


View Code


package pa4;
import java.io.IOException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.TaskAttemptID;
import org.apache.hadoop.util.LineReader;
import java.util.StringTokenizer;
public class TokenInputFormat extends FileInputFormat {
/**
* Don't allow the files to be split!
*/
@Override
protected boolean isSplitable(JobContext ctx, Path filename) {
// ensure the input files are not splittable!
return false;
}
/**
* Just return the record reader
* key is the docno
*/
public RecordReader createRecordReader(InputSplit split,
TaskAttemptContext ctx)
throws IOException, InterruptedException {
return new TokenRecordReader();
}
public static class TokenRecordReader extends RecordReader {
private long start;
private long pos;
private long end;
private LineReader in;
private int maxLineLength;
private Text line;
private Text key = null;
private ValuePair value = null;
private StringTokenizer tokens = null;
private int tokenPos = 0;
private String fileID = "0";    // input file id that appears in inverted index
public void initialize(InputSplit genericSplit,
TaskAttemptContext context) throws IOException {
FileSplit split = (FileSplit) genericSplit;
Configuration job = context.getConfiguration();
this.maxLineLength = job.getInt("mapred.linerecordreader.maxlength",
Integer.MAX_VALUE);
start = split.getStart();
end = start + split.getLength();
final Path file = split.getPath();
// Assume file name is an integer of file ID
fileID = file.getName();
FileSystem fs = file.getFileSystem(job);
FSDataInputStream fileIn = fs.open(split.getPath());
in = new LineReader(fileIn, job);
this.pos = start;
line = new Text();
key = new Text();
value = new ValuePair();
}
public boolean nextKeyValue() throws IOException {
boolean splitEnds = false;
while (tokens == null || !tokens.hasMoreTokens()) {
int lineSize = in.readLine(line, maxLineLength,
Math.max((int) Math.min(Integer.MAX_VALUE, end - pos),
maxLineLength));
if (lineSize == 0) {
splitEnds = true;
break;
}
pos += lineSize;
tokens = new StringTokenizer(line.toString(), " /t/n/r/f,.;-?///!'/":=*{}()$[]");
        }
if (splitEnds) {
key = null;
value = null;
line = null;
tokens = null;
return false;
} else
return true;
}
@Override
public Text getCurrentKey() {
key.set(tokens.nextToken());
tokenPos ++;
return key;
}
@Override
public ValuePair getCurrentValue() {
value.set(fileID, tokenPos);
return value;
}
/**
* Get the progress within the split
*/
public float getProgress() {
if (start == end) {
return 0.0f;
} else {
return Math.min(1.0f, (pos - start) / (float) (end - start));
}
}
public synchronized void close() throws IOException {
if (in != null) {
in.close();
}
}
}
public static void main(String[] args)
throws IOException {
String fn = args[0];
Configuration conf = new Configuration();
FileSplit split = new FileSplit(new Path(fn), 0, 10000000, null);
TokenRecordReader irr = new TokenRecordReader();
TaskAttemptContext ctx = new TaskAttemptContext(conf,
new TaskAttemptID("hello", 12, true, 12, 12));
irr.initialize(split, ctx);
while (irr.nextKeyValue()) {
System.out.println(irr.getCurrentKey() + ": " + irr.getCurrentValue());
}
}
}
ValuePair.java


View Code


package pa4;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.*;
import org.apache.hadoop.io.*;
/**
*
* @author Ming
*/
public class ValuePair implements WritableComparable {
private Text one;
private IntWritable two;
public void set(Text first, IntWritable second) {
one = first;
two = second;
}
public void set(String first, int second) {
one.set(first);
two.set(second);
}
public ValuePair() {
set(new Text(), new IntWritable());
}
public ValuePair(Text first, IntWritable second) {
set(first, second);
}
public ValuePair(String first, int second) {
set(first, second);
}
public Text getFirst() {
return one;
}
public IntWritable getSecond() {
return two;
}
@Override
public void write(DataOutput out) throws IOException {
one.write(out);
two.write(out);
}
@Override
public void readFields(DataInput in) throws IOException {
one.readFields(in);
two.readFields(in);
}
@Override
public int hashCode() {
return one.hashCode();
}
@Override
public boolean equals(Object o) {
if (o instanceof ValuePair) {
ValuePair tp = (ValuePair)o;
return one.equals(tp.one);
}
return false;
}
@Override
public String toString() {
return "(" + one + ", " + two + ")";
}
@Override
public int compareTo(ValuePair tp) {
int cmp = one.compareTo(tp.one);
if (cmp != 0) {
return cmp;
}
return two.compareTo(tp.two);
}
public static class Comparator extends WritableComparator {
private static final Text.Comparator TEXT_COMPARATOR = new Text.Comparator();
private static final IntWritable.Comparator INT_COMPARATOR = new IntWritable.Comparator();
public Comparator() {
super(ValuePair.class);
}
@Override
public int compare(byte[] b1, int s1, int l1,
byte[] b2, int s2, int l2) {
try {
int oneL1 = WritableUtils.decodeVIntSize(b1[s1]) + readVInt(b1, s1);
int oneL2 = WritableUtils.decodeVIntSize(b2[s2]) + readVInt(b2, s2);
int cmp = TEXT_COMPARATOR.compare(b1, s1, oneL1, b2, s2, oneL2);
if (cmp != 0) {
return cmp;
}
return INT_COMPARATOR.compare(b1, s1+oneL1, l1-oneL1,
b2, s2+oneL2, l2-oneL2);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
}
@Override
public int compare(WritableComparable a, WritableComparable b) {
if (a instanceof ValuePair && b instanceof ValuePair) {
return ((ValuePair) a).compareTo((ValuePair) b);
}
return super.compare(a, b);
}
}
static {
WritableComparator.define(ValuePair.class, new Comparator());
}
}
ps:2012-5-20
  这里键值对valuepair的运用让我想到了前几天写的Hashmap实现原理。在hashmap的实现过程中,也运用了键值对类Entry。 两者之间有共通之处,有空可以再改进Hashmap实现原理。
  
  
  
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-86155-1-1.html 上篇帖子: Hadoop学习笔记(二):MapReduce的特性-计数器、排序 下篇帖子: Hadoop Capacity Scheduler配置使用记录
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表