-
Notifications
You must be signed in to change notification settings - Fork 169
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
feat: Implement basic version of RLIKE #734
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
67ab968
add some documentation
andygrove 3fec3e4
add another test
andygrove 51c2f0d
prepare for review
andygrove 7f47092
remove todo
andygrove a871bea
docs
andygrove 56a9980
upmerge
andygrove 10dea84
clippy
andygrove eb462bb
formatting
andygrove e966b07
test a subset of patterns
andygrove e559952
Add another test
andygrove f975432
remove unused methods
andygrove 3a21ca5
remove unused import
andygrove 2bd9495
add dictionary support
andygrove 8c4ffd1
docs
andygrove 4e82115
add rlike microbenchmark
andygrove 5dcd8fa
enable rlike
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 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 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 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 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 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 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 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 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 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,170 @@ | ||
// 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::utils::down_cast_any_ref; | ||
use crate::SparkError; | ||
use arrow::compute::take; | ||
use arrow_array::builder::BooleanBuilder; | ||
use arrow_array::types::Int32Type; | ||
use arrow_array::{Array, BooleanArray, DictionaryArray, RecordBatch, StringArray}; | ||
use arrow_schema::{DataType, Schema}; | ||
use datafusion_common::{internal_err, Result}; | ||
use datafusion_expr::ColumnarValue; | ||
use datafusion_physical_expr_common::physical_expr::PhysicalExpr; | ||
use regex::Regex; | ||
use std::any::Any; | ||
use std::fmt::{Display, Formatter}; | ||
use std::hash::{Hash, Hasher}; | ||
use std::sync::Arc; | ||
|
||
/// Implementation of RLIKE operator. | ||
/// | ||
/// Note that this implementation is not yet Spark-compatible and simply delegates to | ||
/// the Rust regexp crate. It will match Spark behavior for some simple cases but has | ||
/// differences in whitespace handling and does not support all the features of Java's | ||
/// regular expression engine, which are documented at: | ||
/// | ||
/// https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html | ||
#[derive(Debug)] | ||
pub struct RLike { | ||
child: Arc<dyn PhysicalExpr>, | ||
// Only scalar patterns are supported | ||
pattern_str: String, | ||
pattern: Regex, | ||
} | ||
|
||
impl Hash for RLike { | ||
fn hash<H: Hasher>(&self, state: &mut H) { | ||
state.write(self.pattern_str.as_bytes()); | ||
} | ||
} | ||
|
||
impl RLike { | ||
pub fn try_new(child: Arc<dyn PhysicalExpr>, pattern: &str) -> Result<Self> { | ||
Ok(Self { | ||
child, | ||
pattern_str: pattern.to_string(), | ||
pattern: Regex::new(pattern).map_err(|e| { | ||
SparkError::Internal(format!("Failed to compile pattern {}: {}", pattern, e)) | ||
})?, | ||
}) | ||
} | ||
|
||
fn is_match(&self, inputs: &StringArray) -> BooleanArray { | ||
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(self.pattern.is_match(inputs.value(i))); | ||
} | ||
} | ||
} else { | ||
for i in 0..inputs.len() { | ||
builder.append_value(self.pattern.is_match(inputs.value(i))); | ||
} | ||
} | ||
builder.finish() | ||
} | ||
} | ||
|
||
impl Display for RLike { | ||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { | ||
write!( | ||
f, | ||
"RLike [child: {}, pattern: {}] ", | ||
self.child, self.pattern_str | ||
) | ||
} | ||
} | ||
|
||
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_str.eq(&x.pattern_str)) | ||
.unwrap_or(false) | ||
} | ||
} | ||
|
||
impl PhysicalExpr for RLike { | ||
fn as_any(&self) -> &dyn Any { | ||
self | ||
} | ||
|
||
fn data_type(&self, _input_schema: &Schema) -> Result<DataType> { | ||
Ok(DataType::Boolean) | ||
} | ||
|
||
fn nullable(&self, input_schema: &Schema) -> Result<bool> { | ||
self.child.nullable(input_schema) | ||
} | ||
|
||
fn evaluate(&self, batch: &RecordBatch) -> Result<ColumnarValue> { | ||
match self.child.evaluate(batch)? { | ||
ColumnarValue::Array(array) if array.as_any().is::<DictionaryArray<Int32Type>>() => { | ||
let dict_array = array | ||
.as_any() | ||
.downcast_ref::<DictionaryArray<Int32Type>>() | ||
.expect("dict array"); | ||
let dict_values = dict_array | ||
.values() | ||
.as_any() | ||
.downcast_ref::<StringArray>() | ||
.expect("strings"); | ||
// evaluate the regexp pattern against the dictionary values | ||
let new_values = self.is_match(dict_values); | ||
// convert to conventional (not dictionary-encoded) array | ||
let result = take(&new_values, dict_array.keys(), None)?; | ||
Ok(ColumnarValue::Array(result)) | ||
} | ||
ColumnarValue::Array(array) => { | ||
let inputs = array | ||
.as_any() | ||
.downcast_ref::<StringArray>() | ||
.expect("string array"); | ||
let array = self.is_match(inputs); | ||
Ok(ColumnarValue::Array(Arc::new(array))) | ||
} | ||
ColumnarValue::Scalar(_) => { | ||
internal_err!("non scalar regexp patterns are not supported") | ||
} | ||
} | ||
} | ||
|
||
fn children(&self) -> Vec<&Arc<dyn PhysicalExpr>> { | ||
vec![&self.child] | ||
} | ||
|
||
fn with_new_children( | ||
self: Arc<Self>, | ||
children: Vec<Arc<dyn PhysicalExpr>>, | ||
) -> Result<Arc<dyn PhysicalExpr>> { | ||
assert!(children.len() == 1); | ||
Ok(Arc::new(RLike::try_new( | ||
children[0].clone(), | ||
&self.pattern_str, | ||
)?)) | ||
} | ||
|
||
fn dyn_hash(&self, state: &mut dyn Hasher) { | ||
use std::hash::Hash; | ||
let mut s = state; | ||
self.hash(&mut s); | ||
} | ||
} |
24 changes: 24 additions & 0 deletions
24
spark/benchmarks/CometAggregateBenchmark-jdk11-results.txt
This file contains 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,24 @@ | ||
================================================================================================ | ||
Grouped Aggregate (single group key + single aggregate SUM) | ||
================================================================================================ | ||
|
||
OpenJDK 64-Bit Server VM 11.0.24+8-post-Ubuntu-1ubuntu322.04 on Linux 6.5.0-41-generic | ||
AMD Ryzen 9 7950X3D 16-Core Processor | ||
Grouped HashAgg Exec: single group key (cardinality 1048576), single aggregate SUM: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative | ||
------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ||
SQL Parquet - Spark (SUM) 2663 2744 115 3.9 254.0 1.0X | ||
SQL Parquet - Comet (Scan, Exec) (SUM) 1067 1084 24 9.8 101.8 2.5X | ||
|
||
|
||
================================================================================================ | ||
Grouped Aggregate (single group key + single aggregate COUNT) | ||
================================================================================================ | ||
|
||
OpenJDK 64-Bit Server VM 11.0.24+8-post-Ubuntu-1ubuntu322.04 on Linux 6.5.0-41-generic | ||
AMD Ryzen 9 7950X3D 16-Core Processor | ||
Grouped HashAgg Exec: single group key (cardinality 1048576), single aggregate COUNT: Best Time(ms) Avg Time(ms) Stdev(ms) Rate(M/s) Per Row(ns) Relative | ||
-------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ||
SQL Parquet - Spark (COUNT) 2532 2552 28 4.1 241.5 1.0X | ||
SQL Parquet - Comet (Scan, Exec) (COUNT) 4590 4592 4 2.3 437.7 0.6X | ||
|
||
|
32 changes: 32 additions & 0 deletions
32
spark/src/main/scala/org/apache/comet/expressions/RegExp.scala
This file contains 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,32 @@ | ||
/* | ||
* 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. | ||
*/ | ||
|
||
package org.apache.comet.expressions | ||
|
||
object RegExp { | ||
|
||
/** Determine whether the regexp pattern is supported natively and compatible with Spark */ | ||
def isSupportedPattern(pattern: String): Boolean = { | ||
// this is a placeholder for implementing logic to determine if the pattern | ||
// is known to be compatible with Spark, so that we can enable regexp automatically | ||
// for common cases and fallback to Spark for more complex cases | ||
false | ||
} | ||
|
||
} |
Oops, something went wrong.
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.
I plan on implementing this in a future PR