You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hive.apache.org by ha...@apache.org on 2013/07/18 11:16:53 UTC

svn commit: r1504395 [1/15] - in /hive/trunk: common/src/java/org/apache/hadoop/hive/conf/ conf/ ql/if/ ql/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/ql/plan/api/ ql/src/java/org/apache/hadoop/hive/ql/exec/ ql/src/java/org/apache/hadoop/hive/ql...

Author: hashutosh
Date: Thu Jul 18 09:16:52 2013
New Revision: 1504395

URL: http://svn.apache.org/r1504395
Log:
HIVE-2206 [jira] add a new optimizer for query correlation discovery and optimization
(Yin Huai via Ashutosh Chauhan)

Summary:
update test results

This issue proposes a new logical optimizer called Correlation Optimizer, which is used to merge correlated MapReduce jobs (MR jobs) into a single MR job. The idea is based on YSmart (http://ysmart.cse.ohio-state.edu/). The paper and slides of YSmart are linked at the bottom.

Since Hive translates queries in a sentence by sentence fashion, for every operation which may need to shuffle the data (e.g. join and aggregation operations), Hive will generate a MapReduce job for that operation. However, for those operations which may need to shuffle the data, they may involve correlations explained below and thus can be executed in a single MR job.

	Input Correlation: Multiple MR jobs have input correlation (IC) if their input relation sets are not disjoint;
	Transit Correlation: Multiple MR jobs have transit correlation (TC) if they have not only input correlation, but also the same partition key;
	Job Flow Correlation: An MR has job flow correlation (JFC) with one of its child nodes if it has the same partition key as that child node.

The current implementation of correlation optimizer only detect correlations among MR jobs for reduce-side join operators and reduce-side aggregation operators (not map only aggregation). A query will be optimized if it satisfies following conditions.

	There exists a MR job for reduce-side join operator or reduce side aggregation operator which have JFC with all of its parents MR jobs (TCs will be also exploited if JFC exists);
	All input tables of those correlated MR job are original input tables (not intermediate tables generated by sub-queries); and
	No self join is involved in those correlated MR jobs.

Correlation optimizer is implemented as a logical optimizer. The main reasons are that it only needs to manipulate the query plan tree and it can leverage the existing component on generating MR jobs.

Current implementation can serve as a framework for correlation related optimizations. I think that it is better than adding individual optimizers.

There are several work that can be done in future to improve this optimizer. Here are three examples.

	Support queries only involve TC;
	Support queries in which input tables of correlated MR jobs involves intermediate tables; and
	Optimize queries involving self join.

References:
Paper and presentation of YSmart.
Paper: http://www.cse.ohio-state.edu/hpcs/WWW/HTML/publications/papers/TR-11-7.pdf
Slides: http://sdrv.ms/UpwJJc

Test Plan: EMPTY

Reviewers: JIRA, ashutoshc

Reviewed By: ashutoshc

CC: brock

Differential Revision: https://reviews.facebook.net/D11097

Added:
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/DemuxOperator.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/MuxOperator.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/correlation/
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/correlation/AbstractCorrelationProcCtx.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/correlation/CorrelationOptimizer.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/correlation/CorrelationUtilities.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/correlation/IntraQueryCorrelation.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/correlation/QueryPlanTreeTransformation.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/correlation/ReduceSinkDeDuplication.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/plan/DemuxDesc.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/plan/MuxDesc.java
    hive/trunk/ql/src/test/queries/clientpositive/correlationoptimizer1.q
    hive/trunk/ql/src/test/queries/clientpositive/correlationoptimizer10.q
    hive/trunk/ql/src/test/queries/clientpositive/correlationoptimizer11.q
    hive/trunk/ql/src/test/queries/clientpositive/correlationoptimizer12.q
    hive/trunk/ql/src/test/queries/clientpositive/correlationoptimizer13.q
    hive/trunk/ql/src/test/queries/clientpositive/correlationoptimizer14.q
    hive/trunk/ql/src/test/queries/clientpositive/correlationoptimizer2.q
    hive/trunk/ql/src/test/queries/clientpositive/correlationoptimizer3.q
    hive/trunk/ql/src/test/queries/clientpositive/correlationoptimizer4.q
    hive/trunk/ql/src/test/queries/clientpositive/correlationoptimizer5.q
    hive/trunk/ql/src/test/queries/clientpositive/correlationoptimizer6.q
    hive/trunk/ql/src/test/queries/clientpositive/correlationoptimizer7.q
    hive/trunk/ql/src/test/queries/clientpositive/correlationoptimizer8.q
    hive/trunk/ql/src/test/queries/clientpositive/correlationoptimizer9.q
    hive/trunk/ql/src/test/results/clientpositive/correlationoptimizer1.q.out
    hive/trunk/ql/src/test/results/clientpositive/correlationoptimizer10.q.out
    hive/trunk/ql/src/test/results/clientpositive/correlationoptimizer11.q.out
    hive/trunk/ql/src/test/results/clientpositive/correlationoptimizer12.q.out
    hive/trunk/ql/src/test/results/clientpositive/correlationoptimizer13.q.out
    hive/trunk/ql/src/test/results/clientpositive/correlationoptimizer14.q.out
    hive/trunk/ql/src/test/results/clientpositive/correlationoptimizer2.q.out
    hive/trunk/ql/src/test/results/clientpositive/correlationoptimizer3.q.out
    hive/trunk/ql/src/test/results/clientpositive/correlationoptimizer4.q.out
    hive/trunk/ql/src/test/results/clientpositive/correlationoptimizer5.q.out
    hive/trunk/ql/src/test/results/clientpositive/correlationoptimizer6.q.out
    hive/trunk/ql/src/test/results/clientpositive/correlationoptimizer7.q.out
    hive/trunk/ql/src/test/results/clientpositive/correlationoptimizer8.q.out
    hive/trunk/ql/src/test/results/clientpositive/correlationoptimizer9.q.out
Removed:
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/ReduceSinkDeDuplication.java
Modified:
    hive/trunk/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java
    hive/trunk/conf/hive-default.xml.template
    hive/trunk/ql/if/queryplan.thrift
    hive/trunk/ql/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/ql/plan/api/OperatorType.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/CommonJoinOperator.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/GroupByOperator.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Operator.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/OperatorFactory.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/mr/ExecReducer.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/GenMRUnion1.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/GenMapRedUtils.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/Optimizer.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/physical/CommonJoinTaskDispatcher.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/SemanticAnalyzer.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/plan/ReduceSinkDesc.java
    hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/plan/UnionDesc.java
    hive/trunk/ql/src/test/results/compiler/plan/groupby2.q.xml
    hive/trunk/ql/src/test/results/compiler/plan/groupby3.q.xml

Modified: hive/trunk/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java
URL: http://svn.apache.org/viewvc/hive/trunk/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java?rev=1504395&r1=1504394&r2=1504395&view=diff
==============================================================================
--- hive/trunk/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java (original)
+++ hive/trunk/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java Thu Jul 18 09:16:52 2013
@@ -569,6 +569,7 @@ public class HiveConf extends Configurat
     // It creates sub-directories in the final output, so should not be turned on in systems
     // where MAPREDUCE-1501 is not present
     HIVE_OPTIMIZE_UNION_REMOVE("hive.optimize.union.remove", false),
+    HIVEOPTCORRELATION("hive.optimize.correlation", false), // exploit intra-query correlations
 
     // whether hadoop map-reduce supports sub-directories. It was added by MAPREDUCE-1501.
     // Some optimizations can only be performed if the version of hadoop being used supports

Modified: hive/trunk/conf/hive-default.xml.template
URL: http://svn.apache.org/viewvc/hive/trunk/conf/hive-default.xml.template?rev=1504395&r1=1504394&r2=1504395&view=diff
==============================================================================
--- hive/trunk/conf/hive-default.xml.template (original)
+++ hive/trunk/conf/hive-default.xml.template Thu Jul 18 09:16:52 2013
@@ -1121,6 +1121,12 @@
 </property>
 
 <property>
+  <name>hive.optimize.correlation</name>
+  <value>false</value>
+  <description>exploit intra-query correlations.</description>
+</property>
+
+<property>
   <name>hive.optimize.reducededuplication.min.reducer</name>
   <value>4</value>
   <description>Reduce deduplication merges two RSs by moving key/parts/reducer-num of the child RS to parent RS.

Modified: hive/trunk/ql/if/queryplan.thrift
URL: http://svn.apache.org/viewvc/hive/trunk/ql/if/queryplan.thrift?rev=1504395&r1=1504394&r2=1504395&view=diff
==============================================================================
--- hive/trunk/ql/if/queryplan.thrift (original)
+++ hive/trunk/ql/if/queryplan.thrift Thu Jul 18 09:16:52 2013
@@ -54,6 +54,8 @@ enum OperatorType {
   HASHTABLESINK,
   HASHTABLEDUMMY,
   PTF,
+  MUX,
+  DEMUX,
 }
 
 struct Operator {

Modified: hive/trunk/ql/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/ql/plan/api/OperatorType.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/ql/plan/api/OperatorType.java?rev=1504395&r1=1504394&r2=1504395&view=diff
==============================================================================
--- hive/trunk/ql/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/ql/plan/api/OperatorType.java (original)
+++ hive/trunk/ql/src/gen/thrift/gen-javabean/org/apache/hadoop/hive/ql/plan/api/OperatorType.java Thu Jul 18 09:16:52 2013
@@ -30,7 +30,9 @@ public enum OperatorType implements org.
   LATERALVIEWFORWARD(15),
   HASHTABLESINK(16),
   HASHTABLEDUMMY(17),
-  PTF(18);
+  PTF(18),
+  MUX(19),
+  DEMUX(20);
 
   private final int value;
 
@@ -49,7 +51,7 @@ public enum OperatorType implements org.
    * Find a the enum type by its integer value, as defined in the Thrift IDL.
    * @return null if the value is not found.
    */
-  public static OperatorType findByValue(int value) { 
+  public static OperatorType findByValue(int value) {
     switch (value) {
       case 0:
         return JOIN;
@@ -89,6 +91,10 @@ public enum OperatorType implements org.
         return HASHTABLEDUMMY;
       case 18:
         return PTF;
+      case 19:
+        return MUX;
+      case 20:
+        return DEMUX;
       default:
         return null;
     }

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/CommonJoinOperator.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/CommonJoinOperator.java?rev=1504395&r1=1504394&r2=1504395&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/CommonJoinOperator.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/CommonJoinOperator.java Thu Jul 18 09:16:52 2013
@@ -331,6 +331,7 @@ public abstract class CommonJoinOperator
     for (AbstractRowContainer<ArrayList<Object>> alw : storage) {
       alw.clear();
     }
+    super.startGroup();
   }
 
   protected int getNextSize(int sz) {

Added: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/DemuxOperator.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/DemuxOperator.java?rev=1504395&view=auto
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/DemuxOperator.java (added)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/DemuxOperator.java Thu Jul 18 09:16:52 2013
@@ -0,0 +1,392 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql.exec;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.ql.metadata.HiveException;
+import org.apache.hadoop.hive.ql.plan.DemuxDesc;
+import org.apache.hadoop.hive.ql.plan.OperatorDesc;
+import org.apache.hadoop.hive.ql.plan.TableDesc;
+import org.apache.hadoop.hive.ql.plan.api.OperatorType;
+import org.apache.hadoop.hive.serde2.Deserializer;
+import org.apache.hadoop.hive.serde2.SerDe;
+import org.apache.hadoop.hive.serde2.io.ByteWritable;
+import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
+import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
+import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
+import org.apache.hadoop.util.ReflectionUtils;
+
+/**
+ * DemuxOperator is an operator used by MapReduce Jobs optimized by
+ * CorrelationOptimizer. If used, DemuxOperator is the first operator in reduce
+ * phase. In the case that multiple operation paths are merged into a single one, it will dispatch
+ * the record to corresponding child operators (Join or GBY).
+ */
+public class DemuxOperator extends Operator<DemuxDesc>
+  implements Serializable {
+
+  private static final long serialVersionUID = 1L;
+  protected static final Log LOG = LogFactory.getLog(DemuxOperator.class.getName());
+
+  /**
+   * Handler is used to assign original tag (oldTag) to a row and
+   * track how many rows are forwarded to every child of DemuxOperator.
+   */
+  protected static class Handler {
+    // oldTag is the tag assigned to ReduceSinkOperators BEFORE Correlation Optimizer
+    // optimizes the operator tree. newTag is the tag assigned to ReduceSinkOperators
+    // AFTER Correlation Optimizer optimizes the operator tree.
+    // Example: we have an operator tree shown below ...
+    //        JOIN2
+    //       /     \
+    //   GBY1       JOIN1
+    //    |         /    \
+    //   RS1       RS2   RS3
+    // If GBY1, JOIN1, and JOIN2 are executed in the same Reducer
+    // (optimized by Correlation Optimizer), we will have ...
+    // oldTag: RS1:0, RS2:0, RS3:1
+    // newTag: RS1:0, RS2:1, RS3:2
+    // We need to know the mapping from the newTag to oldTag and revert
+    // the newTag to oldTag to make operators in the operator tree
+    // function correctly.
+    private final byte newTag;
+    private final byte oldTag;
+    private final byte childIndex;
+    private final ByteWritable oldTagByteWritable;
+    private final List<Object> forwardedRow;
+
+    // counters for debugging
+    private transient long cntr = 0;
+    private transient long nextCntr = 1;
+
+    private long getNextCntr(long cntr) {
+      // A very simple counter to keep track of number of rows processed by an
+      // operator. It dumps
+      // every 1 million times, and quickly before that
+      if (cntr >= 1000000) {
+        return cntr + 1000000;
+      }
+      return 10 * cntr;
+    }
+
+    public long getCntr() {
+      return this.cntr;
+    }
+
+    private final Log log;
+    private final boolean isLogInfoEnabled;
+    private final String id;
+
+    public Handler(byte newTag, byte childIndex, byte oldTag, Log LOG, String id)
+            throws HiveException {
+      this.newTag = newTag;
+      this.oldTag = oldTag;
+      this.childIndex = childIndex;
+      this.oldTagByteWritable = new ByteWritable(oldTag);
+      this.log = LOG;
+      this.isLogInfoEnabled = LOG.isInfoEnabled();
+      this.id = id;
+      this.forwardedRow = new ArrayList<Object>(3);
+    }
+
+    public byte getOldTag() {
+      return oldTag;
+    }
+
+    public Object process(Object row) throws HiveException {
+      forwardedRow.clear();
+      List<Object> thisRow = (List<Object>) row;
+      forwardedRow.add(thisRow.get(0));
+      forwardedRow.add(thisRow.get(1));
+      forwardedRow.add(oldTagByteWritable);
+
+      if (isLogInfoEnabled) {
+        cntr++;
+        if (cntr == nextCntr) {
+          log.info(id + " (newTag, childIndex, oldTag)=(" + newTag + ", " + childIndex + ", "
+              + oldTag + "), forwarding " + cntr + " rows");
+          nextCntr = getNextCntr(cntr);
+        }
+      }
+
+      return forwardedRow;
+    }
+
+    public void printCloseOpLog() {
+      log.info(id + " (newTag, childIndex, oldTag)=(" + newTag + ", " + childIndex + ", "
+          + oldTag + "),  forwarded " + cntr + " rows");
+    }
+  }
+
+  // The mapping from a newTag to its corresponding oldTag. Please see comments in
+  // DemuxOperator.Handler for explanations of newTag and oldTag.
+  private Map<Integer, Integer> newTagToOldTag =
+      new HashMap<Integer, Integer>();
+
+  // The mapping from a newTag to the index of the corresponding child
+  // of this operator.
+  private Map<Integer, Integer> newTagToChildIndex =
+      new HashMap<Integer, Integer>();
+
+  // The mapping from a newTag to its corresponding handler
+  private Map<Integer, Handler> newTagToDispatchHandler =
+      new HashMap<Integer, Handler>();
+
+  // The mapping from the index of a child operator to its corresponding
+  // inputObjectInspectors
+  private Map<Integer, ObjectInspector[]> childInputObjInspectors;
+
+  private int childrenDone;
+
+  // Since DemuxOperator may appear multiple times in MuxOperator's parents list.
+  // We use newChildIndexTag instead of childOperatorsTag.
+  // Example:
+  //         JOIN
+  //           |
+  //          MUX
+  //         / | \
+  //        /  |  \
+  //       /   |   \
+  //       |  GBY  |
+  //       \   |   /
+  //        \  |  /
+  //         DEMUX
+  // In this case, the parent list of MUX is [DEMUX, GBY, DEMUX],
+  // so we need to have two childOperatorsTags (the index of this DemuxOperator in
+  // its children's parents lists, also see childOperatorsTag in Operator) at here.
+  private List<List<Integer>> newChildOperatorsTag;
+
+  @Override
+  protected void initializeOp(Configuration hconf) throws HiveException {
+    this.newTagToOldTag = conf.getNewTagToOldTag();
+    this.newTagToChildIndex = conf.getNewTagToChildIndex();
+    this.newTagToDispatchHandler = new HashMap<Integer, Handler>();
+    this.childInputObjInspectors = new HashMap<Integer, ObjectInspector[]>();
+
+    // For every newTag (every newTag corresponds to a ReduceSinkOperator),
+    // create a handler. Also, we initialize childInputObjInspectors at here.
+    for (Entry<Integer, Integer> entry: newTagToOldTag.entrySet()) {
+      int newTag = entry.getKey();
+      int oldTag = entry.getValue();
+      int childIndex = newTagToChildIndex.get(newTag);
+      Handler handler =
+          new Handler((byte)newTag, (byte)childIndex, (byte)oldTag, LOG, id);
+      newTagToDispatchHandler.put(newTag, handler);
+      int childParentsCount = conf.getChildIndexToOriginalNumParents().get(childIndex);
+      childInputObjInspectors.put(childIndex, new ObjectInspector[childParentsCount]);
+    }
+
+    try {
+      // We populate inputInspectors for all children of this DemuxOperator.
+      // Those inputObjectInspectors are stored in childInputObjInspectors.
+      for (Entry<Integer, Integer> e1: newTagToOldTag.entrySet()) {
+        int newTag = e1.getKey();
+        int oldTag = e1.getValue();
+        int childIndex = newTagToChildIndex.get(newTag);
+        TableDesc keyTableDesc = conf.getKeysSerializeInfos().get(newTag);
+        Deserializer inputKeyDeserializer = (SerDe) ReflectionUtils.newInstance(keyTableDesc
+            .getDeserializerClass(), null);
+        inputKeyDeserializer.initialize(null, keyTableDesc.getProperties());
+
+        TableDesc valueTableDesc = conf.getValuesSerializeInfos().get(newTag);
+        Deserializer inputValueDeserializer = (SerDe) ReflectionUtils.newInstance(valueTableDesc
+            .getDeserializerClass(), null);
+        inputValueDeserializer.initialize(null, valueTableDesc.getProperties());
+
+        List<ObjectInspector> oi = new ArrayList<ObjectInspector>();
+        oi.add(inputKeyDeserializer.getObjectInspector());
+        oi.add(inputValueDeserializer.getObjectInspector());
+        oi.add(PrimitiveObjectInspectorFactory.writableByteObjectInspector);
+        ObjectInspector[] ois = childInputObjInspectors.get(childIndex);
+        ois[oldTag] = ObjectInspectorFactory
+            .getStandardStructObjectInspector(Utilities.fieldNameList, oi);
+      }
+    } catch (Exception e) {
+      throw new RuntimeException(e);
+    }
+    this.childrenDone = 0;
+    newChildOperatorsTag = new ArrayList<List<Integer>>();
+    for (Operator<? extends OperatorDesc> child: childOperators) {
+      List<Integer> childOperatorTags = new ArrayList<Integer>();
+      if (child instanceof MuxOperator) {
+        // This DemuxOperator can appear multiple times in MuxOperator's
+        // parentOperators
+        int index = 0;
+        for (Operator<? extends OperatorDesc> parent: child.getParentOperators()) {
+          if (this == parent) {
+            childOperatorTags.add(index);
+          }
+          index++;
+        }
+      } else {
+        childOperatorTags.add(child.getParentOperators().indexOf(this));
+      }
+      newChildOperatorsTag.add(childOperatorTags);
+    }
+    LOG.info("newChildOperatorsTag " + newChildOperatorsTag);
+    initializeChildren(hconf);
+  }
+
+  // Each child should has its own outputObjInspector
+  @Override
+  protected void initializeChildren(Configuration hconf) throws HiveException {
+    state = State.INIT;
+    LOG.info("Operator " + id + " " + getName() + " initialized");
+    if (childOperators == null) {
+      return;
+    }
+    LOG.info("Initializing children of " + id + " " + getName());
+    for (int i = 0; i < childOperatorsArray.length; i++) {
+      LOG.info("Initializing child " + i + " " + childOperatorsArray[i].getIdentifier() + " " +
+          childOperatorsArray[i].getName() +
+          " " + childInputObjInspectors.get(i).length);
+      // We need to initialize those MuxOperators first because if we first
+      // initialize other operators, the states of all parents of those MuxOperators
+      // are INIT (including this DemuxOperator),
+      // but the inputInspector of those MuxOperators has not been set.
+      if (childOperatorsArray[i] instanceof MuxOperator) {
+        // If this DemuxOperator directly connects to a MuxOperator,
+        // that MuxOperator must be the parent of a JoinOperator.
+        // In this case, that MuxOperator should be initialized
+        // by multiple parents (of that MuxOperator).
+        ObjectInspector[] ois = childInputObjInspectors.get(i);
+        for (int j = 0; j < ois.length; j++) {
+          if (ois[j] != null) {
+            childOperatorsArray[i].initialize(hconf, ois[j], j);
+          }
+        }
+      } else {
+        continue;
+      }
+      if (reporter != null) {
+        childOperatorsArray[i].setReporter(reporter);
+      }
+    }
+    for (int i = 0; i < childOperatorsArray.length; i++) {
+      LOG.info("Initializing child " + i + " " + childOperatorsArray[i].getIdentifier() + " " +
+          childOperatorsArray[i].getName() +
+          " " + childInputObjInspectors.get(i).length);
+      if (!(childOperatorsArray[i] instanceof MuxOperator)) {
+        childOperatorsArray[i].initialize(hconf, childInputObjInspectors.get(i));
+      } else {
+        continue;
+      }
+      if (reporter != null) {
+        childOperatorsArray[i].setReporter(reporter);
+      }
+    }
+  }
+
+  @Override
+  public void processOp(Object row, int tag) throws HiveException {
+    int newTag = tag;
+    forward(row, inputObjInspectors[newTag]);
+  }
+
+  @Override
+  public void forward(Object row, ObjectInspector rowInspector)
+      throws HiveException {
+    if ((++outputRows % 1000) == 0) {
+      if (counterNameToEnum != null) {
+        incrCounter(numOutputRowsCntr, outputRows);
+        outputRows = 0;
+      }
+    }
+
+    if (childOperatorsArray == null && childOperators != null) {
+      throw new HiveException("Internal Hive error during operator initialization.");
+    }
+
+    if ((childOperatorsArray == null) || (getDone())) {
+      return;
+    }
+
+    List<Object> thisRow = (List<Object>) row;
+    assert thisRow.size() == 3;
+    int newTag = ((ByteWritable) thisRow.get(2)).get();
+    Handler handler = newTagToDispatchHandler.get(newTag);
+    int childIndex = newTagToChildIndex.get(newTag);
+    Operator<? extends OperatorDesc> o = childOperatorsArray[childIndex];
+    if (o.getDone()) {
+      childrenDone++;
+    } else {
+      o.process(handler.process(row), handler.getOldTag());
+    }
+
+    // if all children are done, this operator is also done
+    if (childrenDone == childOperatorsArray.length) {
+      setDone(true);
+    }
+
+  }
+
+  @Override
+  protected void closeOp(boolean abort) throws HiveException {
+    // log the number of rows forwarded from each dispatcherHandler
+    for (Handler handler: newTagToDispatchHandler.values()) {
+      handler.printCloseOpLog();
+    }
+  }
+
+  @Override
+  public void endGroup() throws HiveException {
+    if (childOperators == null) {
+      return;
+    }
+
+    if (fatalError) {
+      return;
+    }
+
+    for (int i = 0; i < childOperatorsArray.length; i++) {
+      Operator<? extends OperatorDesc> child = childOperatorsArray[i];
+      child.flush();
+      child.endGroup();
+      for (Integer childTag: newChildOperatorsTag.get(i)) {
+        child.processGroup(childTag);
+      }
+    }
+  }
+
+  /**
+   * @return the name of the operator
+   */
+  @Override
+  public String getName() {
+    return getOperatorName();
+  }
+
+  static public String getOperatorName() {
+    return "DEMUX";
+  }
+
+  @Override
+  public OperatorType getType() {
+    return OperatorType.DEMUX;
+  }
+}

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/GroupByOperator.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/GroupByOperator.java?rev=1504395&r1=1504394&r2=1504395&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/GroupByOperator.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/GroupByOperator.java Thu Jul 18 09:16:52 2013
@@ -707,6 +707,7 @@ public class GroupByOperator extends Ope
   @Override
   public void startGroup() throws HiveException {
     firstRowInGroup = true;
+    super.startGroup();
   }
 
   @Override
@@ -750,7 +751,7 @@ public class GroupByOperator extends Ope
               + " #total = " + numRowsInput + " reduction = " + 1.0
               * (numRowsHashTbl / numRowsInput) + " minReduction = "
               + minReductionHashAggr);
-          flush(true);
+          flushHashTable(true);
           hashAggr = false;
         } else {
           LOG.trace("Hash Aggr Enabled: #hash table = " + numRowsHashTbl
@@ -835,7 +836,7 @@ public class GroupByOperator extends Ope
     // happen at boundaries
     if ((!groupKeyIsNotReduceKey || firstRowInGroup)
         && shouldBeFlushed(newKeys)) {
-      flush(false);
+      flushHashTable(false);
     }
   }
 
@@ -983,7 +984,12 @@ public class GroupByOperator extends Ope
     return length;
   }
 
-  private void flush(boolean complete) throws HiveException {
+  /**
+   * Flush hash table. This method is used by hash-based aggregations
+   * @param complete
+   * @throws HiveException
+   */
+  private void flushHashTable(boolean complete) throws HiveException {
 
     countAfterReport = 0;
 
@@ -1048,6 +1054,42 @@ public class GroupByOperator extends Ope
   }
 
   /**
+   * Forward all aggregations to children. It is only used by DemuxOperator.
+   * @throws HiveException
+   */
+  @Override
+  public void flush() throws HiveException{
+    try {
+      if (hashAggregations != null) {
+        LOG.info("Begin Hash Table flush: size = "
+            + hashAggregations.size());
+        Iterator iter = hashAggregations.entrySet().iterator();
+        while (iter.hasNext()) {
+          Map.Entry<KeyWrapper, AggregationBuffer[]> m = (Map.Entry) iter
+              .next();
+
+          forward(m.getKey().getKeyArray(), m.getValue());
+          iter.remove();
+        }
+        hashAggregations.clear();
+      } else if (aggregations != null) {
+        // sort-based aggregations
+        if (currentKeys != null) {
+          forward(currentKeys.getKeyArray(), aggregations);
+        }
+        currentKeys = null;
+      } else {
+        // The GroupByOperator is not initialized, which means there is no
+        // data
+        // (since we initialize the operators when we see the first record).
+        // Just do nothing here.
+      }
+    } catch (Exception e) {
+      throw new HiveException(e);
+    }
+  }
+
+  /**
    * We need to forward all the aggregations to children.
    *
    */
@@ -1088,33 +1130,9 @@ public class GroupByOperator extends Ope
           // create dummy keys - size 0
           forward(new Object[0], aggregations);
         } else {
-          if (hashAggregations != null) {
-            LOG.info("Begin Hash Table flush at close: size = "
-                + hashAggregations.size());
-            Iterator iter = hashAggregations.entrySet().iterator();
-            while (iter.hasNext()) {
-              Map.Entry<KeyWrapper, AggregationBuffer[]> m = (Map.Entry) iter
-                  .next();
-
-              forward(m.getKey().getKeyArray(), m.getValue());
-              iter.remove();
-            }
-            hashAggregations.clear();
-          } else if (aggregations != null) {
-            // sort-based aggregations
-            if (currentKeys != null) {
-              forward(currentKeys.getKeyArray(), aggregations);
-            }
-            currentKeys = null;
-          } else {
-            // The GroupByOperator is not initialized, which means there is no
-            // data
-            // (since we initialize the operators when we see the first record).
-            // Just do nothing here.
-          }
+          flush();
         }
       } catch (Exception e) {
-        e.printStackTrace();
         throw new HiveException(e);
       }
     }

