Skip to content

Commit 1d2b389

Browse files
authored
perf: Optimize contains for scalar search arg (#19529)
## Which issue does this PR close? <!-- We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123. --> - Closes #. ## Rationale for this change <!-- Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed. Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes. --> This PR is an alternative to #19514 that replaces the use of `make_scalar_function` with a new `make_scalar_function_columnar` that avoids expanding scalar values to arrays for each batch. | Benchmark | Old Code | New Code | Improvement | |--------------------------------------------|----------|----------|-------------| | contains_StringViewArray_scalar_strlen_8 | ~97 µs | ~34 µs | 2.8x faster | | contains_StringViewArray_scalar_strlen_32 | ~175 µs | ~37 µs | 4.7x faster | | contains_StringViewArray_scalar_strlen_128 | ~332 µs | ~42 µs | 7.9x faster | | contains_StringViewArray_scalar_strlen_512 | ~371 µs | ~88 µs | 4.2x faster | ## What changes are included in this PR? <!-- There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR. --> ## Are these changes tested? <!-- We typically require tests for all PRs in order to: 1. Prevent the code from being accidentally broken by subsequent changes 2. Serve as another way to document the expected behavior of the code If tests are not included in your PR, please explain why (for example, are they covered by existing tests)? --> Existing tests ## Are there any user-facing changes? <!-- If there are user-facing changes then we may require documentation to be updated before approving the PR. --> No <!-- If there are any breaking changes to public APIs, please add the `api change` label. -->
1 parent 8469aa1 commit 1d2b389

File tree

3 files changed

+248
-31
lines changed

3 files changed

+248
-31
lines changed

datafusion/functions/Cargo.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,11 @@ harness = false
260260
name = "find_in_set"
261261
required-features = ["unicode_expressions"]
262262

263+
[[bench]]
264+
harness = false
265+
name = "contains"
266+
required-features = ["string_expressions"]
267+
263268
[[bench]]
264269
harness = false
265270
name = "starts_with"
Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
18+
extern crate criterion;
19+
20+
use arrow::array::{StringArray, StringViewArray};
21+
use arrow::datatypes::{DataType, Field};
22+
use criterion::{Criterion, criterion_group, criterion_main};
23+
use datafusion_common::ScalarValue;
24+
use datafusion_common::config::ConfigOptions;
25+
use datafusion_expr::{ColumnarValue, ScalarFunctionArgs};
26+
use rand::distr::Alphanumeric;
27+
use rand::prelude::StdRng;
28+
use rand::{Rng, SeedableRng};
29+
use std::hint::black_box;
30+
use std::sync::Arc;
31+
32+
/// Generate a StringArray/StringViewArray with random ASCII strings
33+
fn gen_string_array(
34+
n_rows: usize,
35+
str_len: usize,
36+
is_string_view: bool,
37+
) -> ColumnarValue {
38+
let mut rng = StdRng::seed_from_u64(42);
39+
let strings: Vec<Option<String>> = (0..n_rows)
40+
.map(|_| {
41+
let s: String = (&mut rng)
42+
.sample_iter(&Alphanumeric)
43+
.take(str_len)
44+
.map(char::from)
45+
.collect();
46+
Some(s)
47+
})
48+
.collect();
49+
50+
if is_string_view {
51+
ColumnarValue::Array(Arc::new(StringViewArray::from(strings)))
52+
} else {
53+
ColumnarValue::Array(Arc::new(StringArray::from(strings)))
54+
}
55+
}
56+
57+
/// Generate a scalar search string
58+
fn gen_scalar_search(search_str: &str, is_string_view: bool) -> ColumnarValue {
59+
if is_string_view {
60+
ColumnarValue::Scalar(ScalarValue::Utf8View(Some(search_str.to_string())))
61+
} else {
62+
ColumnarValue::Scalar(ScalarValue::Utf8(Some(search_str.to_string())))
63+
}
64+
}
65+
66+
/// Generate an array of search strings (same string repeated)
67+
fn gen_array_search(
68+
search_str: &str,
69+
n_rows: usize,
70+
is_string_view: bool,
71+
) -> ColumnarValue {
72+
let strings: Vec<Option<String>> =
73+
(0..n_rows).map(|_| Some(search_str.to_string())).collect();
74+
75+
if is_string_view {
76+
ColumnarValue::Array(Arc::new(StringViewArray::from(strings)))
77+
} else {
78+
ColumnarValue::Array(Arc::new(StringArray::from(strings)))
79+
}
80+
}
81+
82+
fn criterion_benchmark(c: &mut Criterion) {
83+
let contains = datafusion_functions::string::contains();
84+
let n_rows = 8192;
85+
let str_len = 128;
86+
let search_str = "xyz"; // A pattern that likely won't be found
87+
88+
// Benchmark: StringArray with scalar search (the optimized path)
89+
let str_array = gen_string_array(n_rows, str_len, false);
90+
let scalar_search = gen_scalar_search(search_str, false);
91+
let arg_fields = vec![
92+
Field::new("a", DataType::Utf8, true).into(),
93+
Field::new("b", DataType::Utf8, true).into(),
94+
];
95+
let return_field = Field::new("f", DataType::Boolean, true).into();
96+
let config_options = Arc::new(ConfigOptions::default());
97+
98+
c.bench_function("contains_StringArray_scalar_search", |b| {
99+
b.iter(|| {
100+
black_box(contains.invoke_with_args(ScalarFunctionArgs {
101+
args: vec![str_array.clone(), scalar_search.clone()],
102+
arg_fields: arg_fields.clone(),
103+
number_rows: n_rows,
104+
return_field: Arc::clone(&return_field),
105+
config_options: Arc::clone(&config_options),
106+
}))
107+
})
108+
});
109+
110+
// Benchmark: StringArray with array search (for comparison)
111+
let array_search = gen_array_search(search_str, n_rows, false);
112+
c.bench_function("contains_StringArray_array_search", |b| {
113+
b.iter(|| {
114+
black_box(contains.invoke_with_args(ScalarFunctionArgs {
115+
args: vec![str_array.clone(), array_search.clone()],
116+
arg_fields: arg_fields.clone(),
117+
number_rows: n_rows,
118+
return_field: Arc::clone(&return_field),
119+
config_options: Arc::clone(&config_options),
120+
}))
121+
})
122+
});
123+
124+
// Benchmark: StringViewArray with scalar search (the optimized path)
125+
let str_view_array = gen_string_array(n_rows, str_len, true);
126+
let scalar_search_view = gen_scalar_search(search_str, true);
127+
let arg_fields_view = vec![
128+
Field::new("a", DataType::Utf8View, true).into(),
129+
Field::new("b", DataType::Utf8View, true).into(),
130+
];
131+
132+
c.bench_function("contains_StringViewArray_scalar_search", |b| {
133+
b.iter(|| {
134+
black_box(contains.invoke_with_args(ScalarFunctionArgs {
135+
args: vec![str_view_array.clone(), scalar_search_view.clone()],
136+
arg_fields: arg_fields_view.clone(),
137+
number_rows: n_rows,
138+
return_field: Arc::clone(&return_field),
139+
config_options: Arc::clone(&config_options),
140+
}))
141+
})
142+
});
143+
144+
// Benchmark: StringViewArray with array search (for comparison)
145+
let array_search_view = gen_array_search(search_str, n_rows, true);
146+
c.bench_function("contains_StringViewArray_array_search", |b| {
147+
b.iter(|| {
148+
black_box(contains.invoke_with_args(ScalarFunctionArgs {
149+
args: vec![str_view_array.clone(), array_search_view.clone()],
150+
arg_fields: arg_fields_view.clone(),
151+
number_rows: n_rows,
152+
return_field: Arc::clone(&return_field),
153+
config_options: Arc::clone(&config_options),
154+
}))
155+
})
156+
});
157+
158+
// Benchmark different string lengths with scalar search
159+
for str_len in [8, 32, 128, 512] {
160+
let str_array = gen_string_array(n_rows, str_len, true);
161+
let scalar_search = gen_scalar_search(search_str, true);
162+
let arg_fields = vec![
163+
Field::new("a", DataType::Utf8View, true).into(),
164+
Field::new("b", DataType::Utf8View, true).into(),
165+
];
166+
167+
c.bench_function(
168+
&format!("contains_StringViewArray_scalar_strlen_{str_len}"),
169+
|b| {
170+
b.iter(|| {
171+
black_box(contains.invoke_with_args(ScalarFunctionArgs {
172+
args: vec![str_array.clone(), scalar_search.clone()],
173+
arg_fields: arg_fields.clone(),
174+
number_rows: n_rows,
175+
return_field: Arc::clone(&return_field),
176+
config_options: Arc::clone(&config_options),
177+
}))
178+
})
179+
},
180+
);
181+
}
182+
}
183+
184+
criterion_group!(benches, criterion_benchmark);
185+
criterion_main!(benches);

datafusion/functions/src/string/contains.rs

Lines changed: 58 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,12 @@
1515
// specific language governing permissions and limitations
1616
// under the License.
1717

18-
use crate::utils::make_scalar_function;
19-
use arrow::array::{Array, ArrayRef, AsArray};
18+
use arrow::array::{Array, ArrayRef, Scalar};
2019
use arrow::compute::contains as arrow_contains;
2120
use arrow::datatypes::DataType;
2221
use arrow::datatypes::DataType::{Boolean, LargeUtf8, Utf8, Utf8View};
2322
use datafusion_common::types::logical_string;
24-
use datafusion_common::{DataFusionError, Result, exec_err};
23+
use datafusion_common::{Result, exec_err};
2524
use datafusion_expr::binary::{binary_to_string_coercion, string_coercion};
2625
use datafusion_expr::{
2726
Coercion, ColumnarValue, Documentation, ScalarFunctionArgs, ScalarUDFImpl, Signature,
@@ -89,51 +88,79 @@ impl ScalarUDFImpl for ContainsFunc {
8988
}
9089

9190
fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
92-
make_scalar_function(contains, vec![])(&args.args)
91+
contains(args.args.as_slice())
9392
}
9493

9594
fn documentation(&self) -> Option<&Documentation> {
9695
self.doc()
9796
}
9897
}
9998

