示例

数据:

-- ::    34c
-- :: 36c
-- :: 32c
-- :: 37c
-- :: 23c
-- :: 45c
-- :: 50c
-- :: 33c
-- :: 41c
-- :: 27c
-- :: 45c
-- :: 46c
-- :: 47c

要求:

将每年每月中的气温排名前三的数据找出来

实现:

1.每一年用一个reduce任务处理;

2.创建自定义数据类型,存储 [年-月-日-温度];

2.自己实现排序函数 根据 [年-月-温度] 降序排列,也可以在定义数据类型中进行排序;

3.自己实现分组函数,对 [年-月] 分组,reduce的key是分组结果,根据相同的分组值,统计reduce的value值,只统计三个值就可以,因为已经实现了自排序函数。

注意点:

1.自定义数据类型的使用;

2.自定义排序类的使用;

3.自定义分组类的使用,分组类对那些数据进行分组;

4.自定义分区类,分区类与reduce job个数的关系;

示例代码:

RunJob.java

 import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
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 java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date; /**
* weather 统计天气信息
*
* 数据:
* 1999-10-01 14:21:02 34c
* 1999-11-02 13:01:02 30c
*
* 要求:
* 将每年的每月中气温排名前三的数据找出来
*
* 实现:
* 1.每一年用一个reduce任务处理;
* 2.创建自定义数据类型,存储 [年-月-日-温度];
* 2.自己实现排序函数 根据 [年-月-温度] 降序排列,也可以在定义数据类型中进行排序;
* 3.自己实现分组函数,对 [年-月] 分组,reduce的key是分组结果,根据相同的分组值,统计reduce的value值,只统计三个值就可以,因为已经实现了自排序函数。
*
* Created by Edward on 2016/7/11.
*/
public class RunJob { public static void main(String[] args)
{
//access hdfs's user
System.setProperty("HADOOP_USER_NAME","root"); Configuration conf = new Configuration();
conf.set("fs.defaultFS", "hdfs://node1:8020"); try {
FileSystem fs = FileSystem.get(conf); Job job = Job.getInstance(conf);
job.setJarByClass(RunJob.class);
job.setMapperClass(MyMapper.class);
job.setReducerClass(MyReducer.class); //需要指定 map out 的 key 和 value
job.setOutputKeyClass(InfoWritable.class);
job.setOutputValueClass(Text.class); //设置分区 继承 HashPartitioner
job.setPartitionerClass(YearPartition.class);
//根据年份创建指定数量的reduce task
job.setNumReduceTasks(3); //设置排序 继承 WritableComparator
//job.setSortComparatorClass(SortComparator.class); //设置分组 继承 WritableComparator 对reduce中的key进行分组
job.setGroupingComparatorClass(GroupComparator.class); FileInputFormat.addInputPath(job, new Path("/test/weather/input")); Path path = new Path("/test/weather/output");
if(fs.exists(path))//如果目录存在,则删除目录
{
fs.delete(path,true);
}
FileOutputFormat.setOutputPath(job, path); boolean b = job.waitForCompletion(true);
if(b)
{
System.out.println("OK");
} } catch (Exception e) {
e.printStackTrace();
}
} public static class MyMapper extends Mapper<LongWritable, Text, InfoWritable, Text > { private static SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); @Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String[] str = value.toString().split("\t"); try {
Date date = sdf.parse(str[0]);
Calendar c = Calendar.getInstance();
c.setTime(date);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH)+1;
int day = c.get(Calendar.DAY_OF_MONTH); double temperature = Double.parseDouble(str[1].substring(0,str[1].length()-1)); InfoWritable info = new InfoWritable();
info.setYear(year);
info.setMonth(month);
info.setDay(day);
info.setTemperature(temperature); context.write(info, value); } catch (ParseException e) {
e.printStackTrace();
}
}
} public static class MyReducer extends Reducer<InfoWritable, Text, Text, NullWritable> {
@Override
protected void reduce(InfoWritable key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
int i=0;
for(Text t: values)
{
i++;
if(i>3)
break;
context.write(t, NullWritable.get());
}
}
}
}

