使用MapReduce求出各年销售笔数、各年销售总额
时间: 2023-09-17 20:13:58 浏览: 100
假设有一个包含销售数据的文件,每行包含日期、销售金额等信息,如下所示:
```
2018-01-01 100
2019-02-03 200
2018-03-04 150
```
我们可以使用MapReduce来求出各年销售笔数和总额。
首先,需要编写一个Mapper函数,将每行数据解析出日期和销售金额,然后将年份作为key,销售金额作为value输出。
```java
public class SalesMapper extends Mapper<LongWritable, Text, Text, DoubleWritable> {
private final static DoubleWritable sale = new DoubleWritable();
private Text year = new Text();
public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String[] fields = value.toString().split(" ");
String date = fields[0];
String sales = fields[1];
String year = date.substring(0, 4);
sale.set(Double.parseDouble(sales));
context.write(new Text(year), sale);
}
}
```
接下来,需要编写一个Reducer函数,将相同年份的销售金额累加起来,得到该年的销售总额和销售笔数。
```java
public class SalesReducer extends Reducer<Text, DoubleWritable, Text, Text> {
private Text result = new Text();
public void reduce(Text key, Iterable<DoubleWritable> values, Context context) throws IOException, InterruptedException {
double totalSales = 0;
int count = 0;
for (DoubleWritable val : values) {
totalSales += val.get();
count++;
}
result.set("Sales count: " + count + ", Total sales: " + totalSales);
context.write(key, result);
}
}
```
最后,在driver程序中指定输入和输出路径,以及Mapper和Reducer类。
```java
public class SalesAnalysis {
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "Sales Analysis");
job.setJarByClass(SalesAnalysis.class);
job.setMapperClass(SalesMapper.class);
job.setCombinerClass(SalesReducer.class);
job.setReducerClass(SalesReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(DoubleWritable.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
```
运行该程序,即可得到各年的销售笔数和总额。
注意:由于MapReduce是分布式计算,以上代码仅为示例,实际应用中需要考虑更多的细节和优化。
阅读全文