dilipbiswal commented on code in PR #55682:
URL: https://github.com/apache/spark/pull/55682#discussion_r3220912407
##########
python/pyspark/sql/dataframe.py:
##########
@@ -2870,6 +2870,73 @@ def lateralJoin(
"""
...
+ def nearestByJoin(
+ self,
+ other: "DataFrame",
+ rankingExpression: Column,
+ numResults: int,
+ mode: str,
+ direction: str,
+ *,
+ joinType: str = "inner",
+ ) -> "DataFrame":
+ """
+ Nearest-by top-K ranking join with another :class:`DataFrame`. For
each row on the
+ left (query side), returns up to ``numResults`` rows from ``other``
(base side), ranked
+ by ``rankingExpression``.
+
+ The current implementation evaluates the full cross-product of left
and right and
+ bounds memory per left row by ``numResults``. Index-backed approximate
strategies
+ (transparent to ``approx`` mode) are planned for a future release;
until then,
+ pre-filter ``other`` when it is large. Tie-breaking among rows with
equal ranking
+ values is unspecified.
+
+ .. versionadded:: 4.2.0
+
+ Parameters
+ ----------
+ other : :class:`DataFrame`
+ Right (base side) of the join - the candidate pool searched for
each row of this
+ DataFrame.
+ rankingExpression : :class:`Column`
+ Scalar expression used to rank candidate rows on the right side.
+ numResults : int
+ Maximum number of matches per query row. Must be between 1 and
100000.
+ mode : str
+ Search algorithm contract. Must be one of: ``approx``, ``exact``.
``approx`` allows
+ the optimizer to use indexed or other approximate strategies when
available;
+ ``exact`` forces brute-force evaluation and requires the ranking
expression to be
+ deterministic.
+ direction : str
+ ``"distance"`` (smallest values first) or ``"similarity"``
(largest values first).
Review Comment:
Done
##########
sql/core/src/test/scala/org/apache/spark/sql/DataFrameNearestByJoinSuite.scala:
##########
@@ -0,0 +1,442 @@
+/*
+ * 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
+
+import org.apache.spark.sql.catalyst.plans.{NearestByDirection,
NearestByJoinMode, NearestByJoinType}
+import org.apache.spark.sql.execution.streaming.runtime.MemoryStream
+import org.apache.spark.sql.functions._
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.SharedSparkSession
+import org.apache.spark.tags.SlowSQLTest
+
+@SlowSQLTest
+class DataFrameNearestByJoinSuite extends QueryTest with SharedSparkSession {
+
+ private def prepareForNearestByJoin(): (classic.DataFrame,
classic.DataFrame) = {
+ val users = spark.createDataFrame(
+ Seq((1, 10.0), (2, 20.0), (3, 30.0))).toDF("user_id", "score")
+ val products = spark.createDataFrame(
+ Seq(("A", 11.0), ("B", 22.0), ("C", 5.0))).toDF("product", "pscore")
+ (users, products)
+ }
+
+ test("similarity, inner, k=1") {
+ val (users, products) = prepareForNearestByJoin()
+ val result = users.nearestByJoin(
+ products,
+ -abs(users("score") - products("pscore")),
+ numResults = 1,
+ mode = "exact",
+ direction = "similarity")
+
+ checkAnswer(
+ result.select("user_id", "product").orderBy("user_id"),
+ Seq(Row(1, "A"), Row(2, "B"), Row(3, "B"))
+ )
+ }
+
+ test("distance, inner, k=2") {
+ val (users, products) = prepareForNearestByJoin()
+ val result = users.nearestByJoin(
+ products,
+ abs(users("score") - products("pscore")),
+ numResults = 2,
+ mode = "exact",
+ direction = "distance")
+
+ // For each user_id, closest 2 by |score - pscore|:
+ // user 1 (10): A (|10-11|=1), C (|10-5|=5)
+ // user 2 (20): B (|20-22|=2), A (|20-11|=9)
+ // user 3 (30): B (|30-22|=8), A (|30-11|=19)
+ checkAnswer(
+ result.select("user_id", "product").orderBy("user_id", "product"),
+ Seq(
+ Row(1, "A"), Row(1, "C"),
+ Row(2, "A"), Row(2, "B"),
+ Row(3, "A"), Row(3, "B"))
+ )
+ }
+
+ test("left outer when right side is empty") {
+ val (users, products) = prepareForNearestByJoin()
+ val emptyProducts = products.filter(lit(false))
+ val result = users.nearestByJoin(
+ emptyProducts,
+ -abs(users("score") - emptyProducts("pscore")),
+ numResults = 1,
+ joinType = "leftouter",
+ mode = "approx",
+ direction = "similarity")
+
+ checkAnswer(
+ result.select("user_id", "product").orderBy("user_id"),
+ Seq(Row(1, null), Row(2, null), Row(3, null))
+ )
+ }
+
+ test("inner drops left rows with no matches") {
+ val (users, products) = prepareForNearestByJoin()
+ val emptyProducts = products.filter(lit(false))
+ val result = users.nearestByJoin(
+ emptyProducts,
+ -abs(users("score") - emptyProducts("pscore")),
+ numResults = 1,
+ mode = "exact",
+ direction = "similarity")
+
+ assert(result.count() === 0)
+ }
+
+ test("self-join: each row finds nearest other rows in the same DataFrame") {
+ val (users, _) = prepareForNearestByJoin()
+ // For each user, find the 1 other user with the closest score (excluding
self by ranking).
Review Comment:
Done
--
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]