-
Notifications
You must be signed in to change notification settings - Fork 258
feat: Add support for RLike #469
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
Closed
Closed
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
7994069
Add test and proto support for RLike
andygrove 2d31bc8
boilerplate
andygrove 28169e7
test passes
andygrove b3f47b7
error handling
andygrove 7979634
improve test
andygrove b2c9688
add to supported expressions
andygrove 93daf41
add notes to compatibility guide
andygrove 397146a
merge from main
andygrove 204dd59
fix merge conflict
andygrove 390fd0f
lint
andygrove 48d285d
Merge remote-tracking branch 'apache/main' into rlike
andygrove 0b1b2c4
update for DataFusion 39 API change
andygrove 86a2b87
merge from main
andygrove b74394f
update expressions doc
andygrove bad00dc
upmerge
andygrove a6db1a7
regexp benchmarks and tests
andygrove 6177118
fix error
andygrove 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 |
|---|---|---|
|
|
@@ -136,3 +136,7 @@ harness = false | |
| [[bench]] | ||
| name = "shuffle_writer" | ||
| harness = false | ||
|
|
||
| [[bench]] | ||
| name = "regexp" | ||
| harness = false | ||
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,75 @@ | ||
| // 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 std::sync::Arc; | ||
| use arrow::datatypes::Int32Type; | ||
| use arrow::error::ArrowError; | ||
| use arrow_array::{builder::StringBuilder, builder::StringDictionaryBuilder, RecordBatch}; | ||
| use arrow_schema::{DataType, Field, Schema}; | ||
| use comet::execution::datafusion::expressions::regexp::RLike; | ||
| use criterion::{criterion_group, criterion_main, Criterion}; | ||
| use datafusion::common::ScalarValue; | ||
| use datafusion_physical_expr::{expressions::Column, expressions::Literal, PhysicalExpr, expressions::LikeExpr}; | ||
|
|
||
| fn criterion_benchmark(c: &mut Criterion) { | ||
| let batch = create_utf8_batch().unwrap(); | ||
| let child_expr = Arc::new(Column::new("foo", 0)); | ||
| let pattern_expr = Arc::new(Literal::new(ScalarValue::Utf8(Some("5[0-9]5".to_string())))); | ||
| let rlike = RLike::new(child_expr.clone(), pattern_expr.clone()); | ||
| let df_rlike = LikeExpr::new(false, false, child_expr, pattern_expr); | ||
|
|
||
| let mut group = c.benchmark_group("regexp"); | ||
| group.bench_function("regexp_comet_rlike", |b| { | ||
| b.iter(|| rlike.evaluate(&batch).unwrap()); | ||
| }); | ||
| group.bench_function("regexp_datafusion_rlike", |b| { | ||
| b.iter(|| df_rlike.evaluate(&batch).unwrap()); | ||
| }); | ||
| } | ||
|
|
||
| fn create_utf8_batch() -> Result<RecordBatch, ArrowError> { | ||
| let schema = Arc::new(Schema::new(vec![ | ||
| Field::new("a", DataType::Utf8, true), | ||
| Field::new("b", DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)), true) | ||
| ])); | ||
| let mut string_builder = StringBuilder::new(); | ||
| let mut string_dict_builder = StringDictionaryBuilder::<Int32Type>::new(); | ||
| for i in 0..1000 { | ||
| if i % 10 == 0 { | ||
| string_builder.append_null(); | ||
| string_dict_builder.append_null(); | ||
| } else { | ||
| string_builder.append_value(format!("{}", i)); | ||
| string_dict_builder.append_value(format!("{}", i)); | ||
| } | ||
| } | ||
| let string_array = string_builder.finish(); | ||
| let string_dict_array2 = string_dict_builder.finish(); | ||
| RecordBatch::try_new(schema.clone(), vec![Arc::new(string_array), Arc::new(string_dict_array2)]) | ||
| } | ||
|
|
||
| fn config() -> Criterion { | ||
| Criterion::default() | ||
| } | ||
|
|
||
| criterion_group! { | ||
| name = benches; | ||
| config = config(); | ||
| targets = criterion_benchmark | ||
| } | ||
| criterion_main!(benches); |
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,205 @@ | ||
| /* | ||
| * 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 crate::{errors::CometError, execution::datafusion::expressions::utils::down_cast_any_ref}; | ||
| use arrow_array::{builder::BooleanBuilder, Array, RecordBatch, StringArray}; | ||
| use arrow_schema::{DataType, Schema}; | ||
| use datafusion::logical_expr::ColumnarValue; | ||
| use datafusion_common::ScalarValue; | ||
| use datafusion_physical_expr::PhysicalExpr; | ||
| use regex::Regex; | ||
| use std::{ | ||
| any::Any, | ||
| fmt::{Display, Formatter}, | ||
| hash::Hasher, | ||
| sync::Arc, | ||
| }; | ||
|
|
||
| #[derive(Debug, Hash)] | ||
| pub struct RLike { | ||
| child: Arc<dyn PhysicalExpr>, | ||
| pattern: Arc<dyn PhysicalExpr>, | ||
| } | ||
|
|
||
| impl RLike { | ||
| pub fn new(child: Arc<dyn PhysicalExpr>, pattern: Arc<dyn PhysicalExpr>) -> Self { | ||
| Self { child, pattern } | ||
| } | ||
| } | ||
|
|
||
| impl Display for RLike { | ||
| fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { | ||
| write!( | ||
| f, | ||
| "RLike [child: {}, pattern: {}] ", | ||
| self.child, self.pattern | ||
| ) | ||
| } | ||
| } | ||
|
|
||
| impl PartialEq<dyn Any> for RLike { | ||
| fn eq(&self, other: &dyn Any) -> bool { | ||
| down_cast_any_ref(other) | ||
| .downcast_ref::<Self>() | ||
| .map(|x| self.child.eq(&x.child) && self.pattern.eq(&x.pattern)) | ||
| .unwrap_or(false) | ||
| } | ||
| } | ||
|
|
||
| impl PhysicalExpr for RLike { | ||
| fn as_any(&self) -> &dyn Any { | ||
| self | ||
| } | ||
|
|
||
| fn data_type(&self, _input_schema: &Schema) -> datafusion_common::Result<DataType> { | ||
| Ok(DataType::Boolean) | ||
| } | ||
|
|
||
| fn nullable(&self, input_schema: &Schema) -> datafusion_common::Result<bool> { | ||
| self.child.nullable(input_schema) | ||
| } | ||
|
|
||
| fn evaluate(&self, batch: &RecordBatch) -> datafusion_common::Result<ColumnarValue> { | ||
| if let ColumnarValue::Array(v) = self.child.evaluate(batch)? { | ||
| if let ColumnarValue::Scalar(ScalarValue::Utf8(Some(pattern))) = | ||
| self.pattern.evaluate(batch)? | ||
| { | ||
| // TODO cache Regex across invocations of evaluate() or create it in constructor | ||
| match Regex::new(&pattern) { | ||
| Ok(re) => { | ||
| let inputs = v | ||
| .as_any() | ||
| .downcast_ref::<StringArray>() | ||
| .expect("string array"); | ||
| let mut builder = BooleanBuilder::with_capacity(inputs.len()); | ||
| if inputs.is_nullable() { | ||
| for i in 0..inputs.len() { | ||
| if inputs.is_null(i) { | ||
| builder.append_null(); | ||
| } else { | ||
| builder.append_value(re.is_match(inputs.value(i))); | ||
| } | ||
| } | ||
| } else { | ||
| for i in 0..inputs.len() { | ||
| builder.append_value(re.is_match(inputs.value(i))); | ||
| } | ||
| } | ||
| Ok(ColumnarValue::Array(Arc::new(builder.finish()))) | ||
| } | ||
| Err(e) => Err(CometError::Internal(format!( | ||
| "Failed to compile regular expression: {e:?}" | ||
| )) | ||
| .into()), | ||
| } | ||
| } else { | ||
| Err( | ||
| CometError::Internal("Only scalar regex patterns are supported".to_string()) | ||
| .into(), | ||
| ) | ||
| } | ||
| } else { | ||
| // this should be unreachable because Spark will evaluate regex expressions against | ||
| // literal strings as part of query planning | ||
| Err(CometError::Internal("Only columnar inputs are supported".to_string()).into()) | ||
|
Contributor
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. Is it possible to encounter dictionary type?
Member
Author
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. Good point. Yes, it probably is. |
||
| } | ||
| } | ||
|
|
||
| fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> { | ||
| vec![&self.child] | ||
| } | ||
|
|
||
| fn with_new_children( | ||
| self: Arc<Self>, | ||
| children: Vec<Arc<dyn PhysicalExpr>>, | ||
| ) -> datafusion_common::Result<Arc<dyn PhysicalExpr>> { | ||
| assert!(children.len() == 2); | ||
| Ok(Arc::new(RLike::new( | ||
| children[0].clone(), | ||
| children[1].clone(), | ||
| ))) | ||
| } | ||
|
|
||
| fn dyn_hash(&self, state: &mut dyn Hasher) { | ||
| use std::hash::Hash; | ||
| let mut s = state; | ||
| self.hash(&mut s); | ||
| } | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod test { | ||
| use std::sync::Arc; | ||
| use arrow_array::builder::{StringBuilder, StringDictionaryBuilder}; | ||
| use arrow_array::{Array, BooleanArray, RecordBatch}; | ||
| use arrow_array::types::Int32Type; | ||
| use arrow_schema::{ArrowError, DataType, Field, Schema}; | ||
| use datafusion_common::{DataFusionError, ScalarValue}; | ||
| use datafusion_expr::ColumnarValue; | ||
| use datafusion_physical_expr::expressions::Literal; | ||
| use datafusion_physical_expr_common::expressions::column::Column; | ||
| use datafusion_physical_expr_common::physical_expr::PhysicalExpr; | ||
| use super::*; | ||
|
|
||
| #[test] | ||
| fn test_string_input() -> Result<(), DataFusionError> { | ||
| do_test(0, "5[0-9]5", 10) | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_dict_encoded_string_input() -> Result<(), DataFusionError> { | ||
| do_test(1, "5[0-9]5", 10) | ||
| } | ||
|
|
||
| fn do_test(column: usize, pattern: &str, expected_count: usize) -> Result<(), DataFusionError> { | ||
| let batch = create_utf8_batch()?; | ||
| let child_expr = Arc::new(Column::new("foo", column)); | ||
| let pattern_expr = Arc::new(Literal::new(ScalarValue::Utf8(Some(pattern.to_string())))); | ||
| let rlike = RLike::new(child_expr, pattern_expr); | ||
| if let ColumnarValue::Array(array) = rlike.evaluate(&batch).unwrap() { | ||
| let array = array.as_any().downcast_ref::<BooleanArray>().expect("boolean array"); | ||
| assert_eq!(expected_count, array.true_count()); | ||
| } else { | ||
| unreachable!() | ||
| } | ||
| Ok(()) | ||
| } | ||
|
|
||
| fn create_utf8_batch() -> Result<RecordBatch, ArrowError> { | ||
| let schema = Arc::new(Schema::new(vec![ | ||
| Field::new("a", DataType::Utf8, true), | ||
| Field::new("b", DataType::Dictionary(Box::new(DataType::Int32), Box::new(DataType::Utf8)), true) | ||
| ])); | ||
| let mut string_builder = StringBuilder::new(); | ||
| let mut string_dict_builder = StringDictionaryBuilder::<Int32Type>::new(); | ||
| for i in 0..1000 { | ||
| if i % 10 == 0 { | ||
| string_builder.append_null(); | ||
| string_dict_builder.append_null(); | ||
| } else { | ||
| string_builder.append_value(format!("{}", i)); | ||
| string_dict_builder.append_value(format!("{}", i)); | ||
| } | ||
| } | ||
| let string_array = string_builder.finish(); | ||
| let string_dict_array2 = string_dict_builder.finish(); | ||
| RecordBatch::try_new(schema.clone(), vec![Arc::new(string_array), Arc::new(string_dict_array2)]) | ||
| } | ||
|
|
||
| } | ||
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
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
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.
Uh oh!
There was an error while loading. Please reload this page.