---
title: "Hadoop学习三十八：MapReduce job.setNumReduceTasks(0)思考"
author: "zy19982004"
date: "2014-05-19T11:01:16Z"
tags: []
categories: ["企业架构"]
slug: "hadoop-mapreduce-job-setnumreducetasks-0"
draft: false
lastmod: "2014-05-19T13:40:49Z"
id: 2068112
url: "https://zy19982004.iteye.com/blog/2068112"
---

**一.概述**

      在[http://zy19982004.iteye.com/blog/2037549](/blog/2037549)的最后曾经提到过，这里再详细探讨一下。

 

**二.job.setNumReduceTasks(0)唯一影响的是map结果的输出方式**

      当job.setNumReduceTasks(0)时，即没有reduce阶段，此时唯一影响的就是map结果的输出方式

1. 如果有reduce阶段，map的结果被flush到硬盘，作为reduce的输入；reduce的结果将被OutputFormat的RecordWriter写到指定的地方（setOutputPath），作为整个程序的输出。
2. 如果没有reduce阶段，map的结果将直接被OutputFormat的RecordWriter写到指定的地方（setOutputPath），作为整个程序的输出。

      而OutputFormat可以是普通的FileOutputFormat等，也可以是一个空的OutputFormat如NullOutputFormat。

      所以有无reduce和OutputFormat的多样性将组合出现以下情形（这个组合其实没什么意义，只是为了更加清楚而已）

1. 有reduce
   
   1. reduce的结果不需要输出到文件，如reduce里直接将结果插入HBase，此时可以采用NullOutputFormat，当然就不需要setOutputPath。
   2. reduce的结果需要输出到文件，如采用FileOutputFormat，需要setOutputPath。
2. 无reduce
   
   1. map的结果需要不输出到文件，如map里直接将结果插入HBase，此时可以采用NullOutputFormat，当然就不需要setOutputPath。
   2. map的结果需要输出到文件，如采用FileOutputFormat，需要setOutputPath。

      

**三.总结**

1. 有无reduce决定map结果的输出方式。有reduce时reduce的结果作为整个程序的输出；无reduce时，map的结果作为整个程序的输出。如果能在map阶段解决的问题尽量不要丢给直接输出的reduce如IdentityReducer。
2. 如NullOutputFormat层面上OutputFormat的不需要指定OutputPath；其他如FileOutputFormat需要指定，不然
   
   ```
   Exception in thread "main" org.apache.hadoop.mapred.InvalidJobConfException: Output directory not set.
   	at org.apache.hadoop.mapreduce.lib.output.FileOutputFormat.checkOutputSpecs(FileOutputFormat.java:138)
   ```