Added: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/MuxOperator.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/MuxOperator.java?rev=1504395&view=auto
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/MuxOperator.java (added)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/MuxOperator.java Thu Jul 18 09:16:52 2013
@@ -0,0 +1,343 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql.exec;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.ql.metadata.HiveException;
+import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
+import org.apache.hadoop.hive.ql.plan.MuxDesc;
+import org.apache.hadoop.hive.ql.plan.OperatorDesc;
+import org.apache.hadoop.hive.ql.plan.api.OperatorType;
+import org.apache.hadoop.hive.serde2.io.ByteWritable;
+import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
+import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
+import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
+
+/**
+ * MuxOperator is used in the Reduce side of MapReduce jobs optimized by Correlation Optimizer.
+ * Correlation Optimizer will remove unnecessary ReduceSinkOperaotrs,
+ * and MuxOperators are used to replace those ReduceSinkOperaotrs.
+ * Example: The original operator tree is ...
+ *      JOIN2
+ *      /    \
+ *     RS4   RS5
+ *    /        \
+ *   GBY1     JOIN1
+ *    |       /    \
+ *   RS1     RS2   RS3
+ * If GBY1, JOIN1, and JOIN2 can be executed in the same reducer
+ * (optimized by Correlation Optimizer).
+ * The new operator tree will be ...
+ *      JOIN2
+ *        |
+ *       MUX
+ *      /   \
+ *    GBY1  JOIN1
+ *      \    /
+ *       DEMUX
+ *      /  |  \
+ *     /   |   \
+ *    /    |    \
+ *   RS1   RS2   RS3
+ *
+ * A MuxOperator has two functions.
+ * First, it will construct key, value and tag structure for
+ * the input of Join Operators.
+ * Second, it is a part of operator coordination mechanism which makes sure the operator tree
+ * in the Reducer can work correctly.
+ */
+public class MuxOperator extends Operator<MuxDesc> implements Serializable{
+
+  private static final long serialVersionUID = 1L;
+  protected static final Log LOG = LogFactory.getLog(MuxOperator.class.getName());
+
+  /**
+   * Handler is used to construct key-value-tag structure and assign original tag to a row.
+   */
+  protected static class Handler {
+    private final ObjectInspector outputObjInspector;
+    private final int tag;
+    private final ByteWritable tagByteWritable;
+    /**
+     * The evaluators for the key columns. Key columns decide the sort order on
+     * the reducer side. Key columns are passed to the reducer in the "key".
+     */
+    private final ExprNodeEvaluator[] keyEval;
+    /**
+     * The evaluators for the value columns. Value columns are passed to reducer
+     * in the "value".
+     */
+    private final ExprNodeEvaluator[] valueEval;
+    private final Object[] outputKey;
+    private final Object[] outputValue;
+    private final List<Object> forwardedRow;
+
+    public Handler(ObjectInspector inputObjInspector,
+        List<ExprNodeDesc> keyCols,
+        List<ExprNodeDesc> valueCols,
+        List<String> outputKeyColumnNames,
+        List<String> outputValueColumnNames,
+        Integer tag) throws HiveException {
+
+      keyEval = new ExprNodeEvaluator[keyCols.size()];
+      int i = 0;
+      for (ExprNodeDesc e: keyCols) {
+        keyEval[i++] = ExprNodeEvaluatorFactory.get(e);
+      }
+      outputKey = new Object[keyEval.length];
+
+      valueEval = new ExprNodeEvaluator[valueCols.size()];
+      i = 0;
+      for (ExprNodeDesc e: valueCols) {
+        valueEval[i++] = ExprNodeEvaluatorFactory.get(e);
+      }
+      outputValue = new Object[valueEval.length];
+
+      this.tag = tag;
+      this.tagByteWritable = new ByteWritable((byte)tag.intValue());
+
+      ObjectInspector keyObjectInspector = initEvaluatorsAndReturnStruct(keyEval,
+          outputKeyColumnNames, inputObjInspector);
+      ObjectInspector valueObjectInspector = initEvaluatorsAndReturnStruct(valueEval,
+          outputValueColumnNames, inputObjInspector);
+      List<ObjectInspector> ois = new ArrayList<ObjectInspector>();
+      ois.add(keyObjectInspector);
+      ois.add(valueObjectInspector);
+      ois.add(PrimitiveObjectInspectorFactory.writableByteObjectInspector);
+      this.outputObjInspector = ObjectInspectorFactory.getStandardStructObjectInspector(
+              Utilities.fieldNameList, ois);
+      this.forwardedRow = new ArrayList<Object>(3);
+    }
+
+    public ObjectInspector getOutputObjInspector() {
+      return outputObjInspector;
+    }
+
+    public int getTag() {
+      return tag;
+    }
+
+    public Object process(Object row) throws HiveException {
+      // Evaluate the keys
+      for (int i = 0; i < keyEval.length; i++) {
+        outputKey[i] = keyEval[i].evaluate(row);
+      }
+      // Evaluate the value
+      for (int i = 0; i < valueEval.length; i++) {
+        outputValue[i] = valueEval[i].evaluate(row);
+      }
+      forwardedRow.clear();
+      // JoinOperator assumes the key is backed by an list.
+      // To be consistent, the value array is also converted
+      // to a list.
+      forwardedRow.add(Arrays.asList(outputKey));
+      forwardedRow.add(Arrays.asList(outputValue));
+      forwardedRow.add(tagByteWritable);
+      return forwardedRow;
+    }
+  }
+
+  private transient ObjectInspector[] outputObjectInspectors;
+  private transient int numParents;
+  private transient boolean[] forward;
+  private transient boolean[] processGroupCalled;
+  private Handler[] handlers;
+
+  //counters for debugging
+  private transient long[] cntr;
+  private transient long[] nextCntr;
+
+  private long getNextCntr(long cntr) {
+    // A very simple counter to keep track of number of rows processed by an
+    // operator. It dumps
+    // every 1 million times, and quickly before that
+    if (cntr >= 1000000) {
+      return cntr + 1000000;
+    }
+    return 10 * cntr;
+  }
+
+  @Override
+  protected void initializeOp(Configuration hconf) throws HiveException {
+    // A MuxOperator should only has a single child
+    if (childOperatorsArray.length != 1) {
+      throw new HiveException(
+          "Expected number of children is 1. Found : " + childOperatorsArray.length);
+    }
+    numParents = getNumParent();
+    forward = new boolean[numParents];
+    processGroupCalled = new boolean[numParents];
+    outputObjectInspectors = new ObjectInspector[numParents];
+    handlers = new Handler[numParents];
+    cntr = new long[numParents];
+    nextCntr = new long[numParents];
+    for (int i = 0; i < numParents; i++) {
+      processGroupCalled[i] = false;
+      if (conf.getParentToKeyCols().get(i) == null) {
+        // We do not need to evaluate the input row for this parent.
+        // So, we can just forward it to the child of this MuxOperator.
+        handlers[i] = null;
+        forward[i] = true;
+        outputObjectInspectors[i] = inputObjInspectors[i];
+      } else {
+        handlers[i] = new Handler(
+            inputObjInspectors[i],
+            conf.getParentToKeyCols().get(i),
+            conf.getParentToValueCols().get(i),
+            conf.getParentToOutputKeyColumnNames().get(i),
+            conf.getParentToOutputValueColumnNames().get(i),
+            conf.getParentToTag().get(i));
+        forward[i] = false;
+        outputObjectInspectors[i] = handlers[i].getOutputObjInspector();
+      }
+      cntr[i] = 0;
+      nextCntr[i] = 1;
+    }
+    initializeChildren(hconf);
+  }
+
+  /**
+   * Calls initialize on each of the children with outputObjetInspector as the
+   * output row format.
+   */
+  @Override
+  protected void initializeChildren(Configuration hconf) throws HiveException {
+    state = State.INIT;
+    LOG.info("Operator " + id + " " + getName() + " initialized");
+    if (childOperators == null) {
+      return;
+    }
+    LOG.info("Initializing children of " + id + " " + getName());
+    childOperatorsArray[0].initialize(hconf, outputObjectInspectors);
+    if (reporter != null) {
+      childOperatorsArray[0].setReporter(reporter);
+    }
+  }
+
+  @Override
+  public void processOp(Object row, int tag) throws HiveException {
+    forward(row, tag);
+  }
+
+  protected void forward(Object row, int tag)
+      throws HiveException {
+
+    if (childOperatorsArray == null && childOperators != null) {
+      throw new HiveException(
+          "Internal Hive error during operator initialization.");
+    }
+
+    if ((childOperatorsArray == null) || (getDone())) {
+      return;
+    }
+
+    int childrenDone = 0;
+    for (int i = 0; i < childOperatorsArray.length; i++) {
+      Operator<? extends OperatorDesc> o = childOperatorsArray[i];
+      if (o.getDone()) {
+        childrenDone++;
+      } else {
+        if (forward[tag]) {
+          // No need to evaluate, just forward it.
+          o.process(row, tag);
+        } else {
+          // Call the corresponding handler to evaluate this row and
+          // forward the result
+          o.process(handlers[tag].process(row), handlers[tag].getTag());
+        }
+      }
+    }
+
+    if (isLogInfoEnabled) {
+      cntr[tag]++;
+      if (cntr[tag] == nextCntr[tag]) {
+        LOG.info(id + ", tag=" + tag + ", forwarding " + cntr[tag] + " rows");
+        nextCntr[tag] = getNextCntr(cntr[tag]);
+      }
+    }
+
+    // if all children are done, this operator is also done
+    if (childrenDone == childOperatorsArray.length) {
+      setDone(true);
+    }
+  }
+
+  @Override
+  public void startGroup() throws HiveException{
+    for (int i = 0; i < numParents; i++) {
+      processGroupCalled[i] = false;
+    }
+    super.startGroup();
+  }
+
+  @Override
+  public void endGroup() throws HiveException {
+    // do nothing
+  }
+
+  @Override
+  public void processGroup(int tag) throws HiveException {
+    processGroupCalled[tag] = true;
+    boolean shouldProceed = true;
+    for (int i = 0; i < numParents; i++) {
+      if (!processGroupCalled[i]) {
+        shouldProceed = false;
+        break;
+      }
+    }
+    if (shouldProceed) {
+      Operator<? extends OperatorDesc> child = childOperatorsArray[0];
+      int childTag = childOperatorsTag[0];
+      child.flush();
+      child.endGroup();
+      child.processGroup(childTag);
+    }
+  }
+
+  @Override
+  protected void closeOp(boolean abort) throws HiveException {
+    for (int i = 0; i < numParents; i++) {
+      LOG.info(id + ", tag=" + i + ", forwarded " + cntr[i] + " rows");
+    }
+  }
+
+  /**
+   * @return the name of the operator
+   */
+  @Override
+  public String getName() {
+    return getOperatorName();
+  }
+
+  static public String getOperatorName() {
+    return "MUX";
+  }
+
+  @Override
+  public OperatorType getType() {
+    return OperatorType.MUX;
+  }
+}

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Operator.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Operator.java?rev=1504395&r1=1504394&r2=1504395&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Operator.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Operator.java Thu Jul 18 09:16:52 2013
@@ -436,7 +436,7 @@ public abstract class Operator<T extends
    *          parent operator id
    * @throws HiveException
    */
