1.WordCount(统计单词)

经典的运用MapReuce编程模型的实例

1.1 Description

给定一系列的单词/数据,输出每个单词/数据的数量

1.2 Sample

 a is b is not c
b is a is not d

1.3 Output

 a:
b:
c:
d:
is:
not:

1.4 Solution

 /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.apache.hadoop.examples; import java.io.File;
import java.io.IOException;
import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
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.GenericOptionsParser; public class WordCount { //map输出的<key,value>为<输入的单词/数据,1>即<Text,IntWritable>
public static class TokenizerMapper
extends Mapper<Object, Text, Text, IntWritable>{
//value为封装好的int即IntWritable
private final static IntWritable one = new IntWritable(1);
private Text word = new Text(); public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
StringTokenizer itr = new StringTokenizer(value.toString());
while (itr.hasMoreTokens()) {
word.set(itr.nextToken());//word为每个单词/数据,以空格为分隔符识别
context.write(word, one);
}
}
} //reduce输入的<key,value>为<输入的单词/数据,各个值的1相加即sum(实际是一个list)>
//即<Text,IntWrite>
public static class IntSumReducer
extends Reducer<Text,IntWritable,Text,IntWritable> {
private IntWritable result = new IntWritable(); public void reduce(Text key, Iterable<IntWritable> values,
Context context
) throws IOException, InterruptedException {
int sum = 0;
for (IntWritable val : values) {
sum += val.get();
}
result.set(sum);
context.write(key, result);
}
} public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 2) {
System.err.println("Usage: wordcount <in> <out>");
System.exit(2);
}
//删除已存在的输出文件夹
judgeFileExist(otherArgs[1]);
Job job = new Job(conf, "word count");
job.setJarByClass(WordCount.class);
job.setMapperClass(TokenizerMapper.class);
job.setCombinerClass(IntSumReducer.class);
job.setReducerClass(IntSumReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntWritable.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
} //删除文件夹及其目录下的文件
public static void judgeFileExist(String path){
File file = new File(path);
if( file.exists() ){
deleteFileDir(file);
}
} public static void deleteFileDir(File path){
if( path.isDirectory() ){
String[] files = path.list();
for( int i=0;i<files.length;i++ ){
deleteFileDir( new File(path,files[i]) );
}
}
path.delete();
} }

2. 数据去重

2.1 Description

针对给定一系列的数据去重并输出

2.2 Sample

 3-1 a
3-2 b
3-3 c
3-4 d
3-5 a
3-6 b
3-7 c
3-3 c
3-1 b
3-2 a
3-3 b
3-4 d
3-5 a
3-6 c
3-7 d
3-3 c

2.3 Output

 3-1 a
3-1 b
3-2 a
3-2 b
3-3 b
3-3 c
3-4 d
3-5 a
3-6 b
3-6 c
3-7 c
3-7 d

2.4 Solution

 /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.apache.hadoop.examples; import java.io.File;
import java.io.IOException;
import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
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.GenericOptionsParser; public class WordCount { public static class Map extends Mapper<Object,Text,Text,Text>{//map最后一个指定Text
public static Text lineWords= new Text(); //map输出为<Text,Text>,因为只涉及到是否Key存在的问题,故value可任意
public void map(Object key,Text value,Context context)
throws IOException, InterruptedException{
lineWords = value;
context.write(lineWords, new Text(""));//<Text,Text>
}
} public static class Reduce extends Reducer<Text,Text,Text,Text>{
public void reduce(Text key,Iterable<Text> values,Context context)
throws IOException, InterruptedException{
context.write(key,new Text(""));
}
} public static void main(String args[])
throws IOException, ClassNotFoundException, InterruptedException{
Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf,args).getRemainingArgs();
if( otherArgs.length!=2 ){
System.err.println("Usage: Data Deduplication <in> <out>");
System.exit(2);
} //删除已存在的输出文件夹
judgeFileExist(otherArgs[1]);
Job job = new Job(conf,"Data Dup");
job.setJarByClass(WordCount.class);
//设置map combine reduce处理类
job.setMapperClass(Map.class);
job.setCombinerClass(Reduce.class);
job.setReducerClass(Reduce.class);
//设置key value的类型
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
//设置输入和输出目录
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
} //删除文件夹及其目录下的文件
public static void judgeFileExist(String path){
File file = new File(path);
if( file.exists() ){
deleteFileDir(file);
}
} public static void deleteFileDir(File path){
if( path.isDirectory() ){
String[] files = path.list();
for( int i=0;i<files.length;i++ ){
deleteFileDir( new File(path,files[i]) );
}
}
path.delete();
} }

3. 数据排序

3.1 Description

给多个文件的数据排序,每个文件中的每个数据占一行

3.2 Sample


3.3 Output


3.4 Solution

 /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.apache.hadoop.example; import java.io.File;
