You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "zhengruifeng (via GitHub)" <gi...@apache.org> on 2025/01/03 04:05:50 UTC

Re: [PR] [SPARK-48665][PYTHON][CONNECT] Support providing a dict in pyspark lit to create a map. [spark]

zhengruifeng commented on code in PR #49318:
URL: https://github.com/apache/spark/pull/49318#discussion_r1901446567


##########
python/pyspark/sql/connect/functions/builtin.py:
##########
@@ -70,7 +70,9 @@
     ArrayType,
     StringType,
 )
-from pyspark.sql.utils import enum_to_value as _enum_to_value
+from pyspark.sql.utils import (

Review Comment:
   it seems this change is not necessary



##########
python/pyspark/sql/functions/builtin.py:
##########
@@ -253,6 +255,32 @@ def lit(col: Any) -> Column:
     +------------------+-------+-----------------+--------------------+
     |     [true, false]|     []|       [1.5, 0.1]|           [a, b, c]|
     +------------------+-------+-----------------+--------------------+
+
+    Example 7: Creating a literal column as a map from a dict.
+        if spark.sql.pyspark.inferNestedDictAsStruct is False
+
+    >>> import pyspark.sql.functions as sf
+    >>> spark.range(1).select(
+    ...    sf.lit({"a": 1, "b": 2}).alias("map_col")
+    ... ).show() # doctest: +SKIP

Review Comment:
   we can enable the two doctests by applying `spark.conf.set` and `spark.conf.unset`



##########
python/pyspark/sql/connect/functions/builtin.py:
##########
@@ -276,6 +279,23 @@ def lit(col: Any) -> Column:
                 messageParameters={"dtype": col.dtype.name},
             )
         return array(*[lit(c) for c in col]).cast(ArrayType(dt))
+    elif isinstance(col, dict):
+        if any(isinstance(c, Column) for c in col.values()):
+            raise PySparkValueError(
+                errorClass="COLUMN_IN_DICT", messageParameters={"func_name": "lit"}
+            )
+        from pyspark.sql import SparkSession
+
+        spark = SparkSession.getActiveSession()
+        dict_as_struct = (
+            spark.conf.get("spark.sql.pyspark.inferNestedDictAsStruct.enabled")

Review Comment:
   this triggers a `Config` RPC, for nested cases, it will re-trigger multiple times.
   We should cache the config, and make sure only at most one invocation.



##########
python/pyspark/sql/tests/test_functions.py:
##########
@@ -1316,6 +1316,65 @@ def test_lit_list(self):
             messageParameters={"func_name": "lit"},
         )
 
+    # SPARK-48665: added support for dict type
+    def test_lit_dict_struct(self):

Review Comment:
   shall we add a test for nested struct? e.g. `{"a": {"x": 1}, "b": {"y": 2}}`



##########
python/pyspark/sql/functions/builtin.py:
##########
@@ -12843,7 +12890,7 @@ def to_unix_timestamp(
 
     Example 3: Using a format column to represent different formats.
 
-    >>> import pyspark.sql.functions as sf
+    >>> import pyspark.sql.functions as sff

Review Comment:
   why need this change?



##########
python/pyspark/sql/functions/builtin.py:
##########
@@ -262,6 +290,25 @@ def lit(col: Any) -> Column:
                 errorClass="COLUMN_IN_LIST", messageParameters={"func_name": "lit"}
             )
         return array(*[lit(item) for item in col])
+    elif isinstance(col, dict):
+        # Skip checking if the keys are column as Columns are not hashable
+        # and cannot be used as dict keys in the first place.
+        if any(isinstance(value, Column) for value in col.values()):
+            raise PySparkValueError(
+                errorClass="COLUMN_IN_DICT", messageParameters={"func_name": "lit"}
+            )
+        from pyspark.sql import SparkSession
+
+        spark = SparkSession.getActiveSession()

Review Comment:
   do we require an active session here? @HyukjinKwon 



##########
python/pyspark/sql/tests/test_functions.py:
##########
@@ -1316,6 +1316,65 @@ def test_lit_list(self):
             messageParameters={"func_name": "lit"},
         )
 
+    # SPARK-48665: added support for dict type
+    def test_lit_dict_struct(self):
+        with self.sql_conf({"spark.sql.pyspark.inferNestedDictAsStruct.enabled": True}):
+            expected_types = StructType(
+                [
+                    StructField("a", IntegerType(), False),
+                    StructField("b", IntegerType(), False),
+                ]
+            )
+            test_dict = {"a": 1, "b": 2}
+            actual = self.spark.range(1).select(F.lit(test_dict).alias("dict_to_struct"))
+            column_type = actual.schema["dict_to_struct"].dataType
+            actual = actual.first()[0]
+            self.assertEqual(column_type, expected_types)
+            self.assertEqual(actual, Row(a=1, b=2))
+
+    # SPARK-48665: added support for dict type
+    def test_lit_dict_map(self):
+        with self.sql_conf({"spark.sql.pyspark.inferNestedDictAsStruct.enabled": False}):
+            test_dict = {"a": 1, "b": 2}
+            actual = self.spark.range(1).select(F.lit(test_dict).alias("dict_to_map"))
+            column_type = actual.schema["dict_to_map"].dataType
+            actual = actual.first()[0]
+            self.assertEqual(column_type, MapType(StringType(), IntegerType(), False))
+            self.assertEqual(actual, test_dict)
+
+            test_dict = {"a": {"1": 1}, "b": {"2": 2}}
+            actual = self.spark.range(1).select(F.lit(test_dict)).first()[0]
+            self.assertEqual(actual, test_dict)
+
+        with self.sql_conf(
+            {
+                "spark.sql.ansi.enabled": False,

Review Comment:
   how `ansi` affect this feature?



##########
python/pyspark/sql/tests/test_functions.py:
##########
@@ -1316,6 +1316,65 @@ def test_lit_list(self):
             messageParameters={"func_name": "lit"},
         )
 
+    # SPARK-48665: added support for dict type
+    def test_lit_dict_struct(self):
+        with self.sql_conf({"spark.sql.pyspark.inferNestedDictAsStruct.enabled": True}):
+            expected_types = StructType(
+                [
+                    StructField("a", IntegerType(), False),
+                    StructField("b", IntegerType(), False),
+                ]
+            )
+            test_dict = {"a": 1, "b": 2}
+            actual = self.spark.range(1).select(F.lit(test_dict).alias("dict_to_struct"))
+            column_type = actual.schema["dict_to_struct"].dataType
+            actual = actual.first()[0]
+            self.assertEqual(column_type, expected_types)
+            self.assertEqual(actual, Row(a=1, b=2))
+
+    # SPARK-48665: added support for dict type
+    def test_lit_dict_map(self):
+        with self.sql_conf({"spark.sql.pyspark.inferNestedDictAsStruct.enabled": False}):
+            test_dict = {"a": 1, "b": 2}
+            actual = self.spark.range(1).select(F.lit(test_dict).alias("dict_to_map"))
+            column_type = actual.schema["dict_to_map"].dataType
+            actual = actual.first()[0]
+            self.assertEqual(column_type, MapType(StringType(), IntegerType(), False))
+            self.assertEqual(actual, test_dict)
+
+            test_dict = {"a": {"1": 1}, "b": {"2": 2}}
+            actual = self.spark.range(1).select(F.lit(test_dict)).first()[0]
+            self.assertEqual(actual, test_dict)

Review Comment:
   should `actual` be of type `map<string, map<string, int>>` ?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org