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 DictionaryArray::with_values to make it easier to operate on dictionary values #2798

Merged
merged 1 commit into from
Oct 2, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
54 changes: 54 additions & 0 deletions arrow-array/src/array/dictionary_array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,60 @@ impl<K: ArrowPrimitiveType> DictionaryArray<K> {
values,
})
}

/// Returns a new dictionary with the same keys as the current instance
/// but with a different set of dictionary values
///
/// This can be used to perform an operation on the values of a dictionary
Copy link
Contributor

Choose a reason for hiding this comment

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

❤️

///
/// # Panics
///
/// Panics if `values` has a length less than the current values
///
/// ```
/// use arrow_array::builder::PrimitiveDictionaryBuilder;
/// use arrow_array::{Int8Array, Int64Array, ArrayAccessor};
/// use arrow_array::types::{Int32Type, Int8Type};
///
/// // Construct a Dict(Int32, Int8)
/// let mut builder = PrimitiveDictionaryBuilder::<Int32Type, Int8Type>::with_capacity(2, 200);
/// for i in 0..100 {
/// builder.append(i % 2).unwrap();
/// }
///
/// let dictionary = builder.finish();
///
/// // Perform a widening cast of dictionary values
/// let typed_dictionary = dictionary.downcast_dict::<Int8Array>().unwrap();
/// let values: Int64Array = typed_dictionary.values().unary(|x| x as i64);
///
/// // Create a Dict(Int32,
/// let new = dictionary.with_values(&values);
///
/// // Verify values are as expected
/// let new_typed = new.downcast_dict::<Int64Array>().unwrap();
/// for i in 0..100 {
/// assert_eq!(new_typed.value(i), (i % 2) as i64)
/// }
/// ```
///
pub fn with_values(&self, values: &dyn Array) -> Self {
assert!(values.len() >= self.values.len());
Copy link
Contributor

Choose a reason for hiding this comment

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

It took me a little while to convince myself it would be ok if values had a different datatype than self.values()? Because the dictionary builder will create the correct DataType::Dictionary for the new array


let builder = self
.data
.clone()
.into_builder()
.data_type(DataType::Dictionary(
Box::new(K::DATA_TYPE),
Box::new(values.data_type().clone()),
))
.child_data(vec![values.data().clone()]);

// SAFETY:
// Offsets were valid before and verified length is greater than or equal
Self::from(unsafe { builder.build_unchecked() })
}
}

/// Constructs a `DictionaryArray` from an array data reference.
Expand Down
14 changes: 4 additions & 10 deletions arrow/src/compute/kernels/arity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,11 +76,8 @@ where
F: Fn(T::Native) -> T::Native,
{
let dict_values = array.values().as_any().downcast_ref().unwrap();
let values = unary::<T, F, T>(dict_values, op).into_data();
let data = array.data().clone().into_builder().child_data(vec![values]);

let new_dict: DictionaryArray<K> = unsafe { data.build_unchecked() }.into();
Ok(Arc::new(new_dict))
let values = unary::<T, F, T>(dict_values, op);
Ok(Arc::new(array.with_values(&values)))
}

/// A helper function that applies a fallible unary function to a dictionary array with primitive value type.
Expand All @@ -98,11 +95,8 @@ where
}

let dict_values = array.values().as_any().downcast_ref().unwrap();
let values = try_unary::<T, F, T>(dict_values, op)?.into_data();
let data = array.data().clone().into_builder().child_data(vec![values]);

let new_dict: DictionaryArray<K> = unsafe { data.build_unchecked() }.into();
Ok(Arc::new(new_dict))
let values = try_unary::<T, F, T>(dict_values, op)?;
Ok(Arc::new(array.with_values(&values)))
}

/// Applies an infallible unary function to an array with primitive values.
Expand Down