Open rainit2006 opened 6 years ago
Hadoop编程入门(2011年的内容了,有些old。特别是map函数的参数也变了) http://www.jiacheo.org/blog/233
通过split之后, 他变成了若干的分片, 每个分片交给一个Map处理
map处理完后, tasktracker会把数据进行复制和排序, 然后通过输出的key 和value进行 partition的划分, 并把partition相同的map输出, 合并为相同的reduce的输入.
ruducer通过处理, 把数据输出, 每个相同的key, 一定在一个reduce中处理完, 每一个reduce至少对应一份输出(可以通过扩展MultipleOutputFormat来得到多分输出)
来看一个例子, 如下图:(来自 《hadoop权威指南》 一书)
实例
说明几点:
5.1 输入的数据可能就是一堆文本
5.2 mapper会解析每行数据, 然后提取有效的数据, 作为输出. 这里的例子是 从日志文件中提取每一年每天的气温, 最后会计算每年的最高气温
5.3 map的输出就是一条一条的 key-value
5.4 通过shuffle之后, 变成reduce的输入, 这是相同的key对应的value被组合成了一个迭代器
5.5 reduce的任务是提取每一年的最高气温, 然后输出
二. Mapper
Hadoop编程初级实例(2011年的例子,old了) http://www.jiacheo.org/blog/233
hadoop jar site-pv-job.jar org.jiacheo.SitePVSumSampleJob
6.5 查看hadoop的web 工具, 显示当前job进度.
http://www.cnblogs.com/sunddenly/p/3985386.html
1.2.1 Mapper类 map 函数定义如下代码
protected void map(KEYIN key, VALUEIN value, Context context)
throws IOException, InterruptedException
{
context.write((KEYOUT) key, (VALUEOUT) value);
}
1.2.2 Reducer类 reduce 函数定义如下代码
protected void reduce(KEYIN key, Iterable<VALUEIN> values, Context context) throws IOException, InterruptedException
{
for(VALUEIN value: values) {
context.write((KEYOUT) key, (VALUEOUT) value);
}
}
二、 MapReduce 执行原理
2.1 MapRduce执行流程
2.2 Mapper 任务的执行过程
其中,
第二阶段是对输入片中的记录按照一定的规则解析成键值对。有个默认规则是把每一行文本内容解析成键值对。“键”是每一行的起始位置(单位是字节),“值”是本行的文本内容。
第五阶段是对每个分区中的键值对进行排序。首先,按照键进行排序,对于键相同的键值对,按照值进行排序。比如三个键值对<2,2>、<1,3>、<2,1>,键和值分别是整数。那么排序后的结果是<1,3>、<2,1>、<2,2>。
2.3 Reducer执行过程
在整个MapReduce 程序的执行过程中如图2.4,我可以根据上面的讲解来分析下面MapReducer执行过程,从下图可知每个Mapper任务分了两个区,因此会有两个Reducer任务,最终产生两个HDFS副本。
其他: Mapper 类的泛型不是java 的基本类型,而是Hadoop 的数据类型LongWritable、Text、IntWritable。读者可以简单的等价为java 的类long、String、int。
Hadoop初级实验, 很多入门的例子,很好 http://www.jianshu.com/p/7328bb45a7cd
JobClient.runJob(JobConf) 和 job.waitForCompletion 的区别:
JobConf and everything else in the org.apache.hadoop.mapred package is part of the old API used to write hadoop jobs,
Job and everything in the org.apache.hadoop.mapreduce package is part of the new and preferred API to write hadoop jobs.
Both APIs generally provide equivalent core functionality. Job control is performed through the Job class in the new API, rather than the old JobClient, which no longer exists in the new API.
Hadoop旧版本0.2. x与新版本1. x的 API比较 1.存放的位置 一个位于org.apache.hadoop.mapred,这个是老的API; 一个位于org.apache.hadoop.mapreduce,这个是新的API。
2.接口与抽象类 在老的API体系中,InputFormat是一个接口,而在新的API体系中,InputFormat是一个抽象类。 熟悉java的同学都知道接口最大的优点是允许一个类实现多个接口,从而达到类似多重继承的目的。但是在hadoop体系中,这个优势体现并不明显。而且接口的实现类(不含抽象类),必须实现接口的每个方法。相对来说,抽象类的约束较弱。抽象类可以为某些方法默认实现(实际上我们在阅读hadoop的源码时,能看到很多抽象类,大部分抽象类里既有abstract方法需要自己重写,又有不带abstract默认已经实现的方法)。这样做的好处就是,当需要给抽象类添加新方法时,为了保持向后兼容,只需要给抽象类的新添加方法提供默认实现即可,之前的代码完全无须修改。
3 上下文封装 新版API 将变量和函数封装成各种上下文(Context)类,使得API 具有更好的易用性和扩展性。首先,函数参数列表经封装后变短,使得函数更容易使用;其次,当需要修改或添加某些变量或函数时,只需修改封装后的上下文类即可,用户代码无须修改,这样保证了向后兼容性,具有良好的扩展性。 这些Context 各自封装了一种实体的基本信息及对应的操作(setter 和getter 函数),如JobContext、TaskAttemptContext 分别封装了Job 和Task 的基本信息,TaskInputOutputContext 封装了Task 的各种输入输出操作,MapContext 和ReduceContext 分别封装了Mapper 和Reducer 对外的公共接口。
Hadoop1.x和2.x的其他变化:
1.配置文件的路径
在1.x中,Hadoop的配置文件是放在$HADOOP_HOME/conf目录下的,关键的配置文件在src目录都有对应的存放着默认值的文件,如下:
在2.x中,Hadoop的架构发生了变化,配置文件的路径也发生了变化,放到了$HADOOP_HOME/etc/hadoop目录,这样修改的目的,应该是让其更接近于Linux的目录结构吧,让Linux用户理解起来更容易。 Hadoop 2.x中配置文件的几个主要的变化: l 去除了原来1.x中包括的$HADOOP_HOME/src目录,该目录包括关键配置文件的默认值; l 默认不存在mapred-site.xml文件,需要将当前mapred-site.xml.template文件copy一份并重命名为mapred-site.xml,并且只是一个具有configuration节点的空文件; l 默认不存在mapred-queues.xml文件,需要将当前mapred-queues.xml.template文件copy一份并重命名为mapred-queues.xml; l 删除了master文件,现在master的配置在hdfs-site.xml通过属性dfs.namenode.secondary.http-address来设置, 如下:
<property>
<name>dfs.namenode.secondary.http-address</name>
<value>nginx1:9001</value>
</property>
l 增加了yarn-env.sh,用于设置ResourceManager需要的环境变量,主要需要修改JAVA_HOME; l 增加yarn-site.xml配置文件,用于设置ResourceManager;
2,命令文件目录的变化 在1.x中,所有的命令文件,都是放在bin目录下,没有区分客户端和服务端命令,并且最终命令的执行都会调用hadoop去执行; 而在2.x中将服务端使用的命令单独放到了sbin目录,其中有几个主要的变化: http://blog.csdn.net/fenglibing/article/details/32916445
Hadoop Chain Mapper Example Pattern : Mapper1 -> Mapper2 -> Reducer-> Mapper3 关键: ChainMapper类。
ChainMapper.addMapper(job, //主作业
Mapper1.class, //待加入的map class
LongWritable.class, //待加入map class的输入key类型
Text.class, //待加入map class的输入value类型
Text.class, //待加入map class的输出key类型
VLongWritable.class, //待加入map class的输出value类型
map1Conf); //待加入map class的配置信息
//配置mapper2
ChainMapper.addMapper(job, Mapper2.class, Text.class, VLongWritable.class, Text.class, VLongWritable.class, new Configuration(false));
/**
* 配置Reducer
* 注意此处使用的是setReducer()方法
*/
ChainReducer.setReducer(job, Reducer_Only.class, Text.class, VLongWritable.class, Text.class, VLongWritable.class, new Configuration(false));
//配置mapper3
ChainReducer.addMapper(job, Mapper3.class, Text.class, VLongWritable.class, Text.class, VLongWritable.class, new Configuration(false));
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
job.waitForCompletion(true);
对任意MR作业,Map和Reduce阶段可以有无限个Mapper,但reduer只能有一个. ChainReducer专门提供了一个setRreducer()方法来设置整个作业唯一的Reducer。
Fila项目里到的Hadoop 类
项目里让Key作为文件名称。
@Override
protected String generateFileNameForKeyValue(Text key, Writable value, String name) {
return key.toString();
}
-- getBaseRecordWriter method
protected abstract RecordWriter<K,V> getBaseRecordWriter(FileSystem fs,
JobConf job,
String name,
Progressable arg3)
throws IOException
Parameters:
fs - the file system to use
job - a job conf object
name - the name of the file over which a record writer object will be constructed
arg3 - a progressable object
Returns:
A RecordWriter object over the given file
项目里重写了该函数中,没有用fs参数,而是用自己定义的RecordWriter对象来实现文件的写入。 利用FileOutputFormat的getTaskOutputPath函数创建了一个自己的ouput directory. 接着利用orcOutputFormat来生成一个新的RecordWriter作为函数的返回值。
FileOutputFormat<K,V>类 -- getTaskOutputPath(JobConf conf, String name) Helper function to create the task's temporary output directory and return the path to the task's output file.
orcOutputFormat类 import org.apache.hadoop.mapred.lib.MultipleOutputFormat;
@Override
protected RecordWriter getBaseRecordWriter(FileSystem fileSystem, JobConf job, String name, Progressable progressable) throws IOException {
// Because we know that each key results in a file and each file only holds data for one key we can close
// the previous writer (if any) to prevent running into OOM exceptions.
if (recordWriter != null) {
recordWriter.close(null);
recordWriter = null;
}
LOG.info("Creating writer for {}", name);
// it turns out OrcOutputFormat ignores the file system and creates the file on hdfs instead
Path file = FileOutputFormat.getTaskOutputPath(job, name);
final String fsName = file.toString();
LOG.info("Name converted to {}", fsName);
recordWriter = orcOutputFormat.getRecordWriter(fileSystem, job, fsName, progressable);
return recordWriter;
}
Spark
RDD(Resilient Distributed Dataset) 不変(イミュータブル)で並列実行可能な(分割された)コレクションです。
RDDのメソッドの2種類: 「Transformations」と「Actions」。 「Transformations」はRDDを操作し、結果を新しいRDDとして返します。「Actions」はRDDのデータを操作し、結果をRDD以外の形式で返すか保存を行います。
「Transformations」の代表的なメソッドは、mapやfilterです。 mapはRDD内のデータの一つ一つに対して記述した処理を行い、結果を返します。 filterは文字通りフィルタリングするメソッド unionはRDD同士を連結するものです。 flatMapでは各カラムを分割し、一つのカラムにしています。サンプルではunionした結果をスペースで分割し、一つのカラムにしています.
「Actions」の代表的なメソッドは、reduceやcountです。 reduceはRDD内の2つの要素に対して操作を行い、結果を返します。 countは文字通りRDDのデータの件数を返すメソッドです。
https://dev.classmethod.jp/etc/apache-spark_rdd_investigation/
<KEN_All_ROME.CSV>
"0600000","北海道","札幌市 中央区","以下に掲載がない場合","HOKKAIDO","SAPPORO SHI CHUO KU","IKANIKEISAIGANAIBAAI"
"0640941","北海道","札幌市 中央区","旭ケ丘","HOKKAIDO","SAPPORO SHI CHUO KU","ASAHIGAOKA"
"0600041","北海道","札幌市 中央区","大通東","HOKKAIDO","SAPPORO SHI CHUO KU","ODORIHIGASHI"
(以降略)
サンプルソースです。
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
object Startup{
def printRDD(filterName: String, rdd: org.apache.spark.rdd.RDD[_]) = {
println(filterName)
rdd.foreach {r => {
println(r)
}
}
}
def main(args: Array[String]) :Unit = {
val conf = new SparkConf().setAppName("RddSample").setMaster("local[*]")
val sc = new SparkContext(conf)
val inputRDD = sc.textFile("KEN_All_ROME.CSV")
//mapの例
val addresses = inputRDD.map{line =>
val splited = line.replace("\"", "").split(",")
var result: Array[String] = null
if (splited(6) == "IKANIKEISAIGANAIBAAI")
result = Array(splited(0), splited(4), splited(5))
else
result = Array(splited(0), splited(4), splited(5), splited(6))
result.mkString(" ")
}
printRDD("mappedRDD", addresses)
//filterとunionの例
val filtered1 = addresses.filter(line => line.contains("OSAKA")).filter(line => line.contains("AOBADAI"))
val filtered2 = addresses.filter(line => line.contains("KANAGAWA")).filter(line => line.contains("WAKABADAI"))
val unioned = filtered1.union(filtered2)
printRDD("filtered RDD 1", filtered1)
printRDD("filtered RDD 2", filtered2)
printRDD("unioned RDD", unioned)
//flatMapの例
val flatmapped = unioned.flatMap(line => line.split(" "))
printRDD("flatmapped", flatmapped)
//reduceの例
val reduced = flatmapped.reduce((x, y) => x + " " + y)
println("reduced")
println(reduced)
//countの例
val count = inputRDD.count
println("count")
println(count)
}
}