数据资源下载:空气质量数据下载
基于map reducer对数据进行分析实现下面的结果输出
代码设计:重写map,reducer类,再写一个运行实现类。
package PMCount;
import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
public class AirMapper extends Mapper<LongWritable, Text, Text, LongWritable>{
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line = value.toString();
String[] fields = line.split(",");
int year = Integer.parseInt(fields[1].substring(0,4));//要求只要年份不需要月份日期,进行数据处理。
String city = fields[0];
String quality = fields[2];
String place = year + " " + city + " " +quality;//分析数据可知可以合并写入当作键值
context.write(new Text(place),new LongWritable(1));
}
}
package PMCount;
import java.io.IOException;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
public class AirReducer extends Reducer<Text, LongWritable, Text, LongWritable>{
protected void reduce(Text key, Iterable<LongWritable> values, Context context) throws IOException, InterruptedException {
int count = 0;
for (LongWritable value : values) {
count++;
}
context.write(key,new LongWritable(count));
}
}
package PMCount;
import java.io.IOException;
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.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.log4j.BasicConfigurator;
public class AirRunner {
// Driver端的代码:八股文
public static void main(String[] args) throws Exception {
Configuration configuration = new Configuration();
// 如果输出目录已经存在,则先删除
FileSystem fileSystem = FileSystem.get(configuration);
Path outputPath = new Path(args[1]);
if(fileSystem.exists(outputPath)) {
fileSystem.delete(outputPath,true);
}
Job job = Job.getInstance(configuration);
job.setJarByClass(AirRunner.class);
job.setMapperClass(AirMapper.class);
job.setReducerClass(AirReducer.class);
job.setMapOutputKeyClass(Text.class);
job.setMapOutputValueClass(LongWritable.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
FileInputFormat.setInputPaths(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, outputPath);
job.waitForCompletion(true);
}
}
方式一:本地导入数据,本地运行
方式二:打jar再Hadoop上运行
打包
上传数据到Hadoop
运行jar包
查看数据
**拓展:**基于map reducer框架例如此题中的,如下
Mapper<LongWritable, Text, Text, LongWritable>
Reducer<Text, LongWritable, Text, LongWritable>
对于传入的LongWritable, Text, Text, LongWritable这几种对象,也能传入自己定义的对象类,实现对与其他要求的数据统计,或者其他功能和要求。