jorgecarleitao commented on a change in pull request #9428: URL: https://github.com/apache/arrow/pull/9428#discussion_r577296571
########## File path: rust/arrow/src/compute/kernels/regexp.rs ########## @@ -0,0 +1,117 @@ +// 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. + +//! Defines kernel to extract substrings based on a regular +//! expression of a \[Large\]StringArray + +use crate::array::{ + Array, ArrayRef, GenericStringArray, GenericStringBuilder, LargeStringArray, + StringArray, StringOffsetSizeTrait, +}; +use crate::datatypes::DataType; +use crate::error::{ArrowError, Result}; + +use std::sync::Arc; + +use regex::Regex; + +fn generic_regexp_extract<OffsetSize: StringOffsetSizeTrait>( + array: &GenericStringArray<OffsetSize>, + re: &Regex, + idx: usize, +) -> Result<ArrayRef> { + let mut builder: GenericStringBuilder<OffsetSize> = GenericStringBuilder::new(0); + + for maybe_value in array.iter() { Review comment: It is more efficient (and probably idiomatic) to use the `collect::<GenericStringArray<OffsetSize>>()` here. I.e. ```rust array .iter() .map(<logic here>) .collect::<GenericStringArray<OffsetSize>>() ``` Since this is an unary operation on a utf8 array, I would try to write a generic for it (like we do for primitives in `arity.rs`) and use it here. We may even be able to write it using the `trusted_len`, which is the faster option available atm. ########## File path: rust/arrow/src/compute/kernels/regexp.rs ########## @@ -0,0 +1,117 @@ +// 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. + +//! Defines kernel to extract substrings based on a regular +//! expression of a \[Large\]StringArray + +use crate::array::{ + Array, ArrayRef, GenericStringArray, GenericStringBuilder, LargeStringArray, + StringArray, StringOffsetSizeTrait, +}; +use crate::datatypes::DataType; +use crate::error::{ArrowError, Result}; + +use std::sync::Arc; + +use regex::Regex; + +fn generic_regexp_extract<OffsetSize: StringOffsetSizeTrait>( + array: &GenericStringArray<OffsetSize>, + re: &Regex, + idx: usize, +) -> Result<ArrayRef> { + let mut builder: GenericStringBuilder<OffsetSize> = GenericStringBuilder::new(0); + + for maybe_value in array.iter() { + match maybe_value { + Some(value) => match re.captures(value) { + Some(caps) => { + let m = caps.get(idx).ok_or_else(|| { + ArrowError::ComputeError(format!( + "Regexp has no group with index {}", + idx + )) + })?; + builder.append_value(m.as_str())? + } + None => builder.append_null()?, + }, + None => builder.append_null()?, + } + } + Ok(Arc::new(builder.finish())) +} + +/// Extracts a specific group matched by a regular expression for a given String array. +/// Group index 0 returns the whole match, index 1 returns the first group and so on. Please +/// refer to regex crate for details on pattern specifics. +pub fn regexp_extract(array: &Array, pattern: &str, idx: usize) -> Result<ArrayRef> { Review comment: I wonder if the signature shouldn't be `idx: &[usize]` and the result `Vec<ArrayRef>`. It would allow for optimizations where the user wants more than one group for the same regex (as regex is usually slow). Could be left out for now, just a though. ########## File path: rust/arrow/src/compute/kernels/regexp.rs ########## @@ -0,0 +1,117 @@ +// 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. + +//! Defines kernel to extract substrings based on a regular +//! expression of a \[Large\]StringArray + +use crate::array::{ + Array, ArrayRef, GenericStringArray, GenericStringBuilder, LargeStringArray, + StringArray, StringOffsetSizeTrait, +}; +use crate::datatypes::DataType; +use crate::error::{ArrowError, Result}; + +use std::sync::Arc; + +use regex::Regex; + +fn generic_regexp_extract<OffsetSize: StringOffsetSizeTrait>( + array: &GenericStringArray<OffsetSize>, + re: &Regex, + idx: usize, +) -> Result<ArrayRef> { + let mut builder: GenericStringBuilder<OffsetSize> = GenericStringBuilder::new(0); + + for maybe_value in array.iter() { + match maybe_value { + Some(value) => match re.captures(value) { + Some(caps) => { + let m = caps.get(idx).ok_or_else(|| { + ArrowError::ComputeError(format!( + "Regexp has no group with index {}", + idx + )) + })?; + builder.append_value(m.as_str())? + } + None => builder.append_null()?, + }, + None => builder.append_null()?, + } + } + Ok(Arc::new(builder.finish())) +} + +/// Extracts a specific group matched by a regular expression for a given String array. +/// Group index 0 returns the whole match, index 1 returns the first group and so on. Please +/// refer to regex crate for details on pattern specifics. +pub fn regexp_extract(array: &Array, pattern: &str, idx: usize) -> Result<ArrayRef> { + let re = Regex::new(pattern).map_err(|e| { + ArrowError::ComputeError(format!("Regular expression did not compile: {:?}", e)) + })?; + match array.data_type() { + DataType::LargeUtf8 => generic_regexp_extract( + array + .as_any() + .downcast_ref::<LargeStringArray>() + .expect("A large string is expected"), + &re, + idx, + ), + DataType::Utf8 => generic_regexp_extract( + array + .as_any() + .downcast_ref::<StringArray>() + .expect("A string is expected"), + &re, + idx, + ), + _ => Err(ArrowError::ComputeError(format!( + "regexp_extract does not support type {:?}", + array.data_type() + ))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extract_single_group() -> Result<()> { + let values = vec!["abc-005-def", "X-7-5", "X545"]; Review comment: Can we make one of these entries `None`, so that we also test the null entry case? ########## File path: rust/datafusion/src/physical_plan/string_expressions.rs ########## @@ -70,6 +71,16 @@ pub fn concatenate(args: &[ArrayRef]) -> Result<StringArray> { Ok(builder.finish()) } +/// extract a specific group from a string column, using a regular expression +pub fn regexp_extract(args: &[ArrayRef]) -> Result<ArrayRef> { + let pattern_expr = args[1].as_any().downcast_ref::<StringArray>().unwrap(); + let pattern = pattern_expr.value(0); + let idx_expr = args[2].as_any().downcast_ref::<Int64Array>().unwrap(); + let idx = idx_expr.value(0) as usize; Review comment: I am not sure this is correct: the function expects an array, but then only picks the first element of the array for the regex. Maybe this was used because ScalarFunctions did not support the `ScalarValue` variant? ########## File path: rust/arrow/src/compute/kernels/regexp.rs ########## @@ -0,0 +1,117 @@ +// 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. + +//! Defines kernel to extract substrings based on a regular +//! expression of a \[Large\]StringArray + +use crate::array::{ + Array, ArrayRef, GenericStringArray, GenericStringBuilder, LargeStringArray, + StringArray, StringOffsetSizeTrait, +}; +use crate::datatypes::DataType; +use crate::error::{ArrowError, Result}; + +use std::sync::Arc; + +use regex::Regex; + +fn generic_regexp_extract<OffsetSize: StringOffsetSizeTrait>( + array: &GenericStringArray<OffsetSize>, + re: &Regex, + idx: usize, +) -> Result<ArrayRef> { + let mut builder: GenericStringBuilder<OffsetSize> = GenericStringBuilder::new(0); + + for maybe_value in array.iter() { + match maybe_value { + Some(value) => match re.captures(value) { + Some(caps) => { + let m = caps.get(idx).ok_or_else(|| { + ArrowError::ComputeError(format!( + "Regexp has no group with index {}", + idx + )) + })?; + builder.append_value(m.as_str())? + } + None => builder.append_null()?, + }, + None => builder.append_null()?, + } + } + Ok(Arc::new(builder.finish())) +} + +/// Extracts a specific group matched by a regular expression for a given String array. +/// Group index 0 returns the whole match, index 1 returns the first group and so on. Please +/// refer to regex crate for details on pattern specifics. +pub fn regexp_extract(array: &Array, pattern: &str, idx: usize) -> Result<ArrayRef> { + let re = Regex::new(pattern).map_err(|e| { + ArrowError::ComputeError(format!("Regular expression did not compile: {:?}", e)) + })?; + match array.data_type() { + DataType::LargeUtf8 => generic_regexp_extract( + array + .as_any() + .downcast_ref::<LargeStringArray>() + .expect("A large string is expected"), + &re, + idx, + ), + DataType::Utf8 => generic_regexp_extract( + array + .as_any() + .downcast_ref::<StringArray>() + .expect("A string is expected"), + &re, + idx, + ), + _ => Err(ArrowError::ComputeError(format!( + "regexp_extract does not support type {:?}", + array.data_type() + ))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extract_single_group() -> Result<()> { + let values = vec!["abc-005-def", "X-7-5", "X545"]; + let array = StringArray::from(values); + let pattern = r".*-(\d*)-.*"; + let actual = regexp_extract(&array, pattern, 1)?; + let expected = StringArray::from(vec![Some("005"), Some("7"), None]); Review comment: if we want to mimic spark (imo we should), the last entry should result in an empty string, not a `None`. This is because it would be otherwise impossible to differentiate between a "no match" and a "input is null". ########## File path: rust/datafusion/src/physical_plan/functions.rs ########## @@ -523,6 +544,7 @@ fn signature(fun: &BuiltinScalarFunction) -> Signature { BuiltinScalarFunction::NullIf => { Signature::Uniform(2, SUPPORTED_NULLIF_TYPES.to_vec()) } + BuiltinScalarFunction::RegexpExtract => Signature::Any(3), Review comment: I am not sure this is correct; isn't the signature `Variant([[Utf8, Utf8, UInt64], [LargeUtf8, Utf8, UInt64]])` or something like that? Note that these signatures are very important because they are used for type validation during logical planning, as well as type coercion at physical planning. Whenever we write `Any`, the logical planning will accept any type. Worse, the type coercer will not perform any coercion. In this case, because we downcast arg[2] to `Int64Array`, if the user passes a `Int32Array`, the execution panics. ########## File path: rust/arrow/src/compute/kernels/regexp.rs ########## @@ -0,0 +1,117 @@ +// 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. + +//! Defines kernel to extract substrings based on a regular +//! expression of a \[Large\]StringArray + +use crate::array::{ + Array, ArrayRef, GenericStringArray, GenericStringBuilder, LargeStringArray, + StringArray, StringOffsetSizeTrait, +}; +use crate::datatypes::DataType; +use crate::error::{ArrowError, Result}; + +use std::sync::Arc; + +use regex::Regex; + +fn generic_regexp_extract<OffsetSize: StringOffsetSizeTrait>( + array: &GenericStringArray<OffsetSize>, + re: &Regex, + idx: usize, +) -> Result<ArrayRef> { + let mut builder: GenericStringBuilder<OffsetSize> = GenericStringBuilder::new(0); + + for maybe_value in array.iter() { + match maybe_value { + Some(value) => match re.captures(value) { + Some(caps) => { + let m = caps.get(idx).ok_or_else(|| { + ArrowError::ComputeError(format!( + "Regexp has no group with index {}", + idx + )) + })?; + builder.append_value(m.as_str())? + } + None => builder.append_null()?, + }, + None => builder.append_null()?, + } + } + Ok(Arc::new(builder.finish())) +} + +/// Extracts a specific group matched by a regular expression for a given String array. +/// Group index 0 returns the whole match, index 1 returns the first group and so on. Please +/// refer to regex crate for details on pattern specifics. +pub fn regexp_extract(array: &Array, pattern: &str, idx: usize) -> Result<ArrayRef> { + let re = Regex::new(pattern).map_err(|e| { + ArrowError::ComputeError(format!("Regular expression did not compile: {:?}", e)) + })?; + match array.data_type() { + DataType::LargeUtf8 => generic_regexp_extract( + array + .as_any() + .downcast_ref::<LargeStringArray>() + .expect("A large string is expected"), + &re, + idx, + ), + DataType::Utf8 => generic_regexp_extract( + array + .as_any() + .downcast_ref::<StringArray>() + .expect("A string is expected"), + &re, + idx, + ), + _ => Err(ArrowError::ComputeError(format!( + "regexp_extract does not support type {:?}", + array.data_type() + ))), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn extract_single_group() -> Result<()> { + let values = vec!["abc-005-def", "X-7-5", "X545"]; + let array = StringArray::from(values); + let pattern = r".*-(\d*)-.*"; + let actual = regexp_extract(&array, pattern, 1)?; + let expected = StringArray::from(vec![Some("005"), Some("7"), None]); + let result = actual.as_any().downcast_ref::<StringArray>().unwrap(); + assert_eq!(&expected, result); + Ok(()) + } + + #[test] + fn no_matches() -> Result<()> { + let values = vec!["abc", "X::50::00", "X545"]; + let array = StringArray::from(values); + let pattern = r".*-(\d*)-.*"; + let actual = regexp_extract(&array, pattern, 1)?; + let expected = StringArray::from(vec![None, None, None]); + let result = actual.as_any().downcast_ref::<StringArray>().unwrap(); + assert_eq!(&expected, result); + Ok(()) + } Review comment: I would be fine not adding this test. IMO this is covered on the test above. ---------------------------------------------------------------- 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. For queries about this service, please contact Infrastructure at: us...@infra.apache.org