-
Notifications
You must be signed in to change notification settings - Fork 321
feat: support Spark expression json_array_length #4365
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kazantsev-maksim
wants to merge
47
commits into
apache:main
Choose a base branch
from
kazantsev-maksim:json_array_length
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
47 commits
Select commit
Hold shift + click to select a range
768b3e9
impl map_from_entries
c68c342
Revert "impl map_from_entries"
d887555
Merge branch 'apache:main' into main
kazantsev-maksim 231aa90
Merge branch 'apache:main' into main
kazantsev-maksim 9500bbb
Merge branch 'apache:main' into main
kazantsev-maksim 9577481
Merge branch 'apache:main' into main
kazantsev-maksim 3791557
Merge branch 'apache:main' into main
kazantsev-maksim 7c2f082
Merge branch 'apache:main' into main
kazantsev-maksim 609a605
Merge branch 'apache:main' into main
kazantsev-maksim a151b2c
Merge branch 'apache:main' into main
kazantsev-maksim ad3e7f5
Merge branch 'apache:main' into main
kazantsev-maksim ea92e4b
Merge branch 'apache:main' into main
kazantsev-maksim 8dfeca3
Merge branch 'apache:main' into main
kazantsev-maksim 559741e
Merge branch 'apache:main' into main
kazantsev-maksim ebda14e
Merge branch 'apache:main' into main
kazantsev-maksim 408152e
Merge branch 'apache:main' into main
kazantsev-maksim d7857b2
Merge branch 'apache:main' into main
kazantsev-maksim aef41be
Merge branch 'apache:main' into main
kazantsev-maksim 5ac1c58
Merge branch 'apache:main' into main
kazantsev-maksim 9ae8e23
Merge branch 'apache:main' into main
kazantsev-maksim 5ca3888
Merge branch 'apache:main' into main
kazantsev-maksim 160a817
Merge branch 'apache:main' into main
kazantsev-maksim 88fc313
Merge branch 'apache:main' into main
kazantsev-maksim e14c180
Merge branch 'apache:main' into main
kazantsev-maksim 610a885
Merge branch 'apache:main' into main
kazantsev-maksim f8acb2c
Merge branch 'apache:main' into main
kazantsev-maksim ec94897
Merge branch 'apache:main' into main
kazantsev-maksim 43405e4
Merge branch 'apache:main' into main
kazantsev-maksim 47b4915
Merge branch 'apache:main' into main
kazantsev-maksim 26e2682
Merge branch 'apache:main' into main
kazantsev-maksim 6cb5f07
Merge branch 'apache:main' into main
kazantsev-maksim ec194fb
Merge branch 'apache:main' into main
kazantsev-maksim 256fccb
Merge branch 'apache:main' into main
kazantsev-maksim 912c8f9
Merge branch 'apache:main' into main
kazantsev-maksim 561a664
Merge branch 'apache:main' into main
kazantsev-maksim d926ef4
Merge branch 'apache:main' into main
kazantsev-maksim 671412c
Merge branch 'apache:main' into main
kazantsev-maksim c9f52d1
Merge branch 'apache:main' into main
kazantsev-maksim 67f72d9
Merge branch 'apache:main' into main
kazantsev-maksim 314e594
Merge branch 'apache:main' into main
kazantsev-maksim ac8292f
Merge branch 'apache:main' into main
kazantsev-maksim c9c140e
Merge branch 'apache:main' into main
kazantsev-maksim decca58
Merge branch 'apache:main' into main
kazantsev-maksim 0919b33
Merge branch 'apache:main' into main
kazantsev-maksim 21a5771
WORK
57076f4
feat: impl json_array_length
0dfa19c
Merge branch 'main' into json_array_length
kazantsev-maksim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,137 @@ | ||
| // 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. | ||
|
|
||
| use arrow::array::{Array, ArrayRef, Int32Builder}; | ||
| use arrow::datatypes::DataType; | ||
| use datafusion::common::cast::as_string_array; | ||
| use datafusion::common::{exec_err, Result, ScalarValue}; | ||
| use datafusion::logical_expr::{ | ||
| ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility, | ||
| }; | ||
|
|
||
| use std::any::Any; | ||
| use std::sync::Arc; | ||
|
|
||
| #[derive(Debug, PartialEq, Eq, Hash)] | ||
| pub struct JsonArrayLength { | ||
| signature: Signature, | ||
| } | ||
|
|
||
| impl Default for JsonArrayLength { | ||
| fn default() -> Self { | ||
| Self::new() | ||
| } | ||
| } | ||
|
|
||
| impl JsonArrayLength { | ||
| pub fn new() -> Self { | ||
| Self { | ||
| signature: Signature::variadic(vec![DataType::Utf8], Volatility::Immutable), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl ScalarUDFImpl for JsonArrayLength { | ||
| fn as_any(&self) -> &dyn Any { | ||
| self | ||
| } | ||
|
|
||
| fn name(&self) -> &str { | ||
| "json_array_length" | ||
| } | ||
|
|
||
| fn signature(&self) -> &Signature { | ||
| &self.signature | ||
| } | ||
|
|
||
| fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { | ||
| Ok(DataType::Int32) | ||
| } | ||
|
|
||
| fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { | ||
| spark_json_array_length(&args.args) | ||
| } | ||
| } | ||
|
|
||
| fn spark_json_array_length(args: &[ColumnarValue]) -> Result<ColumnarValue> { | ||
| if args.len() != 1 { | ||
| return exec_err!("json_array_length function takes exactly one argument"); | ||
| } | ||
| match &args[0] { | ||
| ColumnarValue::Array(array) => { | ||
| let result = spark_json_array_length_array(array)?; | ||
| Ok(ColumnarValue::Array(result)) | ||
| } | ||
| ColumnarValue::Scalar(scalar) => { | ||
| let result = spark_json_array_length_scalar(scalar)?; | ||
| Ok(ColumnarValue::Scalar(result)) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn spark_json_array_length_array(array: &ArrayRef) -> Result<ArrayRef> { | ||
| match array.data_type() { | ||
| DataType::Utf8 => { | ||
| let array = as_string_array(array)?; | ||
| let mut builder = Int32Builder::with_capacity(array.len()); | ||
|
|
||
| for row_idx in 0..array.len() { | ||
| if array.is_null(row_idx) { | ||
| builder.append_null(); | ||
| } else { | ||
| let json_str = array.value(row_idx); | ||
| if let Some(json_array_length) = get_json_array_length(json_str) { | ||
| builder.append_value(json_array_length); | ||
| } else { | ||
| builder.append_null() | ||
| } | ||
| } | ||
| } | ||
| Ok(Arc::new(builder.finish())) | ||
| } | ||
| other => { | ||
| exec_err!("Unsupported data type {other:?} for function `json_array_length`") | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn spark_json_array_length_scalar(scalar: &ScalarValue) -> Result<ScalarValue> { | ||
| match scalar { | ||
| ScalarValue::Utf8(value) => { | ||
| let length = value | ||
| .clone() | ||
| .and_then(|json_str| get_json_array_length(&json_str)); | ||
| Ok(ScalarValue::Int32(length)) | ||
| } | ||
| other => { | ||
| exec_err!("Unsupported data type {other:?} for function `json_array_length`") | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn get_json_array_length(json_str: &str) -> Option<i32> { | ||
| match serde_json::from_str::<serde_json::Value>(json_str) { | ||
| Ok(json_value) => { | ||
| if json_value.is_array() { | ||
| Some(json_value.as_array().unwrap().len() as i32) | ||
| } else { | ||
| None | ||
| } | ||
| } | ||
| Err(_) => None, | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
61 changes: 61 additions & 0 deletions
61
spark/src/test/resources/sql-tests/expressions/json/json_array_length.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| -- 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. | ||
|
|
||
| statement | ||
| CREATE TABLE test_json_array_length(j string) USING parquet | ||
|
|
||
| statement | ||
| INSERT INTO test_json_array_length VALUES | ||
| ('[1,2,3,4]'), | ||
| ('[]'), | ||
| ('[1]'), | ||
| (NULL), | ||
| ('[1,2,3,{"f1":1,"f2":[5,6]},4]'), | ||
| ('[[1,2],[3,4],[5,6]]'), | ||
| ('[{"a":1},{"b":2},{"c":3}]'), | ||
| ('[1,2'), | ||
| ('[1,2,3,]'), | ||
| ('not a json'), | ||
| ('{"object": "not array"}'), | ||
| (''), | ||
| (' '), | ||
| ('[true, false, null]'), | ||
| ('["string1", "string2", "string3"]'), | ||
| ('[1, "mixed", true, null, {"key":"value"}]'), | ||
| ('[1,2,3,4,5,6,7,8,9,10]'), | ||
| ('["line1\nline2", "tab\tseparated", "quote\"here"]'), | ||
| ('{"outer": [1,2,3], "inner": [[1,2],[3,4]]}'), | ||
| ('{"arrays": {"first": [1,2], "second": [3,4,5]}}'), | ||
| ('[{"arr": [1,2,3]}, {"arr": [4,5]}]') | ||
|
|
||
| query | ||
| SELECT json_array_length(j) FROM test_json_array_length | ||
|
|
||
| query | ||
| SELECT json_array_length('[1,2,3,4]') | ||
|
|
||
| query | ||
| SELECT json_array_length('not an array') | ||
|
|
||
| query | ||
| SELECT json_array_length('{"key":"value"}') | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. could you also add examples for incompatible behavior, such as using single quotes around keys and values |
||
|
|
||
| query | ||
| SELECT json_array_length(NULL) | ||
|
|
||
| query | ||
| SELECT json_array_length('[]') | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Spark's
JsonExpressionUtils.lengthOfJsonArrayuses a Jackson parser configured withALLOW_SINGLE_QUOTESandALLOW_UNESCAPED_CONTROL_CHARS, and uses streaming parsing that ignores trailing content after the array's closing bracket.serde_json::from_str::<Value>is much stricter. Could you markgetSupportLevelasIncompatible(Some("..."))and addgetIncompatibleReasons()so that the auto-generated compat doc surfaces the limitation to users, and the function is gated behindspark.comet.expression.LengthOfJsonArray.allowIncompatible=true.