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. 九度oj 1184 二叉树遍历

    原题链接:http://ac.jobdu.com/problem.php?pid=1184 简单的二叉树重建,遍历. 如下: #include<cstdio> #include<cs ...

  2. ORA-01017 invalid username/password;logon denied" (密码丢失解决方案)

    1.先确认是否输错 用户名和密码 2.如果的确是丢失密码的话: 查看sqlnet.ora 如果是 SQLNET.AUTHENTICATION_SERVICES= (NONE) , 需更改为SQLNET ...

  3. 纯真IP数据库导入mysql

    下载纯真IP数据库 安装后解压到本地为ip.txt 格式为: 1.1.145.0       1.1.147.255     泰国 沙功那空 1.1.148.0       1.1.149.255   ...

  4. Entity Framework 插入数据出现重复插入(导航属性硬是要查再一遍???????)

    问题: Artist artmodel = new Artist(); artmodel.user = uinfo; _artiests.Add(artmodel); 新增一条Artist记录,但是同 ...

  5. Memcached 在windows环境下安装

    1.memcached简介 memcached是一个高性能的分布式内存对象缓存系统,它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动应用的访问性 能.memcached基于 ...

  6. 通过WebBrowser取得AJAX后的网页

    通常情况下通过WebBrowser的文档加载完成事件DocumentCompleted中进行判断 if (_WebBrowder.ReadyState == WebBrowserReadyState. ...

  7. ios-UIWebView中js和oc代码的互调

    webview是ios中显示远程数据的网页控件,webview能显示的内容很多,MP4.文本.pdf等等: 关于js和oc代码的互相调用 1:oc中调用js代码; >>oc中调用js代码很 ...

  8. Gentoo 网络接口配置文件说明

    裁剪的Gentoo系统,仅供公司内部使用! [作为备份档案] 网络接口配置:/etc/conf.d/net #设置静态IPconfig_eth0="192.168.1.x/24" ...

  9. android 通过AlarmManager实现守护进程

    场景:在app崩溃或手动退出或静默安装后能够自动重启应用activity 前提:得到系统签名 platform.pk8.platform.x509.pem及signapk.jar 三个文件缺一不可(系 ...

  10. 网络服务器带宽Mbps、Mb/s、MB/s有什么区别?10M、100M到底是什么概念?

    网络服务器带宽Mbps.Mb/s.MB/s有什么区别?我们经常听到IDC提供的服务器接入带宽是10M独享,或者100M独享,100M共享之类的数据.这的10M.100M到底是什么概念呢? 工具/原料 ...