InfoWritable.java

 import org.apache.hadoop.io.WritableComparable;

 import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException; /**
* 自定义数据类型 继承 WritableComparable
* 【年-月-日-温度】
* Created by Edward on 2016/7/11.
*/
public class InfoWritable implements WritableComparable<InfoWritable> { private int year;
private int month;
private int day;
private double temperature; public void setYear(int year) {
this.year = year;
} public void setMonth(int month) {
this.month = month;
} public void setDay(int day) {
this.day = day;
} public void setTemperature(double temperature) {
this.temperature = temperature;
} public int getYear() {
return year;
} public int getMonth() {
return month;
} public int getDay() {
return day;
} public double getTemperature() {
return temperature;
} /**
*
* 对象比较,对温度进行倒序排序
*/
@Override
public int compareTo(InfoWritable o) { int result = Integer.compare(this.getYear(),o.getYear());
if(result == 0)
{
result = Integer.compare(this.getMonth(),o.getMonth());
if(result == 0)
{
return -Double.compare(this.getTemperature(), o.getTemperature());
}
else
return result;
}
else
return result; //return this==o?0:-1;
} @Override
public void write(DataOutput dataOutput) throws IOException {
dataOutput.writeInt(this.year);
dataOutput.writeInt(this.month);
dataOutput.writeInt(this.day);
dataOutput.writeDouble(this.temperature);
} @Override
public void readFields(DataInput dataInput) throws IOException {
this.year = dataInput.readInt();
this.month = dataInput.readInt();
this.day = dataInput.readInt();
this.temperature = dataInput.readDouble();
}
}

YearPartition.java

 import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.lib.partition.HashPartitioner; /**
*
* 创建分区,通过key中的year来创建分区
*
* Created by Edward on 2016/7/11.
*/
public class YearPartition extends HashPartitioner <InfoWritable, Text>{
@Override
public int getPartition(InfoWritable key, Text value, int numReduceTasks) {
return key.getYear()%numReduceTasks;
}
}

GroupComparator.java

 import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator; /**
* 创建分组类,继承WritableComparator
* 【年-月】
* Created by Edward on 2016/7/11.
*/
public class GroupComparator extends WritableComparator { GroupComparator()
{
super(InfoWritable.class, true);
} @Override
public int compare(WritableComparable a, WritableComparable b) {
InfoWritable ia = (InfoWritable)a;
InfoWritable ib = (InfoWritable)b; int result = Integer.compare(ia.getYear(),ib.getYear());
if(result == 0)
{
return Integer.compare(ia.getMonth(),ib.getMonth());
}
else
return result;
}
}

SortComparator.java

 import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator; /**
* 排序类,继承WritableComparator
* 排序规则【年-月-温度】 温度降序
* Created by Edward on 2016/7/11.
*/
public class SortComparator extends WritableComparator { /**
* 调用父类的构造函数
*/
SortComparator()
{
super(InfoWritable.class, true);
} /**
* 比较两个对象的大小,使用降序排列
* @param a
* @param b
* @return
*/
@Override
public int compare(WritableComparable a, WritableComparable b) { InfoWritable ia = (InfoWritable)a;
InfoWritable ib = (InfoWritable)b; int result = Integer.compare(ia.getYear(),ib.getYear());
if(result == 0)
{
result = Integer.compare(ia.getMonth(),ib.getMonth());
if(result == 0)
{
return -Double.compare(ia.getTemperature(), ib.getTemperature());
}
else
return result;
}
else
return result;
}
}

