MapReduce倒排索引概要
阿新 • • 發佈:2019-02-16
使用場景:主要用於索引,以提高搜尋資料速度
例如百度搜索
執行環境:windows下VM虛擬機器,centos系統,hadoop2.2.0,三節點 ,java 1.7
需要處理的資料為
求出每個索引所對應的包含索引的網址
package boke;
import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
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.Tool;
import org.apache.hadoop.util.ToolRunner;
public class descSort extends Configured implements Tool{
//map任務主要是把每行資料切分,把索引作為key,網址作為vaule
public static class Map extends
Mapper<LongWritable,Text,Text,Text>
{
public void map(LongWritable key,Text value,Context context)throws InterruptedException,IOException
{
String[] lineSplit=value.toString().split(" " );
context.write(new Text(lineSplit[0]), new Text(lineSplit[1]));
}
}
//reudce階段是把相同key(索引)的網址統一放到集合中,再統一輸出
public static class Reduce extends Reducer<Text,Text,Text,Text>
{
public void reduce(Text key,Iterable<Text> values,Context context)throws InterruptedException,IOException
{
StringBuffer sb =new StringBuffer();
boolean sign=false;
for(Text id : values)
{
if(sign)
{
sign=true;
}
else
{
sb.append(" ");
}
sb.append(id.toString());
}
context.write(key, new Text(sb.toString()));
}
}
public int run(String[] args)throws Exception
{
Configuration conf=getConf();
Job job=new Job(conf,"descSort");
job.setJarByClass(descSort.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
//這裡用了combiner可聚合每個map結果,減少reduce傳輸資料容量,從而優化效能
job.setCombinerClass(Reduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.waitForCompletion(true);
return job.isSuccessful()?1:0;
}
public static void main(String[] args)throws Exception
{
int rsa=ToolRunner.run(new Configuration(), new descSort(), args);
System.exit(rsa);
}
}
執行結果
注:combiner和reduce階段對資料處理的方法相同,如
(1 ,wwww.adf.com)(1 ,www.ert.com)
在combiner階段會合併成(1,wwww.adf.com www.ert.com)
map階段結束後會把資料存在本地,reduce階段把需要的資料通過網路傳輸到reduce節點本地,combiner可聚合map的結果,從而降低傳輸資料的大小,優化效能