map/reduce基础——wordcount
wordcount是map/reduce中最基础的一个案例,是一个入门练习案例。
map/reduce一般分为三个组件mapper、reducer、dirver。mapper和reducer负责业务逻辑,driver负责提交业务。
mapper如下
public class Mapwordc extends Mapper<LongWritable, Text, Text, IntWritable> {
//该案例中ivalue的样式:hello world ni hao zm love
@Override
public void map(LongWritable ikey, Text ivalue, Context context) throws IOException, InterruptedException {
//map task 从文件按行读取<key,value>,第一个key默认是行偏移量,value是一行的数据
//把第一行数据转成字符串存放在line变量中
String line = ivalue.toString();
//按照空格将字符串line进行切分,存放在字符数组words[]中
String words [] = line.split(" ");
//遍历words数组,将其中的word作为key,进行输出,输出的<k,v>格式为<key,1>
for (String word:words) {
context.write(new Text(word), new IntWritable(1));
}
}
reducer如下
//reducer获得的数据格式如下:<hello,1>、< world,1>、< ni,1>、< hao,1>、< zm,1>、< love,1>
//reducer获得的key是Text,value是整形1
@Override
public void reduce(Text _key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException {
// process values
//设置一个变量进行计数
int count = 0;
//遍历values每个values都是1,每有一个value都在count上加一计数
for(IntWritable value:values) {
count+=value.get();
}
//同样是遍历values和上面效果一样。
/*Iterator<IntWritable> iterator = values.iterator();
while(iterator.hasNext()) {
IntWritable value = iterator.next();
count += value.get();
}*/
//输出<key,value>,key就是map传进来的key,value是对key的计数count
context.write(_key, new IntWritable(count));
}
driver程序
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf,"driwordc");
job.setJarByClass(cn.pdsu.mr.driwordc.class);