MapReduce -- 统计天气信息的更多相关文章

  1. 半吊子学习Swift--天气预报程序-获取天气信息

    昨天申请的彩云天气Api开发者今天上午已审核通过  饭后运动过后就马不停蹄的来测试接口,接口是采用经纬度的方式来获取天气信息,接口地址如下 https://api.caiyunapp.com/v2/ ...

  2. 内网公告牌获取天气信息解决方案(C# WebForm)

    需求:内网公告牌能够正确显示未来三天的天气信息 本文关键字:C#/WebForm/Web定时任务/Ajax跨域 规划: 1.天定时读取百度接口获取天气信息并存储至Txt文档: 2.示牌开启时请求Web ...

  3. 使用小米天气API获取天气信息

    1. URL部分 以下url中"%s"代表的是城市Id,比如北京的cityId=101010100: //获取未来五天预报信息,红色部分信息不需要 WEATHER_DATA_URL ...

  4. C#调用WebService获取天气信息

    概述 本文使用C#开发Winform应用程序,通过调用<WebXml/>(URL:http://www.webxml.com.cn)的WebService服务WeatherWS来获取天气预 ...

  5. ASP获取json天气信息

    ASP代码(ASP获取页面源码方法,有编码.超时时间参数,处理了乱码.超时的问题): Function GetHttpPage(HttpUrl) Then GetHttpPage="$Fal ...

  6. java获取天气信息

    通过天气信息接口获取天气信息,首先要给项目导入程序所需要的包,具体需要如下几个包: json-lib-2.4.jar ezmorph-1.0.6.jar commons-beanutils-1.8.3 ...

  7. 利用json获取天气信息

    天气预报信息获取是利用json获取的,网上有非常多资源,源码.因为上面涉及到非常多天气信息,包含湿度,出行建议等,以及加入了全部城市代码的资源包.为了练手了解json的原理.我仅获取诚笃城市的最高温, ...

  8. PHP Ajax JavaScript Json 实现天气信息获取

    使用第三方服务 间接方式 思路 使用到的服务 实现代码 前端完整代码 总结 要在自己的网站上添加一个天气预报功能,是一个很普通的需求,实现起来也不是很难.今天来介绍几个简单的方法. 使用第三方服务 有 ...

  9. MongoDb 用 mapreduce 统计留存率

    MongoDb 用 mapreduce 统计留存率(金庆的专栏)留存的定义采用的是新增账号第X日:某日新增的账号中,在新增日后第X日有登录行为记为留存 输出如下:(类同友盟的留存率显示)留存用户注册时 ...

随机推荐

  1. [AngularJS] “路由”的定义概念、使用详解——AngularJS学习资料教程

    这是小编的一些学习资料,理论上只是为了自己以后学习需要的,但是还是需要认真对待的 以下内容仅供参考,请慎重使用学习 AngularJS“路由”的定义概念 AngularJS最近真的很火,很多同事啊同学 ...

  2. check选择样式

    样式一(H5): <form action="#">  <div class="wrapper">    <div class=& ...

  3. 清除浮动以及:after元素

    http://www.iyunlu.com/demo/enclosing-float-and-clearing-float/index.html 以上这篇示意图把清除浮动的几种方法讲的非常清楚了,其中 ...

  4. ORACLE EXPDP命令使用详细

    相关参数以及导出示例: 1. DIRECTORY 指定转储文件和日志文件所在的目录DIRECTORY=directory_objectDirectory_object用于指定目录对象名称.需要注意,目 ...

  5. null的专栏:https://blog.csdn.net/google19890102

    null的专栏:https://blog.csdn.net/google19890102 csdn博客专栏:https://blog.csdn.net/column.html

  6. 使用 CLI 创建 Azure VM 的自定义映像

    自定义映像类似于应用商店映像,不同的是自定义映像的创建者是你自己. 自定义映像可用于启动配置,例如预加载应用程序.应用程序配置和其他 OS 配置. 在本教程中,你将创建自己的 Azure 虚拟机自定义 ...

  7. SQL Server 登录名、用户、角色与权限

    1.在SQL Server中,用户和角色是分为服务器级别和数据库级别的 2.服务器级别 登录名:指有权限登录到某服务器的用户,例如超级管理员的登录名是sa: 登录名具体位置在  数据库——>安全 ...

  8. Vue2学习笔记:v-for指令

    1.使用 <!DOCTYPE html> <html> <head> <title></title> <meta charset=&q ...

  9. 转:未能打开编辑器:Unmatched braces in the pattern.

    原文地址:http://blog.csdn.net/hytdsky/article/details/4736462 Eclipse出现这个问题而不能查看源代码  原因就是语言包的问题 出现这个问题了 ...

  10. Flask配置文件和 路由系统

    debug = True开启debug模式 当你的代码在界面增减之后不用刷新界面自动更新 app.logger.error("这是error模式") app.logger.info ...