-  private void initialize(Configuration hconf, ObjectInspector inputOI,
+  protected void initialize(Configuration hconf, ObjectInspector inputOI,
       int parentId) throws HiveException {
     LOG.info("Initializing child " + id + " " + getName());
     // Double the size of the array if needed
@@ -524,7 +524,7 @@ public abstract class Operator<T extends
     LOG.debug("Start group Done");
   }
 
-  // If a operator wants to do some work at the end of a group
+  // If an operator wants to do some work at the end of a group
   public void endGroup() throws HiveException {
     LOG.debug("Ending group");
 
@@ -544,6 +544,20 @@ public abstract class Operator<T extends
     LOG.debug("End group Done");
   }
 
+  // an blocking operator (e.g. GroupByOperator and JoinOperator) can
+  // override this method to forward its outputs
+  public void flush() throws HiveException {
+  }
+
+  public void processGroup(int tag) throws HiveException {
+    if (childOperators == null) {
+      return;
+    }
+    for (int i = 0; i < childOperatorsArray.length; i++) {
+      childOperatorsArray[i].processGroup(childOperatorsTag[i]);
+    }
+  }
+
   protected boolean allInitializedParentsAreClosed() {
     if (parentOperators != null) {
       for (Operator<? extends OperatorDesc> parent : parentOperators) {
@@ -1481,6 +1495,7 @@ public abstract class Operator<T extends
     return true;
   }
 
+  @Override
   public String toString() {
     return getName() + "[" + getIdentifier() + "]";
   }

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/OperatorFactory.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/OperatorFactory.java?rev=1504395&r1=1504394&r2=1504395&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/OperatorFactory.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/OperatorFactory.java Thu Jul 18 09:16:52 2013
@@ -23,6 +23,8 @@ import java.util.List;
 import java.util.Map;
 
 import org.apache.hadoop.hive.ql.plan.CollectDesc;
+import org.apache.hadoop.hive.ql.plan.MuxDesc;
+import org.apache.hadoop.hive.ql.plan.DemuxDesc;
 import org.apache.hadoop.hive.ql.plan.DummyStoreDesc;
 import org.apache.hadoop.hive.ql.plan.ExtractDesc;
 import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
@@ -98,6 +100,10 @@ public final class OperatorFactory {
         HashTableSinkOperator.class));
     opvec.add(new OpTuple<DummyStoreDesc>(DummyStoreDesc.class,
         DummyStoreOperator.class));
+    opvec.add(new OpTuple<DemuxDesc>(DemuxDesc.class,
+        DemuxOperator.class));
+    opvec.add(new OpTuple<MuxDesc>(MuxDesc.class,
+        MuxOperator.class));
   }
 
   public static <T extends OperatorDesc> Operator<T> get(Class<T> opClass) {
@@ -257,7 +263,7 @@ public final class OperatorFactory {
   public static <T extends OperatorDesc> Operator<T> getAndMakeChild(T conf,
       RowSchema rwsch, Map<String, ExprNodeDesc> colExprMap, Operator... oplist) {
     Operator<T> ret = getAndMakeChild(conf, rwsch, oplist);
-    ret.setColumnExprMap(colExprMap);    
+    ret.setColumnExprMap(colExprMap);
     return (ret);
   }
 

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java?rev=1504395&r1=1504394&r2=1504395&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java Thu Jul 18 09:16:52 2013
@@ -168,13 +168,23 @@ public final class Utilities {
   public static String HADOOP_LOCAL_FS = "file:///";
 
   /**
-   * ReduceField.
-   *
+   * ReduceField:
+   * KEY: record key
+   * VALUE: record value
+   * ALIAS: the tag identifying the source of a record
    */
   public static enum ReduceField {
     KEY, VALUE, ALIAS
   };
 
+  public static List<String> fieldNameList;
+  static {
+    fieldNameList = new ArrayList<String>();
+    for (ReduceField r : ReduceField.values()) {
+      fieldNameList.add(r.toString());
+    }
+  }
+
   private Utilities() {
     // prevent instantiation
   }
@@ -236,15 +246,18 @@ public final class Utilities {
   public static void setWorkflowAdjacencies(Configuration conf, QueryPlan plan) {
     try {
       Graph stageGraph = plan.getQueryPlan().getStageGraph();
-      if (stageGraph == null)
+      if (stageGraph == null) {
         return;
+      }
       List<Adjacency> adjList = stageGraph.getAdjacencyList();
-      if (adjList == null)
+      if (adjList == null) {
         return;
+      }
       for (Adjacency adj : adjList) {
         List<String> children = adj.getChildren();
-        if (children == null || children.isEmpty())
+        if (children == null || children.isEmpty()) {
           return;
+        }
         conf.setStrings("mapreduce.workflow.adjacency."+adj.getNode(),
             children.toArray(new String[children.size()]));
       }

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/mr/ExecReducer.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/mr/ExecReducer.java?rev=1504395&r1=1504394&r2=1504395&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/mr/ExecReducer.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/mr/ExecReducer.java Thu Jul 18 09:16:52 2013
@@ -25,6 +25,7 @@ import java.net.URLClassLoader;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Iterator;
+import java.util.List;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
@@ -74,7 +75,6 @@ public class ExecReducer extends MapRedu
   private long cntr = 0;
   private long nextCntr = 1;
 
-  private static String[] fieldNames;
   public static final Log l4j = LogFactory.getLog("ExecReducer");
   private boolean isLogInfoEnabled = false;
 
@@ -86,13 +86,6 @@ public class ExecReducer extends MapRedu
   // Input value serde needs to be an array to support different SerDe
   // for different tags
   private final SerDe[] inputValueDeserializer = new SerDe[Byte.MAX_VALUE];
-  static {
-    ArrayList<String> fieldNameArray = new ArrayList<String>();
-    for (Utilities.ReduceField r : Utilities.ReduceField.values()) {
-      fieldNameArray.add(r.toString());
-    }
-    fieldNames = fieldNameArray.toArray(new String[0]);
-  }
 
   TableDesc keyTableDesc;
   TableDesc[] valueTableDesc;
@@ -148,7 +141,7 @@ public class ExecReducer extends MapRedu
         ois.add(valueObjectInspector[tag]);
         ois.add(PrimitiveObjectInspectorFactory.writableByteObjectInspector);
         rowObjectInspector[tag] = ObjectInspectorFactory
-            .getStandardStructObjectInspector(Arrays.asList(fieldNames), ois);
+            .getStandardStructObjectInspector(Utilities.fieldNameList, ois);
       }
     } catch (Exception e) {
       throw new RuntimeException(e);
@@ -176,7 +169,7 @@ public class ExecReducer extends MapRedu
 
   private BytesWritable groupKey;
 
-  ArrayList<Object> row = new ArrayList<Object>(3);
+  List<Object> row = new ArrayList<Object>(3);
   ByteWritable tag = new ByteWritable();
 
   public void reduce(Object key, Iterator values, OutputCollector output,

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/GenMRUnion1.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/GenMRUnion1.java?rev=1504395&r1=1504394&r2=1504395&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/GenMRUnion1.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/GenMRUnion1.java Thu Jul 18 09:16:52 2013
@@ -226,6 +226,15 @@ public class GenMRUnion1 implements Node
     // future
     Map<Operator<? extends OperatorDesc>, GenMapRedCtx> mapCurrCtx = ctx.getMapCurrCtx();
 
+    if (union.getConf().isAllInputsInSameReducer()) {
+      // All inputs of this UnionOperator are in the same Reducer.
+      // We do not need to break the operator tree.
+      mapCurrCtx.put((Operator<? extends OperatorDesc>) nd,
+          new GenMapRedCtx(ctx.getCurrTask(), ctx.getCurrTopOp(),
+              ctx.getCurrAliasId()));
+      return null;
+    }
+
     UnionParseContext uPrsCtx = uCtx.getUnionParseContext(union);
 
     ctx.setCurrUnionOp(union);

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/GenMapRedUtils.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/GenMapRedUtils.java?rev=1504395&r1=1504394&r2=1504395&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/GenMapRedUtils.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/GenMapRedUtils.java Thu Jul 18 09:16:52 2013
@@ -33,6 +33,7 @@ import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.hive.conf.HiveConf;
 import org.apache.hadoop.hive.ql.Context;
 import org.apache.hadoop.hive.ql.exec.ConditionalTask;
+import org.apache.hadoop.hive.ql.exec.DemuxOperator;
 import org.apache.hadoop.hive.ql.exec.JoinOperator;
 import org.apache.hadoop.hive.ql.exec.Operator;
 import org.apache.hadoop.hive.ql.exec.OperatorFactory;
@@ -113,7 +114,8 @@ public final class GenMapRedUtils {
             || currTask.getParentTasks().isEmpty())) {
       rootTasks.add(currTask);
     }
-    if (reducer.getClass() == JoinOperator.class) {
+    if (reducer.getClass() == JoinOperator.class ||
+        reducer.getClass() == DemuxOperator.class) {
       plan.setNeedsTagging(true);
     }
 
@@ -158,7 +160,8 @@ public final class GenMapRedUtils {
 
     plan.setNumReduceTasks(desc.getNumReducers());
 
-    if (reducer.getClass() == JoinOperator.class) {
+    if (reducer.getClass() == JoinOperator.class ||
+        reducer.getClass() == DemuxOperator.class) {
       plan.setNeedsTagging(true);
     }
 
@@ -946,7 +949,8 @@ public final class GenMapRedUtils {
 
       // TODO: Allocate work to remove the temporary files and make that
       // dependent on the redTask
-      if (reducer.getClass() == JoinOperator.class) {
+      if (reducer.getClass() == JoinOperator.class ||
+          reducer.getClass() == DemuxOperator.class) {
         cplan.setNeedsTagging(true);
       }
     }

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/Optimizer.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/Optimizer.java?rev=1504395&r1=1504394&r2=1504395&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/Optimizer.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/Optimizer.java Thu Jul 18 09:16:52 2013
@@ -22,6 +22,8 @@ import java.util.ArrayList;
 import java.util.List;
 
 import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.ql.optimizer.correlation.CorrelationOptimizer;
+import org.apache.hadoop.hive.ql.optimizer.correlation.ReduceSinkDeDuplication;
 import org.apache.hadoop.hive.ql.optimizer.index.RewriteGBUsingIndex;
 import org.apache.hadoop.hive.ql.optimizer.lineage.Generator;
 import org.apache.hadoop.hive.ql.optimizer.listbucketingpruner.ListBucketingPruner;
@@ -103,6 +105,11 @@ public class Optimizer {
     if (HiveConf.getBoolVar(hiveConf, HiveConf.ConfVars.HIVELIMITOPTENABLE)) {
       transformations.add(new GlobalLimitOptimizer());
     }
+    if(HiveConf.getBoolVar(hiveConf, HiveConf.ConfVars.HIVEOPTCORRELATION) &&
+        !HiveConf.getBoolVar(hiveConf, HiveConf.ConfVars.HIVEGROUPBYSKEW) &&
+        !HiveConf.getBoolVar(hiveConf, HiveConf.ConfVars.HIVE_OPTIMIZE_SKEWJOIN_COMPILETIME)) {
+      transformations.add(new CorrelationOptimizer());
+    }
     transformations.add(new SimpleFetchOptimizer());  // must be called last
   }
 

Added: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/correlation/AbstractCorrelationProcCtx.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/correlation/AbstractCorrelationProcCtx.java?rev=1504395&view=auto
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/correlation/AbstractCorrelationProcCtx.java (added)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/correlation/AbstractCorrelationProcCtx.java Thu Jul 18 09:16:52 2013
@@ -0,0 +1,73 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql.optimizer.correlation;
+
+import static org.apache.hadoop.hive.conf.HiveConf.ConfVars.HIVEOPTREDUCEDEDUPLICATIONMINREDUCER;
+import static org.apache.hadoop.hive.conf.HiveConf.ConfVars.HIVESCRIPTOPERATORTRUST;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.hadoop.hive.ql.exec.Operator;
+import org.apache.hadoop.hive.ql.lib.NodeProcessorCtx;
+import org.apache.hadoop.hive.ql.parse.ParseContext;
+
+abstract class AbstractCorrelationProcCtx implements NodeProcessorCtx {
+  private ParseContext pctx;
+  // For queries using script, the optimization cannot be applied without user's confirmation
+  // If script preserves alias and value for columns related to keys, user can set this true
+  private final boolean trustScript;
+
+  // This is min number of reducer for deduped RS to avoid query executed on
+  // too small number of reducers. For example, queries GroupBy+OrderBy can be executed by
+  // only one reducer if this configuration does not prevents
+  private final int minReducer;
+  private final Set<Operator<?>> removedOps;
+
+  public AbstractCorrelationProcCtx(ParseContext pctx) {
+    removedOps = new HashSet<Operator<?>>();
+    trustScript = pctx.getConf().getBoolVar(HIVESCRIPTOPERATORTRUST);
+    minReducer = pctx.getConf().getIntVar(HIVEOPTREDUCEDEDUPLICATIONMINREDUCER);
+    this.pctx = pctx;
+  }
+
+  public ParseContext getPctx() {
+    return pctx;
+  }
+
+  public void setPctx(ParseContext pctx) {
+    this.pctx = pctx;
+  }
+
+  public boolean trustScript() {
+    return trustScript;
+  }
+
+  public int minReducer() {
+    return minReducer;
+  }
+
+  public boolean hasBeenRemoved(Operator<?> rsOp) {
+    return removedOps.contains(rsOp);
+  }
+
+  public boolean addRemovedOperator(Operator<?> rsOp) {
+    return removedOps.add(rsOp);
+  }
+}