电商日志数据分析
一、项目要求:
根据电商日志文件,分析:
1 . 统计页面浏览量(每行记录就是一次浏览)
2 . 统计各个省份的浏览量 (需要解析IP)
3 . 日志的ETL操作(ETL:数据从来源端经过抽取(Extract)、转换(Transform)、加载(Load)至目的端的过程)
为什么要ETL:没有必要解析出所有数据,只需要解析出有价值的字段即可。本项目中需要解析出:ip、url、pageId(topicId对应的页面Id)、country、province、city
二、实现步骤
1.导入数据
导入数据到指定目录下:
在这里插入图片描述
2.编写代码
Map阶段代码如下
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
// Split the input line into fields based on the delimiter
String[] fields = value.toString().split("\u0001");
if (fields.length > 13) {
// Assuming the IP address is in the 14th field (index 13)
String ip = fields[13];
String log = value.toString();
LogParser parser = new LogParser();
Map<String, String> logInfo = parser.parse(log);
if (StringUtils.isNotBlank(logInfo.get("ip"))) {
IPParser.RegionInfo regionInfo = IPParser.getInstance().analyseIp(logInfo.get("ip"));
String province = regionInfo.getProvince();
if (StringUtils.isNotBlank(province)) {
context.write(new Text(province), new IntWritable(1));
} else {
context.write(new Text("-"), new IntWritable(1));
}
} else {
context.write(new Text("+"), new IntWritable(1));
}
}
}
这段代码的主要目的是从日志文件中提取IP地址,并分析其所在的省份。如果成功提取并分析出省份,就将省份名称作为键输出;如果省份名称无效,则输出一个特殊标记;如果IP地址无效,则输出另一个特殊标记。这样,Reducer阶段就可以根据这些键来聚合数据,例如统计每个省份的日志条目数量或标记无效的日志条目。
Reduce阶段代码如下:
protected 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);
}
reduce方法接收三个参数:
Text key:当前处理的键,通常是Mapper输出的键。
Iterable values:与该键相关联的所有值的集合。
Context context:Reducer的上下文对象,用于写入最终的输出结果。
3.打jar包进行上传