我正在使用虚拟盒上的map reduce运行简单的字数统计程序,安装了Cloudera Cent os并安装了所有先决条件。
package training;
import java.io.IOException;
import java.util.StringTokenizer;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.fs.Path;
public class WordCount {
public static class Map extends Mapper<LongWritable,Text,Text,IntWritable>{
public void map(LongWritable key, Text value,
Context context)
throws IOException,InterruptedException {
String line = value.toString();
StringTokenizer tokenizer = new StringTokenizer(line);
while (tokenizer.hasMoreTokens()) {
value.set(tokenizer.nextToken());
context.write(value, new IntWritable(1));
}
}
}
public static class Reduce extends Reducer<Text,IntWritable,Text,IntWritable>{
public void reduce(Text key, Iterable<IntWritable> values,
Context context)
throws IOException,InterruptedException {
int sum=0;
// TODO Auto-generated method stub
for(IntWritable x: values)
{
sum+=x.get();
}
context.write(key, new IntWritable(sum));
}
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
Configuration conf= new Configuration();
job.setJarByClass(WordCount.class);
job.setMapperClass(Map.class);
job.setReducerClass(Reduce.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
我将此项目导出为jar文件,并执行以下是我使用的命令
hadoop jar Map.jar training.Wordcount.class /<hdfs path of file>/filename.txt outputfile
但是我跑步时遇到的错误如下
java.io.IOException: Type mismatch in key from map: expected org.apache.hadoop.io.Text, received org.apache.hadoop.io.LongWritable
我不明白我到底错过了什么。
我尝试了所有可能的解决方案但没有成功。
有人可以帮助我完成详细的步骤,我的代码需要做哪些更改吗?
答案 0 :(得分:0)
我犯了错误。上面的代码都很好,但我执行时的错误是
hadoop jar Map.jar training.Wordcount.class /<hdfs path of file>/filename.txt outputfile.txt
我的Map Reduce结果显示的输出是目录而不是文件。
输出目录将包含一些文件,如r-00001等。当我打开这个文件时,我得到了内容如下
Hadoop 2
The 1
Job 4
其中上述文本表示输入文件中的内容/单词。
当我说.txt文件时,程序期望文本输入格式,但实际上我试图发送数字。所以这就是我收到错误的原因。
所以,我尝试的正确命令如下
hadoop jar Map.jar training.Wordcount.class /<hdfs path of file>/filename.txt outputDirectoryofHDFS