99+
fn to_array(value: &ColumnarValue) -> Result<(ArrayRef, bool)> {
100+
match value {
101+
ColumnarValue::Array(array) => Ok((Arc::clone(array), false)),
102+
ColumnarValue::Scalar(scalar) => Ok((scalar.to_array()?, true)),
103+
}
104+
}
105+
106+
/// Helper to call arrow_contains with proper Datum handling.
107+
/// When an argument is marked as scalar, we wrap it in `Scalar` to tell arrow's
108+
/// kernel to use the optimized single-value code path instead of iterating.
109+
fn call_arrow_contains(
110+
haystack: &ArrayRef,
111+
haystack_is_scalar: bool,
112+
needle: &ArrayRef,
113+
needle_is_scalar: bool,
114+
) -> Result<ColumnarValue> {
115+
// Arrow's Datum trait is implemented for ArrayRef, Arc<dyn Array>, and Scalar<T>
116+
// We pass ArrayRef directly when not scalar, or wrap in Scalar when it is
117+
let result = match (haystack_is_scalar, needle_is_scalar) {
118+
(false, false) => arrow_contains(haystack, needle)?,
119+
(false, true) => arrow_contains(haystack, &Scalar::new(Arc::clone(needle)))?,
120+
(true, false) => arrow_contains(&Scalar::new(Arc::clone(haystack)), needle)?,
121+
(true, true) => arrow_contains(
122+
&Scalar::new(Arc::clone(haystack)),
123+
&Scalar::new(Arc::clone(needle)),
124+
)?,
125+
};
126+
127+
// If both inputs were scalar, return a scalar result
128+
if haystack_is_scalar && needle_is_scalar {
129+
let scalar = datafusion_common::ScalarValue::try_from_array(&result, 0)?;
130+
Ok(ColumnarValue::Scalar(scalar))
131+
} else {
132+
Ok(ColumnarValue::Array(Arc::new(result)))
133+
}
134+
}
135+
100136
/// use `arrow::compute::contains` to do the calculation for contains
101-
fn contains(args: &[ArrayRef]) -> Result<ArrayRef, DataFusionError> {
137+
fn contains(args: &[ColumnarValue]) -> Result<ColumnarValue> {
138+
let (haystack, haystack_is_scalar) = to_array(&args[0])?;
139+
let (needle, needle_is_scalar) = to_array(&args[1])?;
140+
102141
if let Some(coercion_data_type) =
103-
string_coercion(args[0].data_type(), args[1].data_type()).or_else(|| {
104-
binary_to_string_coercion(args[0].data_type(), args[1].data_type())
142+
string_coercion(haystack.data_type(), needle.data_type()).or_else(|| {
143+
binary_to_string_coercion(haystack.data_type(), needle.data_type())
105144
})
106145
{
107-
let arg0 = if args[0].data_type() == &coercion_data_type {
108-
Arc::clone(&args[0])
146+
let haystack = if haystack.data_type() == &coercion_data_type {
147+
haystack
109148
} else {
110-
arrow::compute::kernels::cast::cast(&args[0], &coercion_data_type)?
149+
arrow::compute::kernels::cast::cast(&haystack, &coercion_data_type)?
111150
};
112-
let arg1 = if args[1].data_type() == &coercion_data_type {
113-
Arc::clone(&args[1])
151+
let needle = if needle.data_type() == &coercion_data_type {
152+
needle
114153
} else {
115-
arrow::compute::kernels::cast::cast(&args[1], &coercion_data_type)?
154+
arrow::compute::kernels::cast::cast(&needle, &coercion_data_type)?
116155
};
117156

118157
match coercion_data_type {
119-
Utf8View => {
120-
let mod_str = arg0.as_string_view();
121-
let match_str = arg1.as_string_view();
122-
let res = arrow_contains(mod_str, match_str)?;
123-
Ok(Arc::new(res) as ArrayRef)
124-
}
125-
Utf8 => {
126-
let mod_str = arg0.as_string::<i32>();
127-
let match_str = arg1.as_string::<i32>();
128-
let res = arrow_contains(mod_str, match_str)?;
129-
Ok(Arc::new(res) as ArrayRef)
130-
}
131-
LargeUtf8 => {
132-
let mod_str = arg0.as_string::<i64>();
133-
let match_str = arg1.as_string::<i64>();
134-
let res = arrow_contains(mod_str, match_str)?;
135-
Ok(Arc::new(res) as ArrayRef)
136-
}
158+
Utf8View | Utf8 | LargeUtf8 => call_arrow_contains(
159+
&haystack,
160+
haystack_is_scalar,
161+
&needle,
162+
needle_is_scalar,
163+
),
137164
other => {
138165
exec_err!("Unsupported data type {other:?} for function `contains`.")
139166
}

0 commit comments

Comments
 (0)