vineetgarg02 commented on a change in pull request #671: HIVE-21857
URL: https://github.com/apache/hive/pull/671#discussion_r296056369
 
 

 ##########
 File path: 
ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveFilterSortPredicates.java
 ##########
 @@ -0,0 +1,268 @@
+/*
+ * 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.calcite.rules;
+
+import java.util.Comparator;
+import java.util.List;
+import java.util.stream.Collectors;
+import org.apache.calcite.plan.RelOptRule;
+import org.apache.calcite.plan.RelOptRuleCall;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.Filter;
+import org.apache.calcite.rel.metadata.RelMetadataQuery;
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexDynamicParam;
+import org.apache.calcite.rex.RexFieldAccess;
+import org.apache.calcite.rex.RexInputRef;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexShuttle;
+import org.apache.calcite.rex.RexVisitorImpl;
+import org.apache.calcite.util.Pair;
+import 
org.apache.hadoop.hive.ql.optimizer.calcite.stats.FilterSelectivityEstimator;
+import org.apache.hadoop.hive.ql.optimizer.calcite.stats.HiveRelMdSize;
+
+
+/**
+ * Rule that sorts conditions in a filter predicate to accelerate query 
processing
+ * based on selectivity and compute cost. Currently it is not applied 
recursively,
+ * i.e., it is only applied to top predicates in the condition.
+ */
+public class HiveFilterSortPredicates extends RelOptRule {
+
+  public static final HiveFilterSortPredicates INSTANCE = new 
HiveFilterSortPredicates();
+
+
+  private HiveFilterSortPredicates() {
+    super(
+        operand(Filter.class,
+            operand(RelNode.class, any())));
+  }
+
+  @Override
+  public boolean matches(RelOptRuleCall call) {
+    final Filter filter = call.rel(0);
+
+    HiveRulesRegistry registry = 
call.getPlanner().getContext().unwrap(HiveRulesRegistry.class);
+
+    // If this operator has been visited already by the rule,
+    // we do not need to apply the optimization
+    if (registry != null && registry.getVisited(this).contains(filter)) {
+      return false;
+    }
+
+    return true;
+  }
+
+  @Override
+  public void onMatch(RelOptRuleCall call) {
+    final Filter filter = call.rel(0);
+    final RelNode input = call.rel(1);
+
+    // Register that we have visited this operator in this rule
+    HiveRulesRegistry registry = 
call.getPlanner().getContext().unwrap(HiveRulesRegistry.class);
+    if (registry != null) {
+      registry.registerVisited(this, filter);
+    }
+
+    final RexNode originalCond = filter.getCondition();
+    RexSortPredicatesShuttle sortPredicatesShuttle = new 
RexSortPredicatesShuttle(
+        input, filter.getCluster().getMetadataQuery());
+    final RexNode newCond = originalCond.accept(sortPredicatesShuttle);
+    if (!sortPredicatesShuttle.modified) {
+      // We are done, bail out
+      return;
+    }
+
+    // We register the new filter so we do not fire the rule on it again
+    final Filter newFilter = filter.copy(filter.getTraitSet(), input, newCond);
+    if (registry != null) {
+      registry.registerVisited(this, newFilter);
+    }
+
+    call.transformTo(newFilter);
+  }
+
+  /**
+   * If the expression is an AND/OR, it will sort predicates accordingly
+   * to maximize performance.
+   * In particular, for AND clause:
+   * rank = (selectivity - 1) / cost per tuple
+   * Similarly, for OR clause:
+   * rank = (-selectivity) / cost per tuple
+   */
+  private static class RexSortPredicatesShuttle extends RexShuttle {
+
+    private FilterSelectivityEstimator selectivityEstimator;
+    private boolean modified;
+
+    private RexSortPredicatesShuttle(RelNode inputRel, RelMetadataQuery mq) {
+      selectivityEstimator = new FilterSelectivityEstimator(inputRel, mq);
+      modified = false;
+    }
+
+    @Override
+    public RexNode visitCall(final RexCall call) {
+      switch (call.getKind()) {
+        case AND:
+          List<RexNode> newAndOperands = call.getOperands()
+              .stream()
+              .map(pred -> new Pair<>(pred, rankingAnd(pred)))
+              .sorted(Comparator.comparing(Pair::getValue, 
Comparator.nullsLast(Double::compare)))
+              .map(Pair::getKey)
+              .collect(Collectors.toList());
+          if (!call.getOperands().equals(newAndOperands)) {
+            modified = true;
+            return call.clone(call.getType(), newAndOperands);
+          }
+          break;
+        case OR:
+          List<RexNode> newOrOperands = call.getOperands()
+              .stream()
+              .map(pred -> new Pair<>(pred, rankingOr(pred)))
+              .sorted(Comparator.comparing(Pair::getValue, 
Comparator.nullsLast(Double::compare)))
+              .map(Pair::getKey)
+              .collect(Collectors.toList());
+          if (!call.getOperands().equals(newOrOperands)) {
+            modified = true;
+            return call.clone(call.getType(), newOrOperands);
+          }
+          break;
+      }
+      return call;
+    }
+
+    private Double rankingAnd(RexNode e) {
+      Double selectivity = selectivityEstimator.estimateSelectivity(e);
+      if (selectivity == null) {
+        return null;
+      }
+      Double costPerTuple = costPerTuple(e);
+      if (costPerTuple == null) {
+        return null;
+      }
+      return (selectivity - 1d) / costPerTuple;
+    }
+
+    private Double rankingOr(RexNode e) {
+      Double selectivity = selectivityEstimator.estimateSelectivity(e);
+      if (selectivity == null) {
+        return null;
+      }
+      Double costPerTuple = costPerTuple(e);
+      if (costPerTuple == null) {
+        return null;
+      }
+      return -selectivity / costPerTuple;
+    }
+
+    private Double costPerTuple(RexNode e) {
+      return e.accept(new RexFunctionCost());
+    }
+
+  }
+
+  /**
+   * The cost of a call expression e is computed as:
+   * cost(e) = functionCost + sum_1..n(byteSize(o_i) + cost(o_i))
+   * with the call having operands i in 1..n.
+   */
+  private static class RexFunctionCost extends RexVisitorImpl<Double> {
+
+    private RexFunctionCost() {
+      super(true);
+    }
+
+    @Override
+    public Double visitCall(RexCall call) {
+      if (!deep) {
+        return null;
+      }
+
+      Double cost = 0.d;
+      for (RexNode operand : call.operands) {
+        Double operandCost = operand.accept(this);
+        if (operandCost == null) {
+          return null;
+        }
+        cost += operandCost;
+        Double size = HiveRelMdSize.averageTypeSize(operand.getType());
+        if (size == null) {
+          return null;
+        }
+        cost += size;
+      }
+
+      return cost + functionCost(call);
+    }
+
+    private static Double functionCost(RexCall call) {
+      switch (call.getKind()) {
+        case EQUALS:
+        case NOT_EQUALS:
+        case LESS_THAN:
+        case GREATER_THAN:
+        case LESS_THAN_OR_EQUAL:
+        case GREATER_THAN_OR_EQUAL:
+        case IS_NOT_NULL:
+        case IS_NULL:
+        case IS_TRUE:
+        case IS_NOT_TRUE:
+        case IS_FALSE:
+        case IS_NOT_FALSE:
+          return 1d;
+
+        case BETWEEN:
+          return 3d;
+
+        case IN:
+          return 2d * (call.getOperands().size() - 1);
 
 Review comment:
   Can you add comment to explain what is the rationale for choosing these 
"arbitrary constant" for function costs.

----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
[email protected]


With regards,
Apache Git Services

---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to