Apache DataFusion SQL Query Engine
feat(spark): implement Spark string function like/ilike (#16962)
Chen Chongchen1a575a0835df
diff --git a/datafusion/spark/src/function/string/ilike.rs b/datafusion/spark/src/function/string/ilike.rsnew file mode 100644index 0000000000..f28e931c50--- /dev/null+++ b/datafusion/spark/src/function/string/ilike.rs@@ -0,0 +1,173 @@+// 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::ArrayRef;+use arrow::compute::ilike;+use arrow::datatypes::DataType;+use datafusion_common::{exec_err, Result};+use datafusion_expr::ColumnarValue;+use datafusion_expr::{ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility};+use datafusion_functions::utils::make_scalar_function;+use std::any::Any;+use std::sync::Arc;++/// ILIKE function for case-insensitive pattern matching+/// <https://spark.apache.org/docs/latest/api/sql/index.html#ilike>+#[derive(Debug)]+pub struct SparkILike {+ signature: Signature,+}++impl Default for SparkILike {+ fn default() -> Self {+ Self::new()+ }+}++impl SparkILike {+ pub fn new() -> Self {+ Self {+ signature: Signature::string(2, Volatility::Immutable),+ }+ }+}++impl ScalarUDFImpl for SparkILike {+ fn as_any(&self) -> &dyn Any {+ self+ }++ fn name(&self) -> &str {+ "ilike"+ }++ fn signature(&self) -> &Signature {+ &self.signature+ }++ fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {+ Ok(DataType::Boolean)+ }++ fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {+ make_scalar_function(spark_ilike, vec![])(&args.args)+ }+}++/// Returns true if str matches pattern (case insensitive).+pub fn spark_ilike(args: &[ArrayRef]) -> Result<ArrayRef> {+ if args.len() != 2 {+ return exec_err!("ilike function requires exactly 2 arguments");+ }++ let result = ilike(&args[0], &args[1])?;+ Ok(Arc::new(result))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::function::utils::test::test_scalar_function;+ use arrow::array::{Array, BooleanArray};+ use arrow::datatypes::DataType::Boolean;+ use datafusion_common::{Result, ScalarValue};+ use datafusion_expr::{ColumnarValue, ScalarUDFImpl};++ macro_rules! test_ilike_string_invoke {+ ($INPUT1:expr, $INPUT2:expr, $EXPECTED:expr) => {+ test_scalar_function!(+ SparkILike::new(),+ vec![+ ColumnarValue::Scalar(ScalarValue::Utf8($INPUT1)),+ ColumnarValue::Scalar(ScalarValue::Utf8($INPUT2))+ ],+ $EXPECTED,+ bool,+ Boolean,+ BooleanArray+ );++ test_scalar_function!(+ SparkILike::new(),+ vec![+ ColumnarValue::Scalar(ScalarValue::LargeUtf8($INPUT1)),+ ColumnarValue::Scalar(ScalarValue::LargeUtf8($INPUT2))+ ],+ $EXPECTED,+ bool,+ Boolean,+ BooleanArray+ );++ test_scalar_function!(+ SparkILike::new(),+ vec![+ ColumnarValue::Scalar(ScalarValue::Utf8View($INPUT1)),+ ColumnarValue::Scalar(ScalarValue::Utf8View($INPUT2))+ ],+ $EXPECTED,+ bool,+ Boolean,+ BooleanArray+ );+ };+ }++ #[test]+ fn test_ilike_invoke() -> Result<()> {+ test_ilike_string_invoke!(+ Some(String::from("Spark")),+ Some(String::from("_park")),+ Ok(Some(true))+ );+ test_ilike_string_invoke!(+ Some(String::from("Spark")),+ Some(String::from("_PARK")),+ Ok(Some(true))+ );+ test_ilike_string_invoke!(+ Some(String::from("SPARK")),+ Some(String::from("_park")),+ Ok(Some(true))+ );+ test_ilike_string_invoke!(+ Some(String::from("Spark")),+ Some(String::from("sp%")),+ Ok(Some(true))+ );+ test_ilike_string_invoke!(+ Some(String::from("Spark")),+ Some(String::from("SP%")),+ Ok(Some(true))+ );+ test_ilike_string_invoke!(+ Some(String::from("Spark")),+ Some(String::from("%ARK")),+ Ok(Some(true))+ );+ test_ilike_string_invoke!(+ Some(String::from("Spark")),+ Some(String::from("xyz")),+ Ok(Some(false))+ );+ test_ilike_string_invoke!(None, Some(String::from("_park")), Ok(None));+ test_ilike_string_invoke!(Some(String::from("Spark")), None, Ok(None));+ test_ilike_string_invoke!(None, None, Ok(None));++ Ok(())+ }+}diff --git a/datafusion/spark/src/function/string/like.rs b/datafusion/spark/src/function/string/like.rsnew file mode 100644index 0000000000..eb2e605b3b--- /dev/null+++ b/datafusion/spark/src/function/string/like.rs@@ -0,0 +1,178 @@+// 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::ArrayRef;+use arrow::compute::like;+use arrow::datatypes::DataType;+use datafusion_common::{exec_err, Result};+use datafusion_expr::ColumnarValue;+use datafusion_expr::{ScalarFunctionArgs, ScalarUDFImpl, Signature, Volatility};+use datafusion_functions::utils::make_scalar_function;+use std::any::Any;+use std::sync::Arc;++/// LIKE function for case-sensitive pattern matching+/// <https://spark.apache.org/docs/latest/api/sql/index.html#like>+#[derive(Debug)]+pub struct SparkLike {+ signature: Signature,+}++impl Default for SparkLike {+ fn default() -> Self {+ Self::new()+ }+}++impl SparkLike {+ pub fn new() -> Self {+ Self {+ signature: Signature::string(2, Volatility::Immutable),+ }+ }+}++impl ScalarUDFImpl for SparkLike {+ fn as_any(&self) -> &dyn Any {+ self+ }++ fn name(&self) -> &str {+ "like"+ }++ fn signature(&self) -> &Signature {+ &self.signature+ }++ fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> {+ Ok(DataType::Boolean)+ }++ fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {+ make_scalar_function(spark_like, vec![])(&args.args)+ }+}++/// Returns true if str matches pattern (case sensitive).+pub fn spark_like(args: &[ArrayRef]) -> Result<ArrayRef> {+ if args.len() != 2 {+ return exec_err!("like function requires exactly 2 arguments");+ }++ let result = like(&args[0], &args[1])?;+ Ok(Arc::new(result))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::function::utils::test::test_scalar_function;+ use arrow::array::{Array, BooleanArray};+ use arrow::datatypes::DataType::Boolean;+ use datafusion_common::{Result, ScalarValue};+ use datafusion_expr::{ColumnarValue, ScalarUDFImpl};++ macro_rules! test_like_string_invoke {+ ($INPUT1:expr, $INPUT2:expr, $EXPECTED:expr) => {+ test_scalar_function!(+ SparkLike::new(),+ vec![+ ColumnarValue::Scalar(ScalarValue::Utf8($INPUT1)),+ ColumnarValue::Scalar(ScalarValue::Utf8($INPUT2))+ ],+ $EXPECTED,+ bool,+ Boolean,+ BooleanArray+ );++ test_scalar_function!(+ SparkLike::new(),+ vec![+ ColumnarValue::Scalar(ScalarValue::LargeUtf8($INPUT1)),+ ColumnarValue::Scalar(ScalarValue::LargeUtf8($INPUT2))+ ],+ $EXPECTED,+ bool,+ Boolean,+ BooleanArray+ );++ test_scalar_function!(+ SparkLike::new(),+ vec![+ ColumnarValue::Scalar(ScalarValue::Utf8View($INPUT1)),+ ColumnarValue::Scalar(ScalarValue::Utf8View($INPUT2))+ ],+ $EXPECTED,+ bool,+ Boolean,+ BooleanArray+ );+ };+ }++ #[test]+ fn test_like_invoke() -> Result<()> {+ test_like_string_invoke!(+ Some(String::from("Spark")),+ Some(String::from("_park")),+ Ok(Some(true))+ );+ test_like_string_invoke!(+ Some(String::from("Spark")),+ Some(String::from("_PARK")),+ Ok(Some(false)) // case-sensitive+ );+ test_like_string_invoke!(+ Some(String::from("SPARK")),+ Some(String::from("_park")),+ Ok(Some(false)) // case-sensitive+ );+ test_like_string_invoke!(+ Some(String::from("Spark")),+ Some(String::from("Sp%")),+ Ok(Some(true))+ );+ test_like_string_invoke!(+ Some(String::from("Spark")),+ Some(String::from("SP%")),+ Ok(Some(false)) // case-sensitive+ );+ test_like_string_invoke!(+ Some(String::from("Spark")),+ Some(String::from("%ark")),+ Ok(Some(true))+ );+ test_like_string_invoke!(+ Some(String::from("Spark")),+ Some(String::from("%ARK")),+ Ok(Some(false)) // case-sensitive+ );+ test_like_string_invoke!(+ Some(String::from("Spark")),+ Some(String::from("xyz")),+ Ok(Some(false))+ );+ test_like_string_invoke!(None, Some(String::from("_park")), Ok(None));+ test_like_string_invoke!(Some(String::from("Spark")), None, Ok(None));+ test_like_string_invoke!(None, None, Ok(None));++ Ok(())+ }+}diff --git a/datafusion/spark/src/function/string/mod.rs b/datafusion/spark/src/function/string/mod.rsindex e45bf4add7..9e3c7126c6 100644--- a/datafusion/spark/src/function/string/mod.rs+++ b/datafusion/spark/src/function/string/mod.rs@@ -17,6 +17,8 @@pub mod ascii;pub mod char;+pub mod ilike;+pub mod like;pub mod luhn_check;use datafusion_expr::ScalarUDF;@@ -25,6 +27,8 @@ use std::sync::Arc;make_udf_function!(ascii::SparkAscii, ascii);make_udf_function!(char::SparkChar, char);+make_udf_function!(ilike::SparkILike, ilike);+make_udf_function!(like::SparkLike, like);make_udf_function!(luhn_check::SparkLuhnCheck, luhn_check);pub mod expr_fn {@@ -40,6 +44,16 @@ pub mod expr_fn {"Returns the ASCII character having the binary equivalent to col. If col is larger than 256 the result is equivalent to char(col % 256).",arg1));+ export_functions!((+ ilike,+ "Returns true if str matches pattern (case insensitive).",+ str pattern+ ));+ export_functions!((+ like,+ "Returns true if str matches pattern (case sensitive).",+ str pattern+ ));export_functions!((luhn_check,"Returns whether the input string of digits is valid according to the Luhn algorithm.",@@ -48,5 +62,5 @@ pub mod expr_fn {}pub fn functions() -> Vec<Arc<ScalarUDF>> {- vec![ascii(), char(), luhn_check()]+ vec![ascii(), char(), ilike(), like(), luhn_check()]}diff --git a/datafusion/sqllogictest/test_files/spark/predicate/ilike.slt b/datafusion/sqllogictest/test_files/spark/predicate/ilike.sltindex aab57c95ba..8a3170c158 100644--- a/datafusion/sqllogictest/test_files/spark/predicate/ilike.slt+++ b/datafusion/sqllogictest/test_files/spark/predicate/ilike.slt@@ -23,5 +23,52 @@## Original Query: SELECT ilike('Spark', '_Park');## PySpark 3.5.5 Result: {'ilike(Spark, _Park)': True, 'typeof(ilike(Spark, _Park))': 'boolean', 'typeof(Spark)': 'string', 'typeof(_Park)': 'string'}-#query-#SELECT ilike('Spark'::string, '_Park'::string);+query B+SELECT ilike('Spark'::string, '_Park'::string);+----+true++query B+SELECT ilike('Spark', arrow_cast('_Park', 'LargeUtf8'));+----+true++query B+SELECT ilike(arrow_cast('Spark', 'Utf8View'), arrow_cast('_Park', 'LargeUtf8'));+----+true++query B+SELECT ilike('Spark'::string, '_park'::string);+----+true++query B+SELECT ilike('SPARK'::string, '_park'::string);+----+true++query B+SELECT ilike('Spark'::string, 'SP%'::string);+----+true++query B+SELECT ilike('Spark'::string, '%ARK'::string);+----+true++query B+SELECT ilike('Spark'::string, 'xyz'::string);+----+false++query B+SELECT ilike(NULL::string, '_park'::string);+----+NULL++query B+SELECT ilike('Spark'::string, NULL::string);+----+NULLdiff --git a/datafusion/sqllogictest/test_files/spark/predicate/like.slt b/datafusion/sqllogictest/test_files/spark/predicate/like.sltindex 03852feb5f..35cd8a4eaf 100644--- a/datafusion/sqllogictest/test_files/spark/predicate/like.slt+++ b/datafusion/sqllogictest/test_files/spark/predicate/like.slt@@ -23,5 +23,62 @@## Original Query: SELECT like('Spark', '_park');## PySpark 3.5.5 Result: {'Spark LIKE _park': True, 'typeof(Spark LIKE _park)': 'boolean', 'typeof(Spark)': 'string', 'typeof(_park)': 'string'}-#query-#SELECT like('Spark'::string, '_park'::string);+query B+SELECT like('Spark'::string, '_park'::string);+----+true++query B+SELECT ilike('Spark', arrow_cast('_park', 'LargeUtf8'));+----+true++query B+SELECT ilike(arrow_cast('Spark', 'Utf8View'), arrow_cast('_park', 'LargeUtf8'));+----+true++query B+SELECT like('Spark'::string, '_Park'::string);+----+false++query B+SELECT like('SPARK'::string, '_park'::string);+----+false++query B+SELECT like('Spark'::string, 'Sp%'::string);+----+true++query B+SELECT like('Spark'::string, 'SP%'::string);+----+false++query B+SELECT like('Spark'::string, '%ark'::string);+----+true++query B+SELECT like('Spark'::string, '%ARK'::string);+----+false++query B+SELECT like('Spark'::string, 'xyz'::string);+----+false++query B+SELECT like(NULL::string, '_park'::string);+----+NULL++query B+SELECT like('Spark'::string, NULL::string);+----+NULL