import java.io.IOException; import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
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.GenericOptionsParser; public class dataSort{ public static class map extends Mapper<Object,Text,IntWritable,IntWritable>{
private static IntWritable data = new IntWritable();
String lineWords = new String();
//map
public void map(Object key,Text value,Context context)
throws IOException, InterruptedException{
lineWords = value.toString();
data.set(Integer.parseInt(lineWords));
context.write(data,new IntWritable(1));
}
} public static class reduce extends Reducer<IntWritable, IntWritable,IntWritable,IntWritable>{
private static IntWritable lineNum = new IntWritable(1);
public void reduce(IntWritable key,Iterable<IntWritable> values,Context context)
throws IOException, InterruptedException{
for(IntWritable val:values){
context.write(lineNum,key);
lineNum = new IntWritable(lineNum.get()+1);
}
}
} public static void main(String args[])
throws IOException, ClassNotFoundException, InterruptedException{
Configuration conf = new Configuration(); String[] otherArgs = new GenericOptionsParser(conf,args).getRemainingArgs();
if( otherArgs.length!=2 ){
System.err.println("Usage: Data Deduplication <in> <out>");
System.exit(2);
} //删除已存在的输出文件夹
judgeFileExist(otherArgs[1]);
Job job = new Job(conf,"Data Dup");
job.setJarByClass(dataSort.class);
//设置map combine reduce处理类
job.setMapperClass(map.class);
job.setCombinerClass(reduce.class);
job.setReducerClass(reduce.class);
//设置key value的类型
job.setOutputKeyClass(IntWritable.class);
job.setOutputValueClass(IntWritable.class);
//设置输入和输出目录
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
//删除文件夹及其目录下的文件
public static void judgeFileExist(String path){
File file = new File(path);
if( file.exists() ){
deleteFileDir(file);
}
} public static void deleteFileDir(File path){
if( path.isDirectory() ){
String[] files = path.list();
for( int i=0;i<files.length;i++ ){
deleteFileDir( new File(path,files[i]) );
}
}
path.delete();
}
}

MapReduce实例的更多相关文章

  1. MapReduce实例2(自定义compare、partition)& shuffle机制

    MapReduce实例2(自定义compare.partition)& shuffle机制 实例:统计流量 有一份流量数据,结构是:时间戳.手机号.....上行流量.下行流量,需求是统计每个用 ...

  2. MapReduce实例&YARN框架

    MapReduce实例&YARN框架 一个wordcount程序 统计一个相当大的数据文件中,每个单词出现的个数. 一.分析map和reduce的工作 map: 切分单词 遍历单词数据输出 r ...

  3. MapReduce实例浅析

    在文章<MapReduce原理与设计思想>中,详细剖析了MapReduce的原理,这篇文章则通过实例重点剖析MapReduce 本文地址:http://www.cnblogs.com/ar ...

  4. MapReduce实例-基于内容的推荐(一)

    环境: Hadoop1.x,CentOS6.5,三台虚拟机搭建的模拟分布式环境 数据:下载的amazon产品共同采购网络元数据(需FQ下载)http://snap.stanford.edu/data/ ...

  5. MapReduce实例-倒排索引

    环境: Hadoop1.x,CentOS6.5,三台虚拟机搭建的模拟分布式环境 数据:任意数量.格式的文本文件(我用的四个.java代码文件) 方案目标: 根据提供的文本文件,提取出每个单词在哪个文件 ...

  6. MapReduce实例-NASA博客数据频度简单分析

    环境: Hadoop1.x,CentOS6.5,三台虚拟机搭建的模拟分布式环境,gnuplot, 数据:http://ita.ee.lbl.gov/html/contrib/NASA-HTTP.htm ...

  7. MapReduce实例——求平均值,所得结果无法写出到文件的错误原因及解决方案

    1.错误原因 mapreduce按行读取文本,map需要在原有基础上增加一个控制语句,使得读到空行时不执行write操作,否则reduce不接受,也无法输出到新路径. 2.解决方案 原错误代码 pub ...

  8. MapReduce实例(数据去重)

    数据去重: 原理(理解):Mapreduce程序首先应该确认<k3,v3>,根据<k3,v3>确定<k2,v2>,原始数据中出现次数超过一次的数据在输出文件中只出现 ...

  9. MapReduce实例——查询缺失扑克牌

    问题: 解决: 首先分为两个过程,Map过程将<=10的牌去掉,然后只针对于>10的牌进行分类,Reduce过程,将Map传过来的键值对进行统计,然后计算出少于3张牌的的花色 1.代码 1 ...

随机推荐

  1. CDN 内容分发网络技术

    1.前言 Internet的高速发展,给人们的工作和生活带来了极大的便利,对Internet的服务品质和访问速度要求越来越高,虽然带宽不断增加,用户数量也在不断增加,受Web服务器的负荷和传输距离等因 ...

  2. .net 面试问题 汇总

    用.net做B/S结构的系统,您是用几层结构来开发,每一层之间的关系以及为什么要这样分层? 答: 从下至上分别为:数据访问层.业务逻辑层(又或成为领域层).表示层 数据访问层:有时候也称为是持久层,其 ...

  3. [转]p2p端口映射工具 dog-tunnel

    [转]p2p端口映射工具 dog-tunnel http://www.oschina.net/p/dog-tunnel 狗洞是一个高速的 P2P 端口映射工具,同时支持Socks5代理. 0.5版后开 ...

  4. 61.MII、RMII、GMII接口的详细介绍

    概述: MII (Media Independent Interface(介质无关接口)或称为媒体独立接口,它是IEEE-802.3定义的以太网行业标准.它包括一个数据接口和一个MAC和PHY之间的管 ...

  5. visualgo 数据结构与算法可视化工具

    推荐可视化数据结构与算法工具 http://zh.visualgo.net/

  6. hasOwnProperty与isPrototypeOf

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  7. Upgrading to Java 8——第四章 The Stream API

    在这章中我们将学习Stream API,在JDK 8 中的一项新的特性.为了理解这一章的主题,你需要知道如何使用Lambda表达式和java.util.function里的预定义的函数式接口. 一个S ...

  8. android中的“visible ”、“invisible”、“gone”的区别(转载)

    在Android开 发中,大部分控件都有visibility这个属性,其属性有3个分别为“visible ”.“invisible”.“gone”.主要用来设置控制控件的显示和隐藏.有些人可能会疑惑I ...

  9. PHP去除数组中重复数据的两个例子

    例一: <?php$input = array("a" => "green","", "red"," ...

  10. codeforces 161D Distance in Tree 树形dp

    题目链接: http://codeforces.com/contest/161/problem/D D. Distance in Tree time limit per test 3 secondsm ...