O MapReduce é um modelo de programação paralela desenvolvido no Google para grandes conjuntos de dados. Ele processa dados em blocos, em vez de em ordem sequencial. Para isso, baseia-se em um mapa de funções de entrada pareadas (chaves) e valores, que passam pela função reduce — daí o nome — para tornar os dados mais compreensíveis. Em vez de fornecer à função map uma chave e um valor, um índice invertido pareia palavras e documentos para buscar texto. Você pode usar índices invertidos no MapReduce para criar um índice de busca por palavra-chave, por exemplo.
Instruções
- Digite o código da função map:
public static class InvertedIndexerMapper extends MapReduceBase
implements Mapper<LongWritable, Text, Text, Text>
{
private final static Text word = new Text () ;
private final static Text location = new Text () ;
public void map(LongWritable key, Text val,
OutputCollector<Text, Text> output, Reporter reporter)
throws IOException
{
FileSplit fileSplit = (FileSplit) reporter.getInputSplit() ;
String fileName = fileSplit.getPath() .getName() ;
location.set(fileName) ;
String line - val.toString() ;
StringTokenizer itr = new StringTokenizer(line.toLowerCase()) ;
while (itr.hasMoreTokens()) {
word.set(itr.nextToken()) ;
output.collect(word, location) ;
}
}
}
- Digite o código da função reduce:
public static class InvertedIndexerReducer extends MapReduceBase
implements Reducer<Text, Text, Text, Text>
{
public void reduce(Text key, Iterator<Text> values,
OutputCollector<Text, Text> output,
Reporter reporter) throws IOException
{
boolean first = true;
StringBuilder toReturn = new StringBuilder() ;
while (values.hasNext()) {
if (!first)
toReturn.append(", ") ;
first = false;
toReturn.append(values.next().toString()) ;
}
output.collect(key, new Text(toReturn.toString())) ;
}
}
- Digite o código para completar o índice invertido:
public static void main(String[] args) throws IOException
{
if (args.length < 2) {
System.out
println("Usage: InvertedIndex <input path> <output path>") ;
system.exit(1) ;
}
JobConf conf = new JobConf(InvertedIndex.class) ;
conf.setJobName("InvertedIndex") ;
conf.setOutputKeyClass(Text.class) ;
conf.setOutputValueClass(Text.class) ;
conf.setMapperClass(InvertedIndexerMapper.class) ;
conf.setReducerClass(InvertedIndexerReducer.class) ;
FileInputFormat.setInputPaths(conf, new Path(args[0])) ;
FileOutputFormat.setOutputPath(conf, new Path(args[1])) ;
try {
JobClient.runJob(conf) ;
} catch (Exception e) {
e.printStackTrace() ;
}
}