现在的位置: 首页 > 云计算 > 正文

mapreduce文档倒排索引例程

2013年07月24日 云计算 ⁄ 共 2051字 ⁄ 字号 评论关闭

import java.io.IOException;
import java.util.StringTokenizer;
import java.util.Collections;
import java.util.Iterator;

import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

public class InvertedIndex {

public static class InvertedIndexMapper extends Mapper<Object,Text,Text,Text>
{
public void map(Object key,Text value,Context context)
throws IOException,InterruptedException
{
FileSplit fileSplit = (FileSplit)context.getInputSplit();
String fileName = fileSplit.getPath().getName();
Text word = new Text();
Text fileName_lineOffset = new Text(fileName+"#"+key.toString());
StringTokenizer itr = new StringTokenizer(value.toString());
for(;itr.hasMoreTokens();)
{
word.set(itr.nextToken());
context.write(word, fileName_lineOffset);
}
}
}

public static class InvertedIndexReducer extends Reducer<Text,Text,Text,Text>
{
public void reduce(Text key , Iterable<Text>values,Context context)
throws IOException,InterruptedException
{
Iterator<Text> it = values.iterator();
StringBuilder all = new StringBuilder();
if(it.hasNext()) all.append(it.next().toString());
for(;it.hasNext();)
{
all.append(";");
all.append(it.next().toString());
}

context.write(key, new Text(all.toString()));
}
}

public static void main(String[] args)
{
try
{
Configuration conf = new Configuration();
Job job = new Job(conf,"invertindex");
job.setJarByClass(InvertedIndex.class);
job.setInputFormatClass(TextInputFormat.class);
job.setMapperClass(InvertedIndexMapper.class);
job.setReducerClass(InvertedIndexReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job,new Path(args[1]));
System.exit(job.waitForCompletion(true)?0:1);
}
catch(Exception e)
{
e.printStackTrace();
}
}

}

抱歉!评论已关闭.