This is an automated email from the ASF dual-hosted git repository.
github-merge-queue[bot] pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-rs.git
The following commit(s) were added to refs/heads/main by this push:
new 0ada6ff1ae feat(arrow-string): support run-end encoded operands in
like kernels (#12154)
0ada6ff1ae is described below
commit 0ada6ff1ae5f500efd51757993abbfa9fa558a53
Author: Alfonso Subiotto Marqués <[email protected]>
AuthorDate: Fri Nov 13 20:35:08 2026 +0000
feat(arrow-string): support run-end encoded operands in like kernels
(#12154)
# Which issue does this PR close?
- Closes #12153.
# Rationale for this change
The string matching kernels return an error for `RunEndEncoded` inputs,
so callers have to decode before filtering.
# What changes are included in this PR?
`like`, `ilike`, `nlike`, `nilike`, `starts_with`, `ends_with`,
`contains` and `eq_ignore_ascii_case` accept run-end encoded operands,
including run-end encoded dictionaries. Value types are the same as for
unencoded inputs, so binary values also work with `starts_with`,
`ends_with` and `contains`.
Run-end encoded operands are rewritten into encodings the kernels
already support:
- **Against a scalar**: match each run once and repeat the result across
the run.
- **Two arrays**: look up each row through a dictionary view of the
runs, without copying values.
Adds an `ree_like` benchmark group.
# Are these changes tested?
Yes. The existing string test macros also run each case on `RunArray`,
and new tests cover slicing mid-run, nulls, dictionary values, run-end
encoded patterns, empty inputs, type errors and binary values.
Benchmarks for 65,536 rows:
| Benchmark | phys=64 | phys=1024 | phys=32768 |
|---|---|---|---|
| `like_flat_scalar` | 335 µs | 326 µs | 330 µs |
| `like_ree_scalar` | 0.86 µs | 9.4 µs | 257 µs |
| `like_ree_dict_scalar` | 1.03 µs | 10.0 µs | 271 µs |
| `like_ree_decoded_scalar` | 787 µs | 847 µs | 976 µs |
| `like_ree_flat` | 871 µs | 887 µs | 1.21 ms |
# Are there any significant user-facing changes?
No. Run-end encoded inputs that previously returned an error are now
supported.
AI assistance was used for this PR but I thoroughly reviewed this change
before opening a PR.
cc @alamb @Rich-T-kid
---------
Co-authored-by: Amp <[email protected]>
---
arrow-string/src/like.rs | 273 +++++++++++++++++++++++++++++++++++-
arrow/benches/comparison_kernels.rs | 44 ++++++
2 files changed, 312 insertions(+), 5 deletions(-)
diff --git a/arrow-string/src/like.rs b/arrow-string/src/like.rs
index 4867268831..f23c987cde 100644
--- a/arrow-string/src/like.rs
+++ b/arrow-string/src/like.rs
@@ -10,10 +10,14 @@
use crate::predicate::Predicate;
+use arrow_array::builder::BooleanBuilder;
use arrow_array::cast::AsArray;
+use arrow_array::types::{ArrowDictionaryKeyType, RunEndIndexType};
use arrow_array::*;
+use arrow_buffer::ArrowNativeType;
use arrow_schema::*;
use arrow_select::take::take;
+use std::sync::Arc;
use crate::binary_like::binary_apply;
pub use arrow_array::StringArrayType;
@@ -52,6 +56,9 @@ impl std::fmt::Display for Op {
/// - LargeUtf8
/// - Utf8View
///
+/// Either operand may be dictionary or run-end encoded, including
dictionary-encoded
+/// run values, as long as the underlying value types match.
+///
/// There are two wildcards supported with the LIKE operator:
///
/// 1. `%` - The percent sign represents zero, one, or multiple characters
@@ -112,6 +119,9 @@ pub fn nilike(left: &dyn Datum, right: &dyn Datum) ->
Result<BooleanArray, Arrow
/// - LargeBinary
/// - BinaryView
///
+/// Either operand may be dictionary or run-end encoded, including
dictionary-encoded
+/// run values, as long as the underlying value types match.
+///
/// # Example
/// ```
/// # use arrow_array::{StringArray, BooleanArray};
@@ -138,6 +148,9 @@ pub fn starts_with(left: &dyn Datum, right: &dyn Datum) ->
Result<BooleanArray,
/// - LargeBinary
/// - BinaryView
///
+/// Either operand may be dictionary or run-end encoded, including
dictionary-encoded
+/// run values, as long as the underlying value types match.
+///
/// # Example
/// ```
/// # use arrow_array::{StringArray, BooleanArray};
@@ -164,6 +177,9 @@ pub fn ends_with(left: &dyn Datum, right: &dyn Datum) ->
Result<BooleanArray, Ar
/// - LargeBinary
/// - BinaryView
///
+/// Either operand may be dictionary or run-end encoded, including
dictionary-encoded
+/// run values, as long as the underlying value types match.
+///
/// # Example
/// ```
/// # use arrow_array::{StringArray, BooleanArray};
@@ -185,6 +201,9 @@ pub fn contains(left: &dyn Datum, right: &dyn Datum) ->
Result<BooleanArray, Arr
/// - LargeUtf8
/// - Utf8View
///
+/// Either operand may be dictionary or run-end encoded, including
dictionary-encoded
+/// run values, as long as the underlying value types match.
+///
/// # Example
/// ```
/// # use arrow_array::{StringArray, BooleanArray};
@@ -215,6 +234,10 @@ fn like_op(op: Op, lhs: &dyn Datum, rhs: &dyn Datum) ->
Result<BooleanArray, Arr
)));
}
+ if l.as_any_ree_opt().is_some() || r.as_any_ree_opt().is_some() {
+ return run_end_encoded_op(op, lhs, rhs);
+ }
+
let l_v = l.as_any_dictionary_opt();
let l = l_v.map(|x| x.values().as_ref()).unwrap_or(l);
@@ -282,6 +305,115 @@ fn like_op(op: Op, lhs: &dyn Datum, rhs: &dyn Datum) ->
Result<BooleanArray, Arr
}
}
+/// Rewrites run-end encoded operands into encodings that [`like_op`] already
supports,
+/// so value types, nulls and errors behave as they do without run-end
encoding.
+fn run_end_encoded_op(
+ op: Op,
+ lhs: &dyn Datum,
+ rhs: &dyn Datum,
+) -> Result<BooleanArray, ArrowError> {
+ let (left, left_is_scalar) = lhs.get();
+ let (right, right_is_scalar) = rhs.get();
+ let left_is_ree = left.as_any_ree_opt().is_some();
+ let right_is_ree = right.as_any_ree_opt().is_some();
+ if left_is_ree && left_is_scalar {
+ // A scalar's only logical value is its only physical value.
+ like_op(op, &Scalar::new(run_values(left)), rhs)
+ } else if right_is_ree && right_is_scalar {
+ like_op(op, lhs, &Scalar::new(run_values(right)))
+ } else if right_is_scalar {
+ // Against a scalar every row of a run has the same result, so match
each
+ // run once and repeat its result.
+ Ok(expand_runs(left, &like_op(op, &run_values(left), rhs)?))
+ } else if left_is_scalar {
+ Ok(expand_runs(right, &like_op(op, lhs, &run_values(right))?))
+ } else if left.is_empty() {
+ // The dictionary kernels panic on a dictionary without values, so
match the
+ // run values instead. They are empty too, and like_op still checks
their types.
+ let left_values = left_is_ree.then(|| run_values(left));
+ let right_values = right_is_ree.then(|| run_values(right));
+ let lhs: &dyn Datum = left_values.as_ref().map_or(lhs, |values|
values);
+ let rhs: &dyn Datum = right_values.as_ref().map_or(rhs, |values|
values);
+ like_op(op, lhs, rhs)
+ } else {
+ // Rows of two arrays need not share run boundaries, so look up each
row
+ // through a dictionary view, which does not copy the values.
+ let left_dictionary = left_is_ree
+ .then(|| run_end_encoded_as_dictionary(left))
+ .transpose()?;
+ let right_dictionary = right_is_ree
+ .then(|| run_end_encoded_as_dictionary(right))
+ .transpose()?;
+ let lhs: &dyn Datum = left_dictionary
+ .as_ref()
+ .map_or(lhs, |dictionary| dictionary);
+ let rhs: &dyn Datum = right_dictionary
+ .as_ref()
+ .map_or(rhs, |dictionary| dictionary);
+ like_op(op, lhs, rhs)
+ }
+}
+
+/// Returns the physical values of the runs that a run-end encoded array's
slice covers.
+fn run_values(array: &dyn Array) -> ArrayRef {
+ downcast_run_array!(
+ array => array.values_slice(),
+ _ => unreachable!("expected a run-end encoded array")
+ )
+}
+
+/// Repeats each run's result, as computed over [`run_values`], for every row
of the run.
+fn expand_runs(array: &dyn Array, run_results: &BooleanArray) -> BooleanArray {
+ downcast_run_array!(
+ array => {
+ let mut builder = BooleanBuilder::with_capacity(array.len());
+ let mut run_start = 0;
+ for (run_result, run_end) in
run_results.iter().zip(array.run_ends().sliced_values()) {
+ let run_end = run_end.as_usize();
+ match run_result {
+ Some(run_result) => builder.append_n(run_end - run_start,
run_result),
+ None => builder.append_nulls(run_end - run_start),
+ }
+ run_start = run_end;
+ }
+ builder.finish()
+ },
+ _ => unreachable!("expected a run-end encoded array")
+ )
+}
+
+fn run_end_encoded_as_dictionary(array: &dyn Array) -> Result<ArrayRef,
ArrowError> {
+ downcast_run_array!(
+ array => run_array_as_dictionary(array),
+ _ => unreachable!("expected a run-end encoded array")
+ )
+}
+
+/// Views a run array as a dictionary whose keys are each row's index into
[`run_values`].
+fn run_array_as_dictionary<R: RunEndIndexType + ArrowDictionaryKeyType>(
+ array: &RunArray<R>,
+) -> Result<ArrayRef, ArrowError> {
+ let mut keys = Vec::with_capacity(array.len());
+ let mut run_start = 0;
+ for (run_index, run_end) in array.run_ends().sliced_values().enumerate() {
+ let run_end = run_end.as_usize();
+ keys.extend(std::iter::repeat_n(
+ R::Native::usize_as(run_index),
+ run_end - run_start,
+ ));
+ run_start = run_end;
+ }
+ let keys = PrimitiveArray::<R>::new(keys.into(), None);
+ let values = array.values_slice();
+ if values.as_any_dictionary_opt().is_some() {
+ // Taking from a dictionary composes the keys, leaving a single
dictionary
+ // layer for like_op to unwrap.
+ take(&values, &keys, None)
+ } else {
+ Ok(Arc::new(DictionaryArray::try_new(keys, values)?))
+ }
+}
+
fn string_apply<'a, T: StringArrayType<'a> + 'a>(
op: Op,
l: T,
@@ -422,7 +554,7 @@ fn binary_predicate<'a>(
mod tests {
use super::*;
use arrow_array::builder::BinaryDictionaryBuilder;
- use arrow_array::types::{ArrowDictionaryKeyType, Int8Type};
+ use arrow_array::types::{ArrowDictionaryKeyType, Int8Type, Int32Type,
Int64Type};
use std::iter::zip;
fn convert_binary_iterator_to_binary_dictionary<
@@ -445,11 +577,12 @@ mod tests {
}
/// Applying `op(left, right)`, both sides are arrays
- /// The macro tests four types of array implementations:
+ /// The macro tests five types of array implementations:
/// - `StringArray`
/// - `LargeStringArray`
/// - `StringViewArray`
/// - `DictionaryArray`
+ /// - `RunArray`
macro_rules! test_utf8 {
($(#[$attr:meta])* $test_name:ident, $left:expr, $right:expr,
$op:expr, $expected:expr) => {
$(#[$attr])*
@@ -476,16 +609,22 @@ mod tests {
let right: DictionaryArray<Int8Type> =
$right.into_iter().collect();
let res = $op(&left, &right).unwrap();
assert_eq!(res, expected);
+
+ let left: RunArray<Int32Type> = $left.into_iter().collect();
+ let right: RunArray<Int32Type> = $right.into_iter().collect();
+ let res = $op(&left, &right).unwrap();
+ assert_eq!(res, expected);
}
};
}
/// Applying `op(left, right)`, both sides are arrays
- /// The macro tests four types of array implementations:
+ /// The macro tests five types of array implementations:
/// - `StringArray`
/// - `LargeStringArray`
/// - `StringViewArray`
/// - `DictionaryArray`
+ /// - `RunArray`
macro_rules! test_utf8_and_binary {
($test_name:ident, $left:expr, $right:expr, $op:expr, $expected:expr)
=> {
#[test]
@@ -512,6 +651,11 @@ mod tests {
let res = $op(&left, &right).unwrap();
assert_eq!(res, expected);
+ let left: RunArray<Int32Type> = $left.into_iter().collect();
+ let right: RunArray<Int32Type> = $right.into_iter().collect();
+ let res = $op(&left, &right).unwrap();
+ assert_eq!(res, expected);
+
let left_binary = $left.iter().map(|x|
x.as_bytes()).collect::<Vec<&[u8]>>();
let right_binary = $right.iter().map(|x|
x.as_bytes()).collect::<Vec<&[u8]>>();
@@ -536,11 +680,12 @@ mod tests {
}
/// Applying `op(left, right)`, left side is array, right side is scalar
- /// The macro tests four types of array implementations:
+ /// The macro tests five types of array implementations:
/// - `StringArray`
/// - `LargeStringArray`
/// - `StringViewArray`
/// - `DictionaryArray`
+ /// - `RunArray`
macro_rules! test_utf8_scalar {
($(#[$attr:meta])* $test_name:ident, $left:expr, $right:expr,
$op:expr, $expected:expr) => {
$(#[$attr])*
@@ -571,16 +716,22 @@ mod tests {
let right: DictionaryArray<Int8Type> =
[$right].into_iter().collect();
let res = $op(&left, &Scalar::new(&right)).unwrap();
assert_eq!(res, expected);
+
+ let left: RunArray<Int32Type> = $left.into_iter().collect();
+ let right: RunArray<Int32Type> =
[$right].into_iter().collect();
+ let res = $op(&left, &Scalar::new(&right)).unwrap();
+ assert_eq!(res, expected);
}
};
}
/// Applying `op(left, right)`, left side is array, right side is scalar
- /// The macro tests four types of array implementations:
+ /// The macro tests five types of array implementations:
/// - `StringArray`
/// - `LargeStringArray`
/// - `StringViewArray`
/// - `DictionaryArray`
+ /// - `RunArray`
macro_rules! test_utf8_and_binary_scalar {
($test_name:ident, $left:expr, $right:expr, $op:expr, $expected:expr)
=> {
#[test]
@@ -607,6 +758,11 @@ mod tests {
let res = $op(&left, &Scalar::new(&right)).unwrap();
assert_eq!(res, expected);
+ let left: RunArray<Int32Type> = $left.into_iter().collect();
+ let right: RunArray<Int32Type> =
[$right].into_iter().collect();
+ let res = $op(&left, &Scalar::new(&right)).unwrap();
+ assert_eq!(res, expected);
+
let left_binary = $left.iter().map(|x|
x.as_bytes()).collect::<Vec<&[u8]>>();
let right_binary: &[u8] = $right.as_ref();
@@ -1582,6 +1738,113 @@ mod tests {
}
}
+ #[test]
+ fn test_run_end_encoded_sliced() {
+ // Logical rows after the slice: ["arrow", null, null, "Parquet",
"Parquet"].
+ // The slice starts and ends mid-run and skips the first run entirely.
+ let run_ends = Int32Array::from(vec![2, 4, 6, 9]);
+ let values = vec![Some("skipped"), Some("arrow"), None,
Some("Parquet")];
+ let dictionary: DictionaryArray<Int8Type> =
values.clone().into_iter().collect();
+ let patterns =
+ StringArray::from(vec![Some("%row"), Some("%"), None, Some("P%"),
Some("p%")]);
+
+ for run_values in [&StringArray::from(values) as &dyn Array,
&dictionary] {
+ let run = RunArray::<Int32Type>::try_new(&run_ends, run_values)
+ .unwrap()
+ .slice(3, 5);
+
+ let res = ilike(&run, &StringArray::new_scalar("a%")).unwrap();
+ assert_eq!(
+ res,
+ BooleanArray::from(vec![Some(true), None, None, Some(false),
Some(false)])
+ );
+
+ let res = eq_ignore_ascii_case(&run,
&StringArray::new_scalar("ARROW")).unwrap();
+ assert_eq!(
+ res,
+ BooleanArray::from(vec![Some(true), None, None, Some(false),
Some(false)])
+ );
+
+ let res = like(&run, &patterns).unwrap();
+ assert_eq!(
+ res,
+ BooleanArray::from(vec![Some(true), None, None, Some(true),
Some(false)])
+ );
+
+ let res = like(&Scalar::new(run.slice(0, 1)), &patterns).unwrap();
+ assert_eq!(
+ res,
+ BooleanArray::from(vec![Some(true), Some(true), None,
Some(false), Some(false)])
+ );
+
+ let res = like(&run,
&Scalar::new(StringArray::new_null(1))).unwrap();
+ assert_eq!(res, BooleanArray::new_null(5));
+
+ let empty = run.slice(0, 0);
+ let res = like(&empty, &StringArray::new_scalar("a%")).unwrap();
+ assert_eq!(res, BooleanArray::from(Vec::<bool>::new()));
+ let res = like(&empty, &patterns.slice(0, 0)).unwrap();
+ assert_eq!(res, BooleanArray::from(Vec::<bool>::new()));
+ }
+ }
+
+ #[test]
+ fn test_run_end_encoded_patterns() {
+ // Logical patterns: ["arr%", "arr%", null, "%row", "x%"].
+ let patterns = RunArray::<Int64Type>::try_new(
+ &Int64Array::from(vec![2, 3, 4, 5]),
+ &StringArray::from(vec![Some("arr%"), None, Some("%row"),
Some("x%")]),
+ )
+ .unwrap();
+
+ let res = like(&StringArray::new_scalar("arrow"), &patterns).unwrap();
+ assert_eq!(
+ res,
+ BooleanArray::from(vec![Some(true), Some(true), None, Some(true),
Some(false)])
+ );
+
+ let values = StringArray::from(vec!["arrow", "parquet", "arrow",
"narrow", "xyz"]);
+ let res = like(&values, &patterns).unwrap();
+ assert_eq!(
+ res,
+ BooleanArray::from(vec![Some(true), Some(false), None, Some(true),
Some(true)])
+ );
+ }
+
+ #[test]
+ fn test_run_end_encoded_type_mismatch() {
+ let run: RunArray<Int32Type> = std::iter::once("arrow").collect();
+ let err = like(&run, &LargeStringArray::new_scalar("a%")).unwrap_err();
+ assert_eq!(
+ err.to_string(),
+ "Invalid argument error: Invalid string/binary operation: Utf8
LIKE LargeUtf8"
+ );
+
+ let empty: RunArray<Int32Type> = std::iter::empty::<&str>().collect();
+ let err = like(&empty,
&Int32Array::from(Vec::<i32>::new())).unwrap_err();
+ assert_eq!(
+ err.to_string(),
+ "Invalid argument error: Invalid string/binary operation: Utf8
LIKE Int32"
+ );
+ let err = like(&Int32Array::from(Vec::<i32>::new()),
&empty).unwrap_err();
+ assert_eq!(
+ err.to_string(),
+ "Invalid argument error: Invalid string/binary operation: Int32
LIKE Utf8"
+ );
+ }
+
+ #[test]
+ fn test_run_end_encoded_binary() {
+ let values = BinaryArray::from(vec![b"arrow".as_slice(), b"parquet"]);
+ let run = RunArray::<Int32Type>::try_new(&Int32Array::from(vec![2,
3]), &values).unwrap();
+ let res = starts_with(&run, &BinaryArray::new_scalar(b"arr")).unwrap();
+ assert_eq!(res, BooleanArray::from(vec![true, true, false]));
+
+ let patterns = BinaryArray::from(vec![b"arrow".as_slice(), b"x",
b"et"]);
+ let res = ends_with(&run, &patterns).unwrap();
+ assert_eq!(res, BooleanArray::from(vec![true, false, true]));
+ }
+
#[test]
#[cfg_attr(miri, ignore)] // Takes too long
fn like_escape() {
diff --git a/arrow/benches/comparison_kernels.rs
b/arrow/benches/comparison_kernels.rs
index 095b9ddd61..2981160d01 100644
--- a/arrow/benches/comparison_kernels.rs
+++ b/arrow/benches/comparison_kernels.rs
@@ -16,6 +16,7 @@ use criterion::{Criterion, Throughput};
use rand::RngExt;
use rand::rngs::StdRng;
use std::hint;
+use std::sync::Arc;
const SIZE: usize = 65536;
@@ -605,6 +606,49 @@ fn add_benchmark(c: &mut Criterion) {
}
group.finish();
+
+ // RunEndEncoded LIKE benchmarks
+
+ let mut group = c.benchmark_group("ree_like");
+
+ for (physical, logical) in [(64, SIZE), (1024, SIZE), (SIZE / 2, SIZE)] {
+ let strings = create_string_array_for_runs(physical, logical, 16);
+ let flat = StringArray::from_iter_values(&strings);
+ let ree: RunArray<Int32Type> =
strings.iter().map(String::as_str).collect();
+ let dict_values: DictionaryArray<Int32Type> =
+ ree.values().as_string::<i32>().iter().collect();
+ let ree_dict = ree.with_values(Arc::new(dict_values));
+ let pattern = StringArray::new_scalar("%ab%");
+
+ let tag = format!("phys={physical},log={logical}");
+
+ group.bench_function(format!("like_flat_scalar({tag})"), |b| {
+ b.iter(|| like(&flat, &pattern).unwrap())
+ });
+
+ group.bench_function(format!("like_ree_scalar({tag})"), |b| {
+ b.iter(|| like(&ree, &pattern).unwrap())
+ });
+
+ group.bench_function(format!("like_ree_dict_scalar({tag})"), |b| {
+ b.iter(|| like(&ree_dict, &pattern).unwrap())
+ });
+
+ // Without native support, callers have to decode before matching.
+ group.bench_function(format!("like_ree_decoded_scalar({tag})"), |b| {
+ b.iter(|| {
+ let decoded =
+ arrow::compute::cast(&ree,
&arrow::datatypes::DataType::Utf8).unwrap();
+ like(&decoded, &pattern).unwrap()
+ })
+ });
+
+ group.bench_function(format!("like_ree_flat({tag})"), |b| {
+ b.iter(|| like(&ree, &flat).unwrap())
+ });
+ }
+
+ group.finish();
}
criterion_group!(benches, add_benchmark);