rdblue commented on a change in pull request #2022: URL: https://github.com/apache/iceberg/pull/2022#discussion_r559054501
########## File path: spark3-extensions/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteMergeInto.scala ########## @@ -0,0 +1,204 @@ +/* + * 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.spark.sql.catalyst.optimizer + +import org.apache.iceberg.TableProperties.{MERGE_WRITE_CARDINALITY_CHECK, MERGE_WRITE_CARDINALITY_CHECK_DEFAULT, MERGE_WRITE_SORT_MODE, MERGE_WRITE_SORT_MODE_GLOBAL} +import org.apache.iceberg.spark.Spark3Util +import org.apache.iceberg.spark.Spark3Util.toRequiredDistribution +import org.apache.iceberg.spark.source.SparkTable +import org.apache.iceberg.util.PropertyUtil +import org.apache.spark.internal.Logging +import org.apache.spark.sql.SparkSession +import org.apache.spark.sql.catalyst.expressions._ +import org.apache.spark.sql.catalyst.plans.{FullOuter, Inner} +import org.apache.spark.sql.catalyst.plans.logical.{MergeAction, _} +import org.apache.spark.sql.catalyst.rules.Rule +import org.apache.spark.sql.catalyst.utils.PlanHelper +import org.apache.spark.sql.connector.catalog.Table +import org.apache.spark.sql.execution.datasources.v2.DataSourceV2Relation +import org.apache.spark.sql.functions._ +import org.apache.spark.sql.internal.SQLConf + +case class RewriteMergeInto(spark: SparkSession) extends Rule[LogicalPlan] with PlanHelper with Logging { + val ROW_FROM_SOURCE = "_row_from_source_" + val ROW_FROM_TARGET = "_row_from_target_" + + import org.apache.spark.sql.execution.datasources.v2.ExtendedDataSourceV2Implicits._ + + override def apply(plan: LogicalPlan): LogicalPlan = { + plan resolveOperators { + // rewrite all operations that require reading the table to delete records + case MergeIntoTable(target: DataSourceV2Relation, + source: LogicalPlan, cond, actions, notActions) => + val targetOutputCols = target.output + val newProjectCols = target.output ++ + Seq( + Alias(InputFileName(), FILE_NAME_COL)(), + Alias(monotonically_increasing_id().expr, ROW_ID_COL)() + ) + val newTargetTable = Project(newProjectCols, target) + + // Construct the plan to prune target based on join condition between source and + // target. + val prunedTargetPlan = Join(source, newTargetTable, Inner, Some(cond), JoinHint.NONE) + val writeInfo = newWriteInfo(target.schema) + val mergeBuilder = target.table.asMergeable.newMergeBuilder("delete", writeInfo) + val targetTableScan = buildScanPlan(spark, target.table, + target.output, mergeBuilder, prunedTargetPlan, isCountCheckEnabled(target.table, actions)) + + // Construct an outer join to help track changes in source and target. + // TODO : Optimize this to use LEFT ANTI or RIGHT OUTER when applicable. + val sourceTableProj = source.output ++ Seq(Alias(lit(true).expr, ROW_FROM_SOURCE)()) + val targetTableProj = target.output ++ Seq(Alias(lit(true).expr, ROW_FROM_TARGET)()) + val newTargetTableScan = Project(targetTableProj, targetTableScan) + val newSourceTableScan = Project(sourceTableProj, source) + val joinPlan = Join(newSourceTableScan, newTargetTableScan, FullOuter, Some(cond), JoinHint.NONE) + + // Construct the plan to replace the data based on the output of `MergeInto` + val mergeParams = MergeIntoParams( + isSourceRowNotPresent = IsNull(findOutputAttr(joinPlan, ROW_FROM_SOURCE)), + isTargetRowNotPresent = IsNull(findOutputAttr(joinPlan, ROW_FROM_TARGET)), + matchedConditions = actions.map(getClauseCondition), + matchedOutputs = actions.map(actionOutput(_, targetOutputCols)), + notMatchedConditions = notActions.map(getClauseCondition), + notMatchedOutputs = notActions.map(actionOutput(_, targetOutputCols)), + targetOutput = targetOutputCols :+ Literal(false), + deleteOutput = targetOutputCols :+ Literal(true), + joinedAttributes = joinPlan.output + ) + val joinKeysFromTarget = targetOutputCols.filter ( + attr => cond.references.exists(attr.semanticEquals(_)) + ) + val writePlan = buildWritePlan(joinPlan, Project(target.output, joinPlan), target.table, joinKeysFromTarget) + val mergePlan = MergeInto(mergeParams, target, writePlan) Review comment: Looks like this adds the sort in `buildWritePlan` to the joined data, not the merged data. I think that will be less efficient than adding the sort after the merge for two reasons: 1. Deleted rows will be included, only to be removed on the write nodes 2. The joined row will contain both the target columns and source columns, so this would be shuffling both the original values and update values in a lot of cases when only the updated values are needed. I think that it should be this instead: ```java val mergePlan = MergeInto(mergeParams, target, joinPlan) val writePlan = buildWritePlan(mergePlan, table) val batchWrite = ... ReplaceData(target, batchWrite, writePlan) ``` I think that will also allow you to remove some of the additional arguments from `buildWritePlan`. ---------------------------------------------------------------- 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] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
