You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "bojana-db (via GitHub)" <gi...@apache.org> on 2026/06/29 15:11:46 UTC

[PR] Add `variant_strip_nulls` expression [spark]

bojana-db opened a new pull request, #56864:
URL: https://github.com/apache/spark/pull/56864

   <!--
   Thanks for sending a pull request!  Here are some tips for you:
     1. If this is your first time, please read our contributor guidelines: https://spark.apache.org/contributing.html
     2. Ensure you have added or run the appropriate tests for your PR: https://spark.apache.org/developer-tools.html
     3. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP][SPARK-XXXX] Your PR title ...'.
     4. Be sure to keep the PR description updated to reflect all changes.
     5. Please write your PR title to summarize what this PR proposes.
     6. If possible, provide a concise example to reproduce the issue for a faster review.
     7. If you want to add a new configuration, please read the guideline first for naming configurations in
        'core/src/main/scala/org/apache/spark/internal/config/ConfigEntry.scala'.
     8. If you want to add or modify an error type or message, please read the guideline first in
        'common/utils/src/main/resources/error/README.md'.
   -->
   
   ### What changes were proposed in this pull request?
   Adds the SQL function` variant_strip_nulls(v[, includeArrays])`, which recursively removes Variant null fields from objects (and, by default, Variant null elements from arrays) in a Variant value.
   
   Details:
   - Object path: a field whose value is a Variant null (the JSON null literal) is removed entirely; recursion walks nested objects and arrays at all levels;
   - includeArrays (BOOLEAN, default true): when true, Variant null elements are also removed from arrays; when false, array null elements are kept, but null fields of objects nested anywhere (including inside arrays) are still stripped;
   - Empty containers are preserved: an object/array emptied by stripping stays {} / []; the parent is never collapsed to NULL;
   - Non-container inputs — scalars and a top-level Variant null (parse_json('null')) — are returned unchanged;
   - NULL intolerant: any NULL argument returns NULL.
   
   
   ### Why are the changes needed?
   <!--
   Please clarify why the changes are needed. For instance,
     1. If you propose a new API, clarify the use case for a new API.
     2. If you fix a bug, you can clarify why it is a bug.
   -->
   There is no built-in way to drop Variant null entries from a Variant; today users must convert it to another type (e.g. a map) and back.
   
   
   ### Does this PR introduce _any_ user-facing change?
   Yes, a new SQL function (and Scala/Python `functions` API.
   
   ### How was this patch tested?
   Unit tests.
   
   
   ### Was this patch authored or co-authored using generative AI tooling?
   Generated-by: Claude Code with Claude Opus 4.8
   


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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3735132616


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/FunctionRegistry.scala:
##########
@@ -996,6 +996,7 @@ object FunctionRegistry {
     expressionBuilder("try_variant_set", TryVariantSetExpressionBuilder),
     expressionBuilder("variant_array_append", VariantArrayAppendExpressionBuilder),
     expressionBuilder("try_variant_array_append", TryVariantArrayAppendExpressionBuilder),
+    expression[VariantStripNulls]("variant_strip_nulls"),

Review Comment:
   Registering with expression[VariantStripNulls] means variant_strip_nulls(v, include_arrays => false) fails — FunctionRegistry.expression[T] throws namedArgumentsNotSupported when it sees a NamedArgumentExpression.
   
   variant_set / try_variant_set, the closest analogue (optional trailing boolean), register through expressionBuilder and declare the argument in a FunctionSignature, which is what makes create_if_missing => false legal:
   ```
   // variantExpressions.scala:1196-1198
   val createIfMissingArg =
     InputParameter("create_if_missing", Some(Literal.create(true, BooleanType)))
   Some(FunctionSignature(Seq(vArg, pathArg, valArg, createIfMissingArg)))
   ```
   
   Using a VariantStripNullsExpressionBuilder would give named-argument support and let the default live in the signature rather than in the secondary constructor at variantExpressions.scala:1525.



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3740619263


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala:
##########
@@ -1490,6 +1490,92 @@ object VariantArrayAppendExpressionBuilder extends VariantArrayAppendExpressionB
 // scalastyle:on line.size.limit
 object TryVariantArrayAppendExpressionBuilder
     extends VariantArrayAppendExpressionBuilderBase(false)
+case class VariantStripNulls(child: Expression, includeArrays: Expression)
+    extends RuntimeReplaceable
+    with ExpectsInputTypes
+    with BinaryLike[Expression]
+    with QueryErrorsBase {
+
+  override def left: Expression = child
+  override def right: Expression = includeArrays
+
+  override def inputTypes: Seq[AbstractDataType] = Seq(VariantType, BooleanType)
+
+  override def checkInputDataTypes(): TypeCheckResult = {
+    val result = super.checkInputDataTypes()
+    if (result.isFailure) {
+      result
+    } else if (!includeArrays.foldable) {
+      DataTypeMismatch(
+        errorSubClass = "NON_FOLDABLE_INPUT",
+        messageParameters = Map(
+          "inputName" -> toSQLId("include_arrays"),
+          "inputType" -> toSQLType(includeArrays.dataType),
+          "inputExpr" -> toSQLExpr(includeArrays)))
+    } else {
+      TypeCheckResult.TypeCheckSuccess
+    }
+  }
+
+  override lazy val replacement: Expression = StaticInvoke(
+    VariantExpressionEvalUtils.getClass,
+    VariantType,
+    "stripNulls",
+    Seq(child, includeArrays),
+    inputTypes,
+    returnNullable = false)
+
+  override def prettyName: String = "variant_strip_nulls"
+
+  override protected def withNewChildrenInternal(
+      newLeft: Expression, newRight: Expression): VariantStripNulls =
+    copy(child = newLeft, includeArrays = newRight)
+}
+
+// scalastyle:off line.size.limit
+@ExpressionDescription(
+  usage = "_FUNC_(v[, include_arrays]) - Recursively removes object fields and array elements " +
+    "whose value is a variant null, unless `include_arrays` is false, in which case null array " +
+    "elements are kept. Returns NULL if any argument is NULL.",
+  arguments = """
+    Arguments:
+      * v - A variant value to mutate.
+      * include_arrays - An optional boolean (default true). Must be a constant.

Review Comment:
   Also, `strip_in_arrays` sounds a bit better than `include_arrays` here? cc @srielau @harshmotw-db 



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3740617648


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala:
##########
@@ -1490,6 +1490,92 @@ object VariantArrayAppendExpressionBuilder extends VariantArrayAppendExpressionB
 // scalastyle:on line.size.limit
 object TryVariantArrayAppendExpressionBuilder
     extends VariantArrayAppendExpressionBuilderBase(false)
+case class VariantStripNulls(child: Expression, includeArrays: Expression)
+    extends RuntimeReplaceable
+    with ExpectsInputTypes
+    with BinaryLike[Expression]
+    with QueryErrorsBase {
+
+  override def left: Expression = child
+  override def right: Expression = includeArrays
+
+  override def inputTypes: Seq[AbstractDataType] = Seq(VariantType, BooleanType)
+
+  override def checkInputDataTypes(): TypeCheckResult = {
+    val result = super.checkInputDataTypes()
+    if (result.isFailure) {
+      result
+    } else if (!includeArrays.foldable) {
+      DataTypeMismatch(
+        errorSubClass = "NON_FOLDABLE_INPUT",
+        messageParameters = Map(
+          "inputName" -> toSQLId("include_arrays"),
+          "inputType" -> toSQLType(includeArrays.dataType),
+          "inputExpr" -> toSQLExpr(includeArrays)))
+    } else {
+      TypeCheckResult.TypeCheckSuccess
+    }
+  }
+
+  override lazy val replacement: Expression = StaticInvoke(
+    VariantExpressionEvalUtils.getClass,
+    VariantType,
+    "stripNulls",
+    Seq(child, includeArrays),
+    inputTypes,
+    returnNullable = false)
+
+  override def prettyName: String = "variant_strip_nulls"
+
+  override protected def withNewChildrenInternal(
+      newLeft: Expression, newRight: Expression): VariantStripNulls =
+    copy(child = newLeft, includeArrays = newRight)
+}
+
+// scalastyle:off line.size.limit
+@ExpressionDescription(
+  usage = "_FUNC_(v[, include_arrays]) - Recursively removes object fields and array elements " +
+    "whose value is a variant null, unless `include_arrays` is false, in which case null array " +
+    "elements are kept. Returns NULL if any argument is NULL.",
+  arguments = """
+    Arguments:
+      * v - A variant value to mutate.
+      * include_arrays - An optional boolean (default true). Must be a constant.

Review Comment:
   Why default true? PostgreSQL 18 `json_strip_nulls` defaults to false (https://www.postgresql.org/docs/devel/functions-json.html):
   ```
   If strip_in_arrays is true (the default is false), null array elements are also stripped.
   ```



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on PR #56864:
URL: https://github.com/apache/spark/pull/56864#issuecomment-5254574318

   **Merge Summary:**
   - merged into master https://github.com/apache/spark/commit/274049387f96976c1bda1bedca3e6f96894c7e8e
   - merged into branch-4.x https://github.com/apache/spark/commit/6f99005cd5022c4a66278991a7dc94141137271b
   
   *Posted by `merge_spark_pr.py`*


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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3740624751


##########
python/docs/source/reference/pyspark.sql/functions.rst:
##########
@@ -607,6 +607,7 @@ VARIANT Functions
     variant_array_append
     try_variant_array_append
     variant_delete
+    variant_strip_nulls

Review Comment:
   e.g. just pick one position and make sure that all function listings agree



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3740621378


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala:
##########
@@ -1490,6 +1490,92 @@ object VariantArrayAppendExpressionBuilder extends VariantArrayAppendExpressionB
 // scalastyle:on line.size.limit
 object TryVariantArrayAppendExpressionBuilder
     extends VariantArrayAppendExpressionBuilderBase(false)
+case class VariantStripNulls(child: Expression, includeArrays: Expression)

Review Comment:
   ```suggestion
   extends VariantArrayAppendExpressionBuilderBase(false)
   
   case class VariantStripNulls(child: Expression, includeArrays: Expression)
   ```



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "bojana-db (via GitHub)" <gi...@apache.org>.
bojana-db commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3737055597


##########
sql/core/src/test/scala/org/apache/spark/sql/VariantSuite.scala:
##########
@@ -680,6 +680,73 @@ class VariantSuite extends SharedSparkSession with ExpressionEvalHelper {
     }
   }
 
+  test("variant_strip_nulls with literal arguments") {
+    def rows(results: Any*): Seq[Row] = results.map(Row(_))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json('{\"a\": 1, \"b\": null, \"c\": 3}')))"),
+      rows("""{"a":1,"c":3}"""))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json('[1, null, 3]')))"),
+      rows("[1,3]"))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json(" +
+        "'{\"a\": [null, 3, {\"b\": null, \"c\": [null, 1]}], \"d\": null, " +
+        "\"e\": {\"f\": null, \"g\": 2}}')))"),
+      rows("""{"a":[3,{"c":[1]}],"e":{"g":2}}"""))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json(" +
+        "'{\"a\": 100000, \"b\": null, \"c\": 10000000000, \"d\": \"hello world\"}')))"),
+      rows("""{"a":100000,"c":10000000000,"d":"hello world"}"""))
+
+    // include_arrays = false keeps array null elements but still strips null fields of objects.
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(" +
+        "parse_json('[{\"a\": 1, \"b\": null}, null, {\"c\": null, \"d\": 4}]'), false))"),
+      rows("""[{"a":1},null,{"d":4}]"""))
+
+    // Empty containers are preserved.
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json('{\"a\": null}')))"),
+      rows("{}"))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json('[null, null]')))"),
+      rows("[]"))
+
+    // Top-level variant null is unchanged.
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json('null')))"),
+      rows("null"))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(CAST(NULL AS VARIANT)))"),
+      rows(null))
+  }
+
+  test("variant_strip_nulls with dynamic arguments") {

Review Comment:
   Added foldable constraint. Will address `variant_set` also.



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3735145895


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala:
##########
@@ -1490,6 +1490,60 @@ object VariantArrayAppendExpressionBuilder extends VariantArrayAppendExpressionB
 // scalastyle:on line.size.limit
 object TryVariantArrayAppendExpressionBuilder
     extends VariantArrayAppendExpressionBuilderBase(false)
+// scalastyle:off line.size.limit
+@ExpressionDescription(
+  usage = "_FUNC_(v[, includeArrays]) - Recursively removes null fields from variant objects " +
+    "and null elements from arrays, unless `includeArrays` is false, in which case null " +
+    "elements in arrays are kept. Returns NULL if any argument is NULL.",
+  arguments = """
+    Arguments:
+      * v - A variant value to mutate.
+      * includeArrays - An optional boolean (default true).
+  """,
+  examples = """
+    Examples:
+      > SELECT _FUNC_(parse_json('{"a": 1, "b": null, "c": 3}'));
+       {"a":1,"c":3}
+      > SELECT _FUNC_(parse_json('[1, null, 3]'));
+       [1,3]
+      > SELECT _FUNC_(parse_json('{"a": {"b": null, "c": [1, null]}}'));
+       {"a":{"c":[1]}}
+      > SELECT _FUNC_(parse_json('{"a": [1, null], "b": null}'), false);
+       {"a":[1,null]}
+      > SELECT _FUNC_(NULL);
+       NULL
+  """,

Review Comment:
   Two behaviors are specified in the VariantBuilder.stripNulls comment but appear nowhere in the user-facing docs; not in examples, not in the Scala scaladoc (functions.scala:14558-14566), not in the Python docstring (builtin.py:23193-23225):
   
   A container emptied by stripping stays {} / [] and the parent field is retained, rather than collapsing to NULL. {"a": null} yields {}, not NULL.
   A top-level variant null (parse_json('null')) is returned unchanged.
   Both are covered by tests, so they're intentional, they just need to be visible. An example like > SELECT _FUNC_(parse_json('{"a": null}')); → {} would carry most of the weight.
   
   Separately, in the usage string at lines 1495-1497, "removes null fields ... Returns NULL if any argument is NULL" uses "null" in two different senses one sentence apart. Saying variant null (the JSON null literal) in the first sentence would disambiguate, a distinction that matters more in variant code than anywhere else.



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3735141777


##########
python/pyspark/sql/tests/test_functions.py:
##########
@@ -3641,6 +3641,8 @@ def check(resultDf, expected):
             df.select(F.to_json(F.try_variant_array_append(arr, df.arrpath, F.lit(9)))),
             ["[1,2,9]", "[[3,9],4]"],
         )
+        check(df.select(F.to_json(F.variant_strip_nulls(v))), ['{"a":1}', '{"b":2}'])
+        check(df.select(F.to_json(F.variant_strip_nulls(v, False))), ['{"a":1}', '{"b":2}'])

Review Comment:
   v here is parse_json over {"a":1} and {"b":2} — no nulls anywhere in the fixture. Both assertions expect the input back unchanged, so nothing is stripped, and the second line's expected value is identical to the first, meaning include_arrays=False adds no coverage over the default. This confirms wiring but not behavior.
   
   The neighbouring variant_delete checks in this same test do exercise real behavior. A fixture with a null object field and a null array element would make both lines meaningful.



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3735137747


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala:
##########
@@ -1490,6 +1490,60 @@ object VariantArrayAppendExpressionBuilder extends VariantArrayAppendExpressionB
 // scalastyle:on line.size.limit
 object TryVariantArrayAppendExpressionBuilder
     extends VariantArrayAppendExpressionBuilderBase(false)
+// scalastyle:off line.size.limit
+@ExpressionDescription(
+  usage = "_FUNC_(v[, includeArrays]) - Recursively removes null fields from variant objects " +

Review Comment:
   Should we be using snake_case, instead of camelCase?



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3740620886


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala:
##########
@@ -1490,6 +1490,92 @@ object VariantArrayAppendExpressionBuilder extends VariantArrayAppendExpressionB
 // scalastyle:on line.size.limit
 object TryVariantArrayAppendExpressionBuilder
     extends VariantArrayAppendExpressionBuilderBase(false)
+case class VariantStripNulls(child: Expression, includeArrays: Expression)
+    extends RuntimeReplaceable
+    with ExpectsInputTypes
+    with BinaryLike[Expression]
+    with QueryErrorsBase {
+
+  override def left: Expression = child
+  override def right: Expression = includeArrays
+
+  override def inputTypes: Seq[AbstractDataType] = Seq(VariantType, BooleanType)
+
+  override def checkInputDataTypes(): TypeCheckResult = {
+    val result = super.checkInputDataTypes()
+    if (result.isFailure) {
+      result
+    } else if (!includeArrays.foldable) {

Review Comment:
   The value is passed through StaticInvoke and read per row at runtime, so a non-foldable boolean column would work here with no code changes. Could you just please confirm, is this restriction deliberate?
   
   It's also inconsistent with the closest sibling: VariantSet.createIfMissing is a plain QuaternaryExpression child with no foldability check and accepts dynamic expressions, even though its PySpark docstring claims "Must be a constant." So today the family documents the same constraint in two places and enforces it in one.



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b closed pull request #56864: [SPARK-58062][SQL] Add `variant_strip_nulls` expression
URL: https://github.com/apache/spark/pull/56864


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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3740624140


##########
python/docs/source/reference/pyspark.sql/functions.rst:
##########
@@ -607,6 +607,7 @@ VARIANT Functions
     variant_array_append
     try_variant_array_append
     variant_delete
+    variant_strip_nulls

Review Comment:
   Nit: let's use same placement with `python/pyspark/sql/functions/builtin.py`



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3735150847


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala:
##########
@@ -1490,6 +1490,60 @@ object VariantArrayAppendExpressionBuilder extends VariantArrayAppendExpressionB
 // scalastyle:on line.size.limit
 object TryVariantArrayAppendExpressionBuilder
     extends VariantArrayAppendExpressionBuilderBase(false)
+// scalastyle:off line.size.limit
+@ExpressionDescription(
+  usage = "_FUNC_(v[, includeArrays]) - Recursively removes null fields from variant objects " +
+    "and null elements from arrays, unless `includeArrays` is false, in which case null " +
+    "elements in arrays are kept. Returns NULL if any argument is NULL.",
+  arguments = """
+    Arguments:
+      * v - A variant value to mutate.
+      * includeArrays - An optional boolean (default true).
+  """,
+  examples = """
+    Examples:
+      > SELECT _FUNC_(parse_json('{"a": 1, "b": null, "c": 3}'));
+       {"a":1,"c":3}
+      > SELECT _FUNC_(parse_json('[1, null, 3]'));
+       [1,3]
+      > SELECT _FUNC_(parse_json('{"a": {"b": null, "c": [1, null]}}'));
+       {"a":{"c":[1]}}
+      > SELECT _FUNC_(parse_json('{"a": [1, null], "b": null}'), false);
+       {"a":[1,null]}
+      > SELECT _FUNC_(NULL);
+       NULL
+  """,
+  since = "4.3.0",
+  group = "variant_funcs"
+)
+// scalastyle:on line.size.limit
+case class VariantStripNulls(child: Expression, includeArrays: Expression)
+    extends RuntimeReplaceable
+    with ExpectsInputTypes
+    with BinaryLike[Expression] {
+
+  def this(child: Expression) = this(child, Literal(true))
+
+  override def left: Expression = child
+  override def right: Expression = includeArrays
+
+  override def dataType: DataType = VariantType

Review Comment:
   Is this redundant?



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3740618519


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala:
##########
@@ -1490,6 +1490,92 @@ object VariantArrayAppendExpressionBuilder extends VariantArrayAppendExpressionB
 // scalastyle:on line.size.limit
 object TryVariantArrayAppendExpressionBuilder
     extends VariantArrayAppendExpressionBuilderBase(false)
+case class VariantStripNulls(child: Expression, includeArrays: Expression)
+    extends RuntimeReplaceable
+    with ExpectsInputTypes
+    with BinaryLike[Expression]
+    with QueryErrorsBase {
+
+  override def left: Expression = child
+  override def right: Expression = includeArrays
+
+  override def inputTypes: Seq[AbstractDataType] = Seq(VariantType, BooleanType)
+
+  override def checkInputDataTypes(): TypeCheckResult = {
+    val result = super.checkInputDataTypes()
+    if (result.isFailure) {
+      result
+    } else if (!includeArrays.foldable) {
+      DataTypeMismatch(
+        errorSubClass = "NON_FOLDABLE_INPUT",
+        messageParameters = Map(
+          "inputName" -> toSQLId("include_arrays"),
+          "inputType" -> toSQLType(includeArrays.dataType),
+          "inputExpr" -> toSQLExpr(includeArrays)))
+    } else {
+      TypeCheckResult.TypeCheckSuccess
+    }
+  }
+
+  override lazy val replacement: Expression = StaticInvoke(
+    VariantExpressionEvalUtils.getClass,
+    VariantType,
+    "stripNulls",
+    Seq(child, includeArrays),
+    inputTypes,
+    returnNullable = false)
+
+  override def prettyName: String = "variant_strip_nulls"
+
+  override protected def withNewChildrenInternal(
+      newLeft: Expression, newRight: Expression): VariantStripNulls =
+    copy(child = newLeft, includeArrays = newRight)
+}
+
+// scalastyle:off line.size.limit
+@ExpressionDescription(
+  usage = "_FUNC_(v[, include_arrays]) - Recursively removes object fields and array elements " +
+    "whose value is a variant null, unless `include_arrays` is false, in which case null array " +
+    "elements are kept. Returns NULL if any argument is NULL.",
+  arguments = """
+    Arguments:
+      * v - A variant value to mutate.
+      * include_arrays - An optional boolean (default true). Must be a constant.

Review Comment:
   Aslo, note possible issues when stripping array elements ends up renumbering the array. After variant_strip_nulls(v) with the current default, any positional path a user holds ($.a[1]) silently points at different data. That's a surprising side effect for a function that reads like it only removes nulls, so it seems better as opt-in?



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on PR #56864:
URL: https://github.com/apache/spark/pull/56864#issuecomment-5252178012

   @bojana-db Please resolve conflicts.


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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on PR #56864:
URL: https://github.com/apache/spark/pull/56864#issuecomment-5252176570

   LGTM, thank you @bojana-db for resolving all comments. Also, thank you @harshmotw-db for review!


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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3740622616


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala:
##########
@@ -1490,6 +1490,92 @@ object VariantArrayAppendExpressionBuilder extends VariantArrayAppendExpressionB
 // scalastyle:on line.size.limit
 object TryVariantArrayAppendExpressionBuilder
     extends VariantArrayAppendExpressionBuilderBase(false)
+case class VariantStripNulls(child: Expression, includeArrays: Expression)
+    extends RuntimeReplaceable
+    with ExpectsInputTypes
+    with BinaryLike[Expression]
+    with QueryErrorsBase {
+
+  override def left: Expression = child
+  override def right: Expression = includeArrays
+
+  override def inputTypes: Seq[AbstractDataType] = Seq(VariantType, BooleanType)
+
+  override def checkInputDataTypes(): TypeCheckResult = {
+    val result = super.checkInputDataTypes()
+    if (result.isFailure) {
+      result
+    } else if (!includeArrays.foldable) {
+      DataTypeMismatch(
+        errorSubClass = "NON_FOLDABLE_INPUT",
+        messageParameters = Map(
+          "inputName" -> toSQLId("include_arrays"),
+          "inputType" -> toSQLType(includeArrays.dataType),
+          "inputExpr" -> toSQLExpr(includeArrays)))
+    } else {
+      TypeCheckResult.TypeCheckSuccess
+    }
+  }
+
+  override lazy val replacement: Expression = StaticInvoke(
+    VariantExpressionEvalUtils.getClass,
+    VariantType,
+    "stripNulls",
+    Seq(child, includeArrays),
+    inputTypes,
+    returnNullable = false)
+
+  override def prettyName: String = "variant_strip_nulls"
+
+  override protected def withNewChildrenInternal(
+      newLeft: Expression, newRight: Expression): VariantStripNulls =
+    copy(child = newLeft, includeArrays = newRight)
+}
+
+// scalastyle:off line.size.limit
+@ExpressionDescription(
+  usage = "_FUNC_(v[, include_arrays]) - Recursively removes object fields and array elements " +
+    "whose value is a variant null, unless `include_arrays` is false, in which case null array " +
+    "elements are kept. Returns NULL if any argument is NULL.",
+  arguments = """
+    Arguments:
+      * v - A variant value to mutate.

Review Comment:
   https://github.com/apache/spark/pull/56864/changes#r3740622197



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3735148947


##########
sql/core/src/test/scala/org/apache/spark/sql/VariantSuite.scala:
##########
@@ -680,6 +680,73 @@ class VariantSuite extends SharedSparkSession with ExpressionEvalHelper {
     }
   }
 
+  test("variant_strip_nulls with literal arguments") {
+    def rows(results: Any*): Seq[Row] = results.map(Row(_))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json('{\"a\": 1, \"b\": null, \"c\": 3}')))"),
+      rows("""{"a":1,"c":3}"""))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json('[1, null, 3]')))"),
+      rows("[1,3]"))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json(" +
+        "'{\"a\": [null, 3, {\"b\": null, \"c\": [null, 1]}], \"d\": null, " +
+        "\"e\": {\"f\": null, \"g\": 2}}')))"),
+      rows("""{"a":[3,{"c":[1]}],"e":{"g":2}}"""))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json(" +
+        "'{\"a\": 100000, \"b\": null, \"c\": 10000000000, \"d\": \"hello world\"}')))"),
+      rows("""{"a":100000,"c":10000000000,"d":"hello world"}"""))
+
+    // include_arrays = false keeps array null elements but still strips null fields of objects.
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(" +
+        "parse_json('[{\"a\": 1, \"b\": null}, null, {\"c\": null, \"d\": 4}]'), false))"),
+      rows("""[{"a":1},null,{"d":4}]"""))
+
+    // Empty containers are preserved.
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json('{\"a\": null}')))"),
+      rows("{}"))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json('[null, null]')))"),
+      rows("[]"))
+
+    // Top-level variant null is unchanged.
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json('null')))"),
+      rows("null"))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(CAST(NULL AS VARIANT)))"),
+      rows(null))
+  }
+
+  test("variant_strip_nulls with dynamic arguments") {

Review Comment:
   Because the flag goes through StaticInvoke rather than being extracted at planning time, variant_strip_nulls(v, some_boolean_column) is accepted and evaluated per row. That's arguably a feature, but the test named "with dynamic arguments" only varies the variant input; the boolean is a literal in both checkAnswer calls (lines 741 and 746), so the per-row path is never covered.
   
   Either add a case with a boolean column, or decide the flag should be foldable-only and reject non-literals. Worth being deliberate about, since it's the kind of thing that gets locked in at release. If literals are the intent, the test name could say so.



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3735153416


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala:
##########
@@ -1490,6 +1490,60 @@ object VariantArrayAppendExpressionBuilder extends VariantArrayAppendExpressionB
 // scalastyle:on line.size.limit
 object TryVariantArrayAppendExpressionBuilder
     extends VariantArrayAppendExpressionBuilderBase(false)
+// scalastyle:off line.size.limit
+@ExpressionDescription(
+  usage = "_FUNC_(v[, includeArrays]) - Recursively removes null fields from variant objects " +
+    "and null elements from arrays, unless `includeArrays` is false, in which case null " +
+    "elements in arrays are kept. Returns NULL if any argument is NULL.",
+  arguments = """
+    Arguments:
+      * v - A variant value to mutate.
+      * includeArrays - An optional boolean (default true).
+  """,
+  examples = """
+    Examples:
+      > SELECT _FUNC_(parse_json('{"a": 1, "b": null, "c": 3}'));
+       {"a":1,"c":3}
+      > SELECT _FUNC_(parse_json('[1, null, 3]'));
+       [1,3]
+      > SELECT _FUNC_(parse_json('{"a": {"b": null, "c": [1, null]}}'));
+       {"a":{"c":[1]}}
+      > SELECT _FUNC_(parse_json('{"a": [1, null], "b": null}'), false);
+       {"a":[1,null]}
+      > SELECT _FUNC_(NULL);
+       NULL
+  """,
+  since = "4.3.0",
+  group = "variant_funcs"
+)
+// scalastyle:on line.size.limit
+case class VariantStripNulls(child: Expression, includeArrays: Expression)
+    extends RuntimeReplaceable
+    with ExpectsInputTypes
+    with BinaryLike[Expression] {
+
+  def this(child: Expression) = this(child, Literal(true))
+
+  override def left: Expression = child
+  override def right: Expression = includeArrays
+
+  override def dataType: DataType = VariantType
+  override def inputTypes: Seq[AbstractDataType] = Seq(VariantType, BooleanType)
+
+  override lazy val replacement: Expression = StaticInvoke(
+    VariantExpressionEvalUtils.getClass,
+    VariantType,

Review Comment:
   We probably don't need the dataType override then (https://github.com/apache/spark/pull/56864/changes#r3735150847).



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "bojana-db (via GitHub)" <gi...@apache.org>.
bojana-db commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3749024026


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala:
##########
@@ -1490,6 +1490,92 @@ object VariantArrayAppendExpressionBuilder extends VariantArrayAppendExpressionB
 // scalastyle:on line.size.limit
 object TryVariantArrayAppendExpressionBuilder
     extends VariantArrayAppendExpressionBuilderBase(false)
+case class VariantStripNulls(child: Expression, includeArrays: Expression)
+    extends RuntimeReplaceable
+    with ExpectsInputTypes
+    with BinaryLike[Expression]
+    with QueryErrorsBase {
+
+  override def left: Expression = child
+  override def right: Expression = includeArrays
+
+  override def inputTypes: Seq[AbstractDataType] = Seq(VariantType, BooleanType)
+
+  override def checkInputDataTypes(): TypeCheckResult = {
+    val result = super.checkInputDataTypes()
+    if (result.isFailure) {
+      result
+    } else if (!includeArrays.foldable) {

Review Comment:
   Yes, it is deliberate. It makes sense for a flag to be foldable as it represents the function behaviour mode and in a sense it can be seen as two different functions. Regarding `variant_set`, restriction is added in https://github.com/apache/spark/pull/57855.



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "bojana-db (via GitHub)" <gi...@apache.org>.
bojana-db commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3748987498


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala:
##########
@@ -1490,6 +1490,92 @@ object VariantArrayAppendExpressionBuilder extends VariantArrayAppendExpressionB
 // scalastyle:on line.size.limit
 object TryVariantArrayAppendExpressionBuilder
     extends VariantArrayAppendExpressionBuilderBase(false)
+case class VariantStripNulls(child: Expression, includeArrays: Expression)
+    extends RuntimeReplaceable
+    with ExpectsInputTypes
+    with BinaryLike[Expression]
+    with QueryErrorsBase {
+
+  override def left: Expression = child
+  override def right: Expression = includeArrays
+
+  override def inputTypes: Seq[AbstractDataType] = Seq(VariantType, BooleanType)
+
+  override def checkInputDataTypes(): TypeCheckResult = {
+    val result = super.checkInputDataTypes()
+    if (result.isFailure) {
+      result
+    } else if (!includeArrays.foldable) {
+      DataTypeMismatch(
+        errorSubClass = "NON_FOLDABLE_INPUT",
+        messageParameters = Map(
+          "inputName" -> toSQLId("include_arrays"),
+          "inputType" -> toSQLType(includeArrays.dataType),
+          "inputExpr" -> toSQLExpr(includeArrays)))
+    } else {
+      TypeCheckResult.TypeCheckSuccess
+    }
+  }
+
+  override lazy val replacement: Expression = StaticInvoke(
+    VariantExpressionEvalUtils.getClass,
+    VariantType,
+    "stripNulls",
+    Seq(child, includeArrays),
+    inputTypes,
+    returnNullable = false)
+
+  override def prettyName: String = "variant_strip_nulls"
+
+  override protected def withNewChildrenInternal(
+      newLeft: Expression, newRight: Expression): VariantStripNulls =
+    copy(child = newLeft, includeArrays = newRight)
+}
+
+// scalastyle:off line.size.limit
+@ExpressionDescription(
+  usage = "_FUNC_(v[, include_arrays]) - Recursively removes object fields and array elements " +
+    "whose value is a variant null, unless `include_arrays` is false, in which case null array " +
+    "elements are kept. Returns NULL if any argument is NULL.",
+  arguments = """
+    Arguments:
+      * v - A variant value to mutate.
+      * include_arrays - An optional boolean (default true). Must be a constant.

Review Comment:
   `variant_strip_nulls` mirrors BigQuery's [JSON_STRIP_NULLS](https://docs.cloud.google.com/bigquery/docs/reference/standard-sql/json_functions#json_strip_nulls), where `include_arrays` defaults to `TRUE`, so name and default both match BigQuery. PostgreSQL's `strip_in_arrays=false` is a backward-compat default (arrays were untouched before PG 18), not an analytics preference. BigQuery frames the function as data compaction ( ["JSON_STRIP_NULLS compresses the data by removing JSON nulls ... helpful for reducing data size during exports"](https://cloud.google.com/blog/products/data-analytics/announcing-new-sql-functions-for-json-in-bigquery) ) which makes sense fot DW/analytics workload and for that use case you generally want array nulls stripped too.



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "bojana-db (via GitHub)" <gi...@apache.org>.
bojana-db commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3737055597


##########
sql/core/src/test/scala/org/apache/spark/sql/VariantSuite.scala:
##########
@@ -680,6 +680,73 @@ class VariantSuite extends SharedSparkSession with ExpressionEvalHelper {
     }
   }
 
+  test("variant_strip_nulls with literal arguments") {
+    def rows(results: Any*): Seq[Row] = results.map(Row(_))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json('{\"a\": 1, \"b\": null, \"c\": 3}')))"),
+      rows("""{"a":1,"c":3}"""))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json('[1, null, 3]')))"),
+      rows("[1,3]"))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json(" +
+        "'{\"a\": [null, 3, {\"b\": null, \"c\": [null, 1]}], \"d\": null, " +
+        "\"e\": {\"f\": null, \"g\": 2}}')))"),
+      rows("""{"a":[3,{"c":[1]}],"e":{"g":2}}"""))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json(" +
+        "'{\"a\": 100000, \"b\": null, \"c\": 10000000000, \"d\": \"hello world\"}')))"),
+      rows("""{"a":100000,"c":10000000000,"d":"hello world"}"""))
+
+    // include_arrays = false keeps array null elements but still strips null fields of objects.
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(" +
+        "parse_json('[{\"a\": 1, \"b\": null}, null, {\"c\": null, \"d\": 4}]'), false))"),
+      rows("""[{"a":1},null,{"d":4}]"""))
+
+    // Empty containers are preserved.
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json('{\"a\": null}')))"),
+      rows("{}"))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json('[null, null]')))"),
+      rows("[]"))
+
+    // Top-level variant null is unchanged.
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(parse_json('null')))"),
+      rows("null"))
+
+    checkAnswer(
+      sql("SELECT to_json(variant_strip_nulls(CAST(NULL AS VARIANT)))"),
+      rows(null))
+  }
+
+  test("variant_strip_nulls with dynamic arguments") {

Review Comment:
   Added foldable constraint.



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "bojana-db (via GitHub)" <gi...@apache.org>.
bojana-db commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3737047094


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala:
##########
@@ -1490,6 +1490,60 @@ object VariantArrayAppendExpressionBuilder extends VariantArrayAppendExpressionB
 // scalastyle:on line.size.limit
 object TryVariantArrayAppendExpressionBuilder
     extends VariantArrayAppendExpressionBuilderBase(false)
+// scalastyle:off line.size.limit
+@ExpressionDescription(
+  usage = "_FUNC_(v[, includeArrays]) - Recursively removes null fields from variant objects " +
+    "and null elements from arrays, unless `includeArrays` is false, in which case null " +
+    "elements in arrays are kept. Returns NULL if any argument is NULL.",
+  arguments = """
+    Arguments:
+      * v - A variant value to mutate.
+      * includeArrays - An optional boolean (default true).
+  """,
+  examples = """
+    Examples:
+      > SELECT _FUNC_(parse_json('{"a": 1, "b": null, "c": 3}'));
+       {"a":1,"c":3}
+      > SELECT _FUNC_(parse_json('[1, null, 3]'));
+       [1,3]
+      > SELECT _FUNC_(parse_json('{"a": {"b": null, "c": [1, null]}}'));
+       {"a":{"c":[1]}}
+      > SELECT _FUNC_(parse_json('{"a": [1, null], "b": null}'), false);
+       {"a":[1,null]}
+      > SELECT _FUNC_(NULL);
+       NULL
+  """,

Review Comment:
   Added examples and edited null references in usage section.



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3740621951


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala:
##########
@@ -1490,6 +1490,92 @@ object VariantArrayAppendExpressionBuilder extends VariantArrayAppendExpressionB
 // scalastyle:on line.size.limit
 object TryVariantArrayAppendExpressionBuilder
     extends VariantArrayAppendExpressionBuilderBase(false)
+case class VariantStripNulls(child: Expression, includeArrays: Expression)
+    extends RuntimeReplaceable
+    with ExpectsInputTypes
+    with BinaryLike[Expression]
+    with QueryErrorsBase {
+
+  override def left: Expression = child
+  override def right: Expression = includeArrays
+
+  override def inputTypes: Seq[AbstractDataType] = Seq(VariantType, BooleanType)
+
+  override def checkInputDataTypes(): TypeCheckResult = {
+    val result = super.checkInputDataTypes()
+    if (result.isFailure) {
+      result
+    } else if (!includeArrays.foldable) {
+      DataTypeMismatch(
+        errorSubClass = "NON_FOLDABLE_INPUT",
+        messageParameters = Map(
+          "inputName" -> toSQLId("include_arrays"),
+          "inputType" -> toSQLType(includeArrays.dataType),
+          "inputExpr" -> toSQLExpr(includeArrays)))
+    } else {
+      TypeCheckResult.TypeCheckSuccess
+    }
+  }
+
+  override lazy val replacement: Expression = StaticInvoke(
+    VariantExpressionEvalUtils.getClass,
+    VariantType,
+    "stripNulls",
+    Seq(child, includeArrays),
+    inputTypes,
+    returnNullable = false)
+
+  override def prettyName: String = "variant_strip_nulls"
+
+  override protected def withNewChildrenInternal(
+      newLeft: Expression, newRight: Expression): VariantStripNulls =
+    copy(child = newLeft, includeArrays = newRight)
+}
+
+// scalastyle:off line.size.limit
+@ExpressionDescription(
+  usage = "_FUNC_(v[, include_arrays]) - Recursively removes object fields and array elements " +
+    "whose value is a variant null, unless `include_arrays` is false, in which case null array " +
+    "elements are kept. Returns NULL if any argument is NULL.",
+  arguments = """
+    Arguments:
+      * v - A variant value to mutate.

Review Comment:
   Variants are immutable and the function returns a new value.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/variant/variantExpressions.scala:
##########
@@ -1490,6 +1490,92 @@ object VariantArrayAppendExpressionBuilder extends VariantArrayAppendExpressionB
 // scalastyle:on line.size.limit
 object TryVariantArrayAppendExpressionBuilder
     extends VariantArrayAppendExpressionBuilderBase(false)
+case class VariantStripNulls(child: Expression, includeArrays: Expression)
+    extends RuntimeReplaceable
+    with ExpectsInputTypes
+    with BinaryLike[Expression]
+    with QueryErrorsBase {
+
+  override def left: Expression = child
+  override def right: Expression = includeArrays
+
+  override def inputTypes: Seq[AbstractDataType] = Seq(VariantType, BooleanType)
+
+  override def checkInputDataTypes(): TypeCheckResult = {
+    val result = super.checkInputDataTypes()
+    if (result.isFailure) {
+      result
+    } else if (!includeArrays.foldable) {
+      DataTypeMismatch(
+        errorSubClass = "NON_FOLDABLE_INPUT",
+        messageParameters = Map(
+          "inputName" -> toSQLId("include_arrays"),
+          "inputType" -> toSQLType(includeArrays.dataType),
+          "inputExpr" -> toSQLExpr(includeArrays)))
+    } else {
+      TypeCheckResult.TypeCheckSuccess
+    }
+  }
+
+  override lazy val replacement: Expression = StaticInvoke(
+    VariantExpressionEvalUtils.getClass,
+    VariantType,
+    "stripNulls",
+    Seq(child, includeArrays),
+    inputTypes,
+    returnNullable = false)
+
+  override def prettyName: String = "variant_strip_nulls"
+
+  override protected def withNewChildrenInternal(
+      newLeft: Expression, newRight: Expression): VariantStripNulls =
+    copy(child = newLeft, includeArrays = newRight)
+}
+
+// scalastyle:off line.size.limit
+@ExpressionDescription(
+  usage = "_FUNC_(v[, include_arrays]) - Recursively removes object fields and array elements " +
+    "whose value is a variant null, unless `include_arrays` is false, in which case null array " +
+    "elements are kept. Returns NULL if any argument is NULL.",
+  arguments = """
+    Arguments:
+      * v - A variant value to mutate.

Review Comment:
   ```suggestion
         * v - The variant value to strip.
   ```



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


Re: [PR] [SPARK-58062][SQL] Add `variant_strip_nulls` expression [spark]

Posted by "uros-b (via GitHub)" <gi...@apache.org>.
uros-b commented on code in PR #56864:
URL: https://github.com/apache/spark/pull/56864#discussion_r3740623108


##########
common/variant/src/main/java/org/apache/spark/types/variant/VariantBuilder.java:
##########
@@ -171,6 +171,16 @@ public static Variant arrayAppendAtPath(Variant v, PathSegment[] segments, Varia
     return builder.result();
   }
 
+  // Return a new variant with null-valued object fields removed, recursing into nested objects
+  // and arrays. When `includeArrays` is true, null array elements are removed too; when false,
+  // arrays keep their nulls but objects inside them are still cleaned. Empty containers and a
+  // top-level variant null are left unchanged. The result is always rebuilt with fresh metadata.

Review Comment:
   "Empty containers ... are left unchanged" reads as if the guarantee only covers containers that were already empty. The more useful guarantee is that a container emptied by stripping is preserved as {} / [] rather than collapsed to null; worth saying explicitly, since that's exactly what the tests at VariantExpressionSuite pin down.



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