[ https://issues.apache.org/jira/browse/HIVE-21857?focusedWorklogId=264258&page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel#worklog-264258 ]
ASF GitHub Bot logged work on HIVE-21857: ----------------------------------------- Author: ASF GitHub Bot Created on: 21/Jun/19 00:19 Start Date: 21/Jun/19 00:19 Worklog Time Spent: 10m Work Description: vineetgarg02 commented on 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: us...@infra.apache.org Issue Time Tracking ------------------- Worklog Id: (was: 264258) Time Spent: 40m (was: 0.5h) > Sort conditions in a filter predicate to accelerate query processing > -------------------------------------------------------------------- > > Key: HIVE-21857 > URL: https://issues.apache.org/jira/browse/HIVE-21857 > Project: Hive > Issue Type: New Feature > Components: CBO > Reporter: Jesus Camacho Rodriguez > Assignee: Jesus Camacho Rodriguez > Priority: Major > Labels: pull-request-available > Attachments: HIVE-21857.01.patch, HIVE-21857.02.patch, > HIVE-21857.03.patch, HIVE-21857.04.patch > > Time Spent: 40m > Remaining Estimate: 0h > > Following approach similar to > http://db.cs.berkeley.edu/jmh/miscpapers/sigmod93.pdf . > To reorder predicates in AND conditions, we could rank each of elements in > the clauses in increasing order based on following formula: > {code} > rank = (selectivity - 1) / cost per tuple > {code} > Similarly, for OR conditions: > {code} > rank = (-selectivity) / cost per tuple > {code} > Selectivity can be computed with FilterSelectivityEstimator. For cost per > tuple, we will need to come up with some heuristic based on how expensive is > the evaluation of the functions contained in that predicate. Custom UDFs > could be annotated. -- This message was sent by Atlassian JIRA (v7.6.3#76005)