Skip to content

Commit

Permalink
[FLINK-12173][table] Optimize SELECT DISTINCT
Browse files Browse the repository at this point in the history
  • Loading branch information
yiyutian1 committed Dec 5, 2024
1 parent 8e17931 commit 2781161
Show file tree
Hide file tree
Showing 25 changed files with 328 additions and 136 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import org.apache.flink.table.planner.plan.nodes.exec.processor.{ExecNodeGraphPr
import org.apache.flink.table.planner.plan.nodes.exec.serde.{JsonSerdeUtil, SerdeContext}
import org.apache.flink.table.planner.plan.nodes.physical.FlinkPhysicalRel
import org.apache.flink.table.planner.plan.optimize.Optimizer
import org.apache.flink.table.planner.plan.optimize.program.FlinkChangelogModeInferenceProgram
import org.apache.flink.table.planner.sinks.DataStreamTableSink
import org.apache.flink.table.planner.sinks.TableSinkUtils.{inferSinkPhysicalSchema, validateLogicalPhysicalTypesCompatible, validateTableSink}
import org.apache.flink.table.planner.utils.InternalConfigOptions.{TABLE_QUERY_CURRENT_DATABASE, TABLE_QUERY_START_EPOCH_TIME, TABLE_QUERY_START_LOCAL_TIME}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import org.apache.flink.table.planner.plan.`trait`._
import org.apache.flink.table.planner.plan.`trait`.UpdateKindTrait.{beforeAfterOrNone, onlyAfterOrNone, BEFORE_AND_AFTER, ONLY_UPDATE_AFTER}
import org.apache.flink.table.planner.plan.metadata.FlinkRelMetadataQuery
import org.apache.flink.table.planner.plan.nodes.physical.stream._
import org.apache.flink.table.planner.plan.optimize.program.{FlinkOptimizeProgram, StreamOptimizeContext}
import org.apache.flink.table.planner.plan.utils._
import org.apache.flink.table.planner.plan.utils.RankProcessStrategy.{AppendFastStrategy, RetractStrategy, UpdateFastStrategy}
import org.apache.flink.table.planner.sinks.DataStreamTableSink
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@
package org.apache.flink.table.planner.plan.optimize.program

import org.apache.flink.table.api.TableException
import org.apache.flink.table.planner.plan.cost.FlinkCostFactory
import org.apache.flink.table.planner.plan.metadata.FlinkRelMdNonCumulativeCost
import org.apache.flink.util.Preconditions

import org.apache.calcite.plan.RelTrait
import org.apache.calcite.plan.{RelOptCostFactory, RelTrait}
import org.apache.calcite.plan.hep.{HepPlanner, HepProgram}
import org.apache.calcite.rel.RelNode

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,9 @@ object FlinkStreamRuleSets {
// Avoid async calls which call async calls.
AsyncCalcSplitRule.NESTED_SPLIT,
// Avoid having async calls in multiple projections in a single calc.
AsyncCalcSplitRule.ONE_PER_CALC_SPLIT
AsyncCalcSplitRule.ONE_PER_CALC_SPLIT,
// Optimize SELECT DISTINCT to use FlinkLogicalRank
StreamLogicalOptimizeSelectDistinctRule.INSTANCE
)

/** RuleSet to do physical optimize for stream */
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,140 @@
/*
* 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.flink.table.planner.plan.rules.physical.stream
import org.apache.flink.table.planner.JList
import org.apache.flink.table.planner.calcite.FlinkTypeFactory
import org.apache.flink.table.planner.plan.nodes.FlinkConventions
import org.apache.flink.table.planner.plan.nodes.logical.{FlinkLogicalAggregate, FlinkLogicalCalc, FlinkLogicalJoin, FlinkLogicalRank}
import org.apache.flink.table.planner.plan.nodes.physical.stream.{StreamPhysicalIntervalJoin, StreamPhysicalRank, StreamPhysicalTemporalSort}
import org.apache.flink.table.planner.plan.utils.{RankProcessStrategy, RankUtil, WindowJoinUtil}
import org.apache.flink.table.runtime.operators.rank.{ConstantRankRange, RankType}
import org.apache.flink.table.types.logical.IntType

import org.apache.calcite.plan.{RelOptRule, RelOptRuleCall}
import org.apache.calcite.plan.RelOptRule.{any, operand}
import org.apache.calcite.rel.`type`.{RelDataType, RelDataTypeField, RelDataTypeFieldImpl, RelDataTypeSystem}
import org.apache.calcite.rel.{RelCollation, RelCollations, RelFieldCollation}
import org.apache.calcite.rel.RelNode
import org.apache.calcite.rel.convert.ConverterRule.Config
import org.apache.calcite.rel.core.JoinRelType
import org.apache.calcite.rel.hint.RelHint
import org.apache.calcite.rel.logical.LogicalProject
import org.apache.calcite.rex.{RexInputRef, RexNode, RexProgram}
import org.apache.calcite.util.ImmutableBitSet

import java.util
import java.util.Collections

import scala.collection.convert.ImplicitConversions.`iterable AsScalaIterable`

/**
* Rule that matches [[FlinkLogicalAggregate]], and converts it to [[FlinkLogicalRank]] in the case
* of SELECT DISTINCT queries.
*
* e.g. {SELECT DISTINCT a, b, c;} will be converted to [[FlinkLogicalRank]] instead of
* [[FlinkLogicalAggregate]] in rowtime.
*/
class StreamLogicalOptimizeSelectDistinctRule
extends RelOptRule(operand(classOf[FlinkLogicalAggregate], any)) {
private val classLoader = Thread.currentThread().getContextClassLoader
private val typeSystem = RelDataTypeSystem.DEFAULT
private val typeFactory = new FlinkTypeFactory(classLoader, typeSystem)
private val intType: RelDataType =
typeFactory.createFieldTypeFromLogicalType(new IntType(false))

override def matches(call: RelOptRuleCall): Boolean = {
val rel: FlinkLogicalAggregate = call.rel(0)
// check if it's a SELECT DISTINCT query
rel.getGroupSet.cardinality() == rel.getRowType.getFieldCount && rel.getAggCallList.isEmpty
}

override def onMatch(call: RelOptRuleCall): Unit = {
val agg: FlinkLogicalAggregate = call.rel(0)

val input = agg.getInput
val traitSet = agg.getTraitSet
val cluster = agg.getCluster

// Create a list of all group keys
val groupKeys = agg.getGroupSet

// Create a projection to select only the fields in the DISTINCT clause
val projectList: JList[RexNode] = {
val list = new util.ArrayList[RexNode](groupKeys.cardinality())
groupKeys.toList.foreach(i => list.add(RexInputRef.of(i, input.getRowType)))
list
}

// Create the projected row type
val projectedFields: JList[RelDataTypeField] = {
val fields = new util.ArrayList[RelDataTypeField](projectList.size())
projectList.forEach {
rexNode =>
val rexInputRef = rexNode.asInstanceOf[RexInputRef]
fields.add(input.getRowType.getFieldList.get(rexInputRef.getIndex))
}
fields
}

// Create the projected row type
val projectedRowType: RelDataType = typeFactory.createStructType(projectedFields)

// Create a RelCollation based on all group keys
val fieldCollations: JList[RelFieldCollation] = {
val collations = new util.ArrayList[RelFieldCollation](groupKeys.cardinality())
groupKeys.foreach {
key => collations.add(new RelFieldCollation(key, RelFieldCollation.Direction.ASCENDING))
}
collations
}
val collation: RelCollation = RelCollations.of(fieldCollations)

// Create a projection to select only the fields in the DISTINCT clause
val projection: RelNode = FlinkLogicalCalc.create(
input,
RexProgram.create(
input.getRowType,
projectList,
null,
projectedRowType,
cluster.getRexBuilder
))

val rank = new FlinkLogicalRank(
cluster,
traitSet,
projection,
groupKeys,
collation,
RankType.ROW_NUMBER,
new ConstantRankRange(1, 1), // We only want the first row for each group
new RelDataTypeFieldImpl("rk", projectedRowType.getFieldCount - 1, intType),
false
)
try RankUtil.canConvertToDeduplicate(rank)
catch {
case _: Exception =>
return
}
call.transformTo(rank)
}
}

object StreamLogicalOptimizeSelectDistinctRule {
val INSTANCE = new StreamLogicalOptimizeSelectDistinctRule()
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ class StreamPhysicalGroupAggregateRule(config: Config) extends ConverterRule(con

override def matches(call: RelOptRuleCall): Boolean = {
val agg: FlinkLogicalAggregate = call.rel(0)

// check if we have grouping sets
if (agg.getGroupType != Group.SIMPLE) {
throw new TableException("GROUPING SETS are currently not supported.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ package org.apache.flink.table.planner.plan.rules.physical.stream

import org.apache.flink.table.api.{TableException, ValidationException}
import org.apache.flink.table.planner.calcite.FlinkTypeFactory.isRowtimeIndicatorType
import org.apache.flink.table.planner.plan.nodes.FlinkRelNode
import org.apache.flink.table.planner.plan.nodes.{FlinkConventions, FlinkRelNode}
import org.apache.flink.table.planner.plan.nodes.logical.FlinkLogicalJoin
import org.apache.flink.table.planner.plan.nodes.physical.stream.StreamPhysicalIntervalJoin
import org.apache.flink.table.planner.plan.utils.IntervalJoinUtil.satisfyIntervalJoin
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -188,7 +188,7 @@ void testUpdatesInUpstreamOperatorNotSupported() {
assertThatExceptionOfType(TableException.class)
.isThrownBy(() -> tEnv.executeSql(sqlQuery))
.withMessageContaining(
"Match Recognize doesn't support consuming update changes which is produced by node GroupAggregate(");
"Match Recognize doesn't support consuming update and delete changes which is produced by node Rank(");
}
}

Expand Down
Loading

0 comments on commit 2781161

Please sign in to comment.