Skip to content
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

Add regexp_like, improve docs and examples for regexp_match` #9137

Merged
merged 8 commits into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions datafusion-examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,21 +52,22 @@ cargo run --example csv_sql
- [`dataframe_output.rs`](examples/dataframe_output.rs): Examples of methods which write data out from a DataFrame
- [`dataframe_in_memory.rs`](examples/dataframe_in_memory.rs): Run a query using a DataFrame against data in memory
- [`deserialize_to_struct.rs`](examples/deserialize_to_struct.rs): Convert query results into rust structs using serde
- [`expr_api.rs`](examples/expr_api.rs): Create, execute, simplify and anaylze `Expr`s
- [`expr_api.rs`](examples/expr_api.rs): Create, execute, simplify and analyze `Expr`s
- [`flight_sql_server.rs`](examples/flight/flight_sql_server.rs): Run DataFusion as a standalone process and execute SQL queries from JDBC clients
- [`make_date.rs`](examples/make_date.rs): Examples of using the make_date function
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you 🙏

- [`memtable.rs`](examples/memtable.rs): Create an query data in memory using SQL and `RecordBatch`es
- [`parquet_sql.rs`](examples/parquet_sql.rs): Build and run a query plan from a SQL statement against a local Parquet file
- [`parquet_sql_multiple_files.rs`](examples/parquet_sql_multiple_files.rs): Build and run a query plan from a SQL statement against multiple local Parquet files
- [`query-aws-s3.rs`](examples/external_dependency/query-aws-s3.rs): Configure `object_store` and run a query against files stored in AWS S3
- [`query-http-csv.rs`](examples/query-http-csv.rs): Configure `object_store` and run a query against files vi HTTP
- [`regexp.rs`](examples/regexp.rs): Examples of using regular expression functions
- [`rewrite_expr.rs`](examples/rewrite_expr.rs): Define and invoke a custom Query Optimizer pass
- [`to_timestamp.rs`](examples/to_timestamp.rs): Examples of using to_timestamp functions
- [`simple_udf.rs`](examples/simple_udf.rs): Define and invoke a User Defined Scalar Function (UDF)
- [`advanced_udf.rs`](examples/advanced_udf.rs): Define and invoke a more complicated User Defined Scalar Function (UDF)
- [`simple_udaf.rs`](examples/simple_udaf.rs): Define and invoke a User Defined Aggregate Function (UDAF)
- [`advanced_udaf.rs`](examples/advanced_udaf.rs): Define and invoke a more complicated User Defined Aggregate Function (UDAF)
- [`simple_udfw.rs`](examples/simple_udwf.rs): Define and invoke a User Defined Window Function (UDWF)
- [`make_date.rs`](examples/make_date.rs): Examples of using the make_date function
- [`to_timestamp.rs`](examples/to_timestamp.rs): Examples of using the to_timestamp functions
- [`advanced_udwf.rs`](examples/advanced_udwf.rs): Define and invoke a more complicated User Defined Window Function (UDWF)

## Distributed
Expand Down
187 changes: 187 additions & 0 deletions datafusion-examples/examples/regexp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
// Licensed to the Apache Software Foundation (ASF) under one
// 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
//
Omega359 marked this conversation as resolved.
Show resolved Hide resolved
// 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::array::BooleanArray;

use datafusion::arrow::datatypes::{DataType, Field, Schema};
use datafusion::arrow::record_batch::RecordBatch;
use datafusion::error::Result;
use datafusion::prelude::*;
use datafusion_common::assert_contains;

/// This example demonstrates how to use the regexp_* functions
///
/// the full list of supported features and
/// syntax can be found at
/// https://docs.rs/regex/latest/regex/#syntax
///
/// Supported flags can be found at
/// https://docs.rs/regex/latest/regex/#grouping-and-flags
#[tokio::main]
async fn main() -> Result<()> {
let ctx = SessionContext::new();
ctx.register_csv(
"examples",
"../../datafusion/physical-expr/tests/data/regex.csv",
CsvReadOptions::new(),
)
.await?;

//
//
//regexp_like examples
//
//
// regexp_like format is (regexp_replace(text, regex[, flags])
//

// use sql and regexp_like function to test col 'values', against patterns in col 'patterns' without flags
let df = ctx
.sql("select regexp_like(values, patterns) from examples")
.await?;

// print the results
df.show().await?;

// use dataframe and regexp_like function to test col 'values', against patterns in col 'patterns' with flags
let df = ctx
.sql("select regexp_like(values, patterns, flags) from examples")
.await?;

df.show().await?;

// literals work as well
// to match against the entire input use ^ and $ in the regex
let df = ctx.sql("select regexp_like('John Smith', '^.*Smith$'), regexp_like('Smith Jones', '^Smith.*$')").await?;

df.show().await?;

// look-around and back references are not supported for performance
// reasons.
// Note that an error may not always be returned but the result
// if returned will always be false
let result = ctx
.sql(r"select regexp_like('(?<=[A-Z]\w )Smith', 'John Smith', 'i') as a")
.await?
.collect()
.await;

let expected = RecordBatch::try_new(
Arc::new(Schema::new(vec![Field::new("a", DataType::Boolean, false)])),
vec![Arc::new(BooleanArray::from(vec![false]))],
)
.unwrap();

assert!(result.is_ok());
let result = result.unwrap();

assert_eq!(result.len(), 1);
assert_eq!(format!("{:?}", result[0]), format!("{expected:?}"));

// invalid flags will result in an error
let result = ctx
.sql(r"select regexp_like('\b4(?!000)\d\d\d\b', 4010, 'g')")
.await?
.collect()
.await;

let expected = "regexp_like() does not support the \"global\" option";
assert_contains!(result.unwrap_err().to_string(), expected);

// there is a size limit on the regex during regex compilation
let result = ctx
.sql("select regexp_like('aaaaa', 'a{5}{5}{5}{5}{5}{5}{5}{5}{5}{5}{5}{5}{5}{5}{5}{5}{5}{5}')")
.await?
.collect()
.await;

let expected = "Regular expression did not compile: CompiledTooBig";
assert_contains!(result.unwrap_err().to_string(), expected);

//
//
//regexp_match examples
//
//
// regexp_match format is (regexp_replace(text, regex[, flags])
//

let df = ctx.table("examples").await?;

df.show().await?;

// use sql and regexp_match function to test col 'values', against patterns in col 'patterns' without flags
let df = ctx
.sql("select regexp_match(values, patterns) from examples")
.await?;

df.show().await?;

// use dataframe and regexp_match function to test col 'values', against patterns in col 'patterns' with flags
let df = ctx
.sql("select regexp_match(values, patterns, flags) from examples")
.await?;

df.show().await?;

// literals work as well
// to match against the entire input use ^ and $ in the regex
let df = ctx.sql("select regexp_match('John Smith', '^.*Smith$'), regexp_match('Smith Jones', '^Smith.*$')").await?;

df.show().await?;

//
//
//regexp_replace examples
//
//
// regexp_replace format is (regexp_replace(text, regex, replace, flags)
//

// use regexp_replace function against tables
let df = ctx
.sql("SELECT regexp_replace(values, patterns, replacement, flags) FROM examples")
.await?;

df.show().await?;

// global flag example
let df = ctx
.sql("SELECT regexp_replace('foobarbaz', 'b(..)', 'X\\1Y', 'g')")
.await?;

df.show().await?;

// without global flag
let df = ctx
.sql("SELECT regexp_replace('foobarbaz', 'b(..)', 'X\\1Y', null)")
.await?;

df.show().await?;

// null regex means null result
let df = ctx
.sql("SELECT regexp_replace('foobarbaz', NULL, 'X\\1Y', 'g')")
.await?;

df.show().await?;

Ok(())
}
21 changes: 21 additions & 0 deletions datafusion/core/tests/dataframe/dataframe_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,27 @@ async fn test_fn_md5() -> Result<()> {
Ok(())
}

#[tokio::test]
#[cfg(feature = "unicode_expressions")]
async fn test_fn_regexp_like() -> Result<()> {
let expr = regexp_like(vec![col("a"), lit("[a-z]")]);

let expected = [
"+-----------------------------------+",
"| regexp_like(test.a,Utf8(\"[a-z]\")) |",
"+-----------------------------------+",
"| true |",
"| true |",
"| true |",
"| true |",
"+-----------------------------------+",
];

assert_fn_batches!(expr, expected);

Ok(())
}

#[tokio::test]
#[cfg(feature = "unicode_expressions")]
async fn test_fn_regexp_match() -> Result<()> {
Expand Down
42 changes: 32 additions & 10 deletions datafusion/expr/src/built_in_function.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,10 @@ pub enum BuiltinScalarFunction {
OctetLength,
/// random
Random,
/// regexp_like
RegexpLike,
/// regexp_match
RegexpMatch,
/// regexp_replace
RegexpReplace,
/// repeat
Expand Down Expand Up @@ -303,8 +307,6 @@ pub enum BuiltinScalarFunction {
Upper,
/// uuid
Uuid,
/// regexp_match
RegexpMatch,
/// arrow_typeof
ArrowTypeof,
/// overlay
Expand Down Expand Up @@ -460,6 +462,8 @@ impl BuiltinScalarFunction {
BuiltinScalarFunction::NullIf => Volatility::Immutable,
BuiltinScalarFunction::OctetLength => Volatility::Immutable,
BuiltinScalarFunction::Radians => Volatility::Immutable,
BuiltinScalarFunction::RegexpLike => Volatility::Immutable,
BuiltinScalarFunction::RegexpMatch => Volatility::Immutable,
BuiltinScalarFunction::RegexpReplace => Volatility::Immutable,
BuiltinScalarFunction::Repeat => Volatility::Immutable,
BuiltinScalarFunction::Replace => Volatility::Immutable,
Expand Down Expand Up @@ -487,7 +491,6 @@ impl BuiltinScalarFunction {
BuiltinScalarFunction::Translate => Volatility::Immutable,
BuiltinScalarFunction::Trim => Volatility::Immutable,
BuiltinScalarFunction::Upper => Volatility::Immutable,
BuiltinScalarFunction::RegexpMatch => Volatility::Immutable,
BuiltinScalarFunction::Struct => Volatility::Immutable,
BuiltinScalarFunction::FromUnixtime => Volatility::Immutable,
BuiltinScalarFunction::ArrowTypeof => Volatility::Immutable,
Expand Down Expand Up @@ -819,13 +822,22 @@ impl BuiltinScalarFunction {
BuiltinScalarFunction::Upper => {
utf8_to_str_type(&input_expr_types[0], "upper")
}
BuiltinScalarFunction::RegexpLike => Ok(match input_expr_types[0] {
LargeUtf8 | Utf8 => Boolean,
Null => Null,
_ => {
return plan_err!(
"The regexp_like function can only accept strings."
);
}
}),
BuiltinScalarFunction::RegexpMatch => Ok(match input_expr_types[0] {
LargeUtf8 => List(Arc::new(Field::new("item", LargeUtf8, true))),
Utf8 => List(Arc::new(Field::new("item", Utf8, true))),
Null => Null,
_ => {
return plan_err!(
"The regexp_extract function can only accept strings."
"The regexp_match function can only accept strings."
);
}
}),
Expand Down Expand Up @@ -1230,17 +1242,15 @@ impl BuiltinScalarFunction {
BuiltinScalarFunction::Replace | BuiltinScalarFunction::Translate => {
Signature::one_of(vec![Exact(vec![Utf8, Utf8, Utf8])], self.volatility())
}
BuiltinScalarFunction::RegexpReplace => Signature::one_of(
BuiltinScalarFunction::RegexpLike => Signature::one_of(
vec![
Exact(vec![Utf8, Utf8]),
Exact(vec![LargeUtf8, Utf8]),
Exact(vec![Utf8, Utf8, Utf8]),
Exact(vec![Utf8, Utf8, Utf8, Utf8]),
Exact(vec![LargeUtf8, Utf8, Utf8]),
],
self.volatility(),
),

BuiltinScalarFunction::NullIf => {
Signature::uniform(2, SUPPORTED_NULLIF_TYPES.to_vec(), self.volatility())
}
BuiltinScalarFunction::RegexpMatch => Signature::one_of(
vec![
Exact(vec![Utf8, Utf8]),
Expand All @@ -1250,6 +1260,17 @@ impl BuiltinScalarFunction {
],
self.volatility(),
),
BuiltinScalarFunction::RegexpReplace => Signature::one_of(
vec![
Exact(vec![Utf8, Utf8, Utf8]),
Exact(vec![Utf8, Utf8, Utf8, Utf8]),
],
self.volatility(),
),

BuiltinScalarFunction::NullIf => {
Signature::uniform(2, SUPPORTED_NULLIF_TYPES.to_vec(), self.volatility())
}
BuiltinScalarFunction::Pi => Signature::exact(vec![], self.volatility()),
BuiltinScalarFunction::Random => Signature::exact(vec![], self.volatility()),
BuiltinScalarFunction::Uuid => Signature::exact(vec![], self.volatility()),
Expand Down Expand Up @@ -1491,6 +1512,7 @@ impl BuiltinScalarFunction {
BuiltinScalarFunction::FindInSet => &["find_in_set"],

// regex functions
BuiltinScalarFunction::RegexpLike => &["regexp_like"],
BuiltinScalarFunction::RegexpMatch => &["regexp_match"],
BuiltinScalarFunction::RegexpReplace => &["regexp_replace"],

Expand Down
13 changes: 10 additions & 3 deletions datafusion/expr/src/expr_fn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -859,15 +859,20 @@ nary_scalar_expr!(
"fill up a string to the length by appending the characters"
);
nary_scalar_expr!(
RegexpReplace,
regexp_replace,
"replace strings that match a regular expression"
RegexpLike,
regexp_like,
"matches a regular expression against a string and returns true or false if there was at least one match or not"
);
nary_scalar_expr!(
RegexpMatch,
regexp_match,
"matches a regular expression against a string and returns matched substrings."
);
nary_scalar_expr!(
RegexpReplace,
regexp_replace,
"replace strings that match a regular expression"
);
nary_scalar_expr!(
Btrim,
btrim,
Expand Down Expand Up @@ -1385,6 +1390,8 @@ mod test {
test_scalar_expr!(Ltrim, ltrim, string);
test_scalar_expr!(MD5, md5, string);
test_scalar_expr!(OctetLength, octet_length, string);
test_nary_scalar_expr!(RegexpLike, regexp_like, string, pattern);
test_nary_scalar_expr!(RegexpLike, regexp_like, string, pattern, flags);
test_nary_scalar_expr!(RegexpMatch, regexp_match, string, pattern);
test_nary_scalar_expr!(RegexpMatch, regexp_match, string, pattern, flags);
test_nary_scalar_expr!(
Expand Down
Loading
Loading