You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@iceberg.apache.org by GitBox <gi...@apache.org> on 2021/01/20 02:25:12 UTC

[GitHub] [iceberg] dilipbiswal commented on a change in pull request #2022: Implement logic to group and sort rows before writing rows for MERGE INTO.

dilipbiswal commented on a change in pull request #2022:
URL: https://github.com/apache/iceberg/pull/2022#discussion_r560630705



##########
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)
+        val batchWrite = mergeBuilder.asWriteBuilder.buildForBatch()
+        ReplaceData(target, batchWrite, mergePlan)
+    }
+  }
+
+  def buildWritePlan(childPlan: LogicalPlan,
+                     planToResolveFrom: LogicalPlan,
+                     table: Table, targetJoinAttrs: Seq[Attribute]): LogicalPlan = {
+    val iceTable = table.asInstanceOf[SparkTable].table()
+    val globalSortEnabled = isGlobalSortEnabled(table)
+    val partitionExpressions = toCatalyst(toRequiredDistribution(iceTable.spec), planToResolveFrom)
+    val sortExpressions: Seq[SortOrder] =  toCatalyst(toRequiredDistribution(iceTable.spec(),
+      iceTable.sortOrder(), false), planToResolveFrom).asInstanceOf[Seq[SortOrder]]
+    val dist = toRequiredDistribution(iceTable.spec(),
+      iceTable.sortOrder(), true)
+    val globalSortExprs: Seq[SortOrder] = toCatalyst(dist, planToResolveFrom).asInstanceOf[Seq[SortOrder]]

Review comment:
       @rdblue Thank you very much !!




----------------------------------------------------------------
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:
users@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscribe@iceberg.apache.org
For additional commands, e-mail: issues-help@iceberg.apache.org