MapReduce中map方法获取当前Record的路径

很多时候我们的hdfs路径设置的都是有规律的,而且从路径中可以获取一些信息。

那么怎么在map的过程中获取到当前处理的记录的路径呢?

// 假设当前路径为/data/app/app1/2015/09/13/00/custom.log.1
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
/* 省略其他代码 */
InputSplit split = context.getInputSplit(); // 得到当前的分片信息
Path path = ((FileSplit) split).getPath(); // /data/app/app1/2015/09/13/00/custom.log.1
String fileName = path.getName();
Path hourPath = path.getParent(); // /data/app/app1/2015/09/13/00
String hour = hourPath.getName(); // 00
Path dayPath = hourPath.getParent(); // /data/app/app1/2015/09/13
String day = dayPath.getName(); // 13
Path monthPath = dayPath.getParent();// /data/app/app1/2015/09
String month = monthPath.getName(); // 09
Path yearPath = monthPath.getParent(); // /data/app/app1/2015
String year = yearPath.getName(); // 2015
Path appPath = yearPath.getParent(); // /data/app/app1
String appName = appPath.getName(); // app1
/* ............. */

应用场景举例:

处理App产生的日志,很多时候日志里的时间戳是获取的手机上的时间,但是手机上的时间有时候会是很奇怪的。

所以我们会按收集到日志的时间来代替日志中的日期。

我们按照日期在Hadoop上归档日志,然后在MapReduce过程中就可以获取到日志接受时间了。

原文地址:https://www.cnblogs.com/erbin/p/4807520.html