dilipbiswal commented on code in PR #55629:
URL: https://github.com/apache/spark/pull/55629#discussion_r3177315115


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/RewriteNearestByJoin.scala:
##########
@@ -0,0 +1,125 @@
+/*
+ * 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.spark.sql.catalyst.expressions._
+import org.apache.spark.sql.catalyst.expressions.aggregate._
+import org.apache.spark.sql.catalyst.plans._
+import org.apache.spark.sql.catalyst.plans.logical._
+import org.apache.spark.sql.catalyst.rules._
+
+/**
+ * Replaces a logical [[NearestByJoin]] operator with a 
`Generate(Inline(...))` over an
+ * `Aggregate` that tags each left row with a unique id, cross-joins with the 
right side, and
+ * groups by the unique id to compute the top-K matches via `MAX_BY`/`MIN_BY` 
(K-overload).
+ *
+ * Input Pseudo-Query:
+ * {{{
+ *    SELECT * FROM left [INNER | LEFT OUTER] JOIN right
+ *      {APPROX | EXACT} NEAREST k BY {DISTANCE | SIMILARITY} expr
+ * }}}
+ *
+ * Rewritten Plan (SIMILARITY, INNER join type):
+ * {{{
+ *    Generate inline(_matches), [N], outer=false, [right.col1, right.col2, 
...]
+ *      +- Aggregate [__qid],
+ *           [first(left.col0) AS left.col0, ..., first(left.colN-1) AS 
left.colN-1,
+ *            max_by(struct(right.*), expr, k) AS _matches]
+ *          +- Join Inner
+ *             :- Project [left.*, monotonically_increasing_id() AS __qid]
+ *             :  +- left
+ *             +- right
+ * }}}
+ *
+ * For `DISTANCE`, `MIN_BY` is used instead of `MAX_BY`. For `LEFT OUTER`, the 
`Generate` is
+ * constructed with `outer = true` so left rows with no matches (empty/null 
`_matches`) are
+ * preserved with `NULL` right-side columns.
+ *
+ * In this initial implementation both `APPROX` and `EXACT` take the same 
brute-force rewrite
+ * path. `APPROX` establishes the contract for future indexed-ANN strategies.
+ */
+object RewriteNearestByJoin extends Rule[LogicalPlan] {
+  def apply(plan: LogicalPlan): LogicalPlan = plan.transformUpWithNewOutput {
+    case j @ NearestByJoin(left, right, joinType, _, numResults, 
rankingExpression, direction) =>
+      // 1. Tag each left row with a unique id so that rows from the same left 
row can later be
+      //    grouped together after the cross-join with `right`.
+      val qidAlias = Alias(MonotonicallyIncreasingID(), "__qid")()
+      val taggedLeft = Project(left.output :+ qidAlias, left)
+      val qidAttr = qidAlias.toAttribute
+
+      // 2. LEFT OUTER-join the tagged left with right (no join condition). 
LEFT OUTER
+      //    (rather than INNER) preserves left rows even when `right` is 
empty, so that a
+      //    `LEFT OUTER NEAREST BY` query still returns those rows with `NULL` 
right-side
+      //    columns after the aggregate + inline below. When `right` is 
non-empty every left
+      //    row already has right-row pairings, so LEFT OUTER and INNER are 
equivalent.
+      //
+      //    Tag the join so `CheckCartesianProducts` skips it: the rewrite 
intentionally
+      //    materializes a cross product bounded by the downstream `MaxMinByK` 
aggregate, so
+      //    `spark.sql.crossJoin.enabled = false` should not reject user 
queries written as
+      //    `NEAREST BY`.
+      val join = Join(taggedLeft, right, LeftOuter, None, JoinHint.NONE)
+      join.setTagValue(NearestByJoin.SYNTHETIC_JOIN_TAG, ())

Review Comment:
   Thanks @gengliangwang @zhidongqu-db - i have implemented (b).



-- 
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.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


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

Reply via email to