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::key function #1912

Merged
merged 1 commit into from Jun 20, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
22 changes: 22 additions & 0 deletions arrow/src/array/array_dictionary.rs
Expand Up @@ -169,6 +169,17 @@ impl<'a, K: ArrowPrimitiveType> DictionaryArray<K> {
.iter()
.map(|key| key.map(|k| k.to_usize().expect("Dictionary index not usize")))
}

/// Return the value of `keys` (the dictionary key) at index `i`,
/// cast to `usize`, `None` if the value at `i` is `NULL`.
pub fn key(&self, i: usize) -> Option<usize> {
self.keys.is_valid(i).then(|| {
self.keys
.value(i)
.to_usize()
.expect("Dictionary index not usize")
Copy link
Member

Choose a reason for hiding this comment

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

For most cases this unwrap won't panic, but do we need to maintain the same behavior with https://github.com/apache/arrow-datafusion/blob/080c32400ddfa2d45b5bebb820184eac8fd5a03a/datafusion/common/src/scalar.rs#L342-L358 ? If so the return type can either be Result<Option<_>> or Option<_>, I'm ok with both (hard to choose...).

Copy link
Contributor

Choose a reason for hiding this comment

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

Panicking should be fine, it's a validation failure if the array contains negative indexes. TBH I keep meaning to change all these checked conversions to numeric casts (i.e. as), I wouldn't be surprised if this leads to non-trivial performance benefits.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Filed #1918 to track

})
}
}

/// Constructs a `DictionaryArray` from an array data reference.
Expand Down Expand Up @@ -534,6 +545,17 @@ mod tests {
assert!(iter.next().is_none());
}

#[test]
fn test_dictionary_key() {
let keys = Int8Array::from(vec![Some(2), None, Some(1)]);
let values = StringArray::from(vec!["foo", "bar", "baz", "blarg"]);

let array = DictionaryArray::try_new(&keys, &values).unwrap();
assert_eq!(array.key(0), Some(2));
assert_eq!(array.key(1), None);
assert_eq!(array.key(2), Some(1));
}

#[test]
fn test_try_new() {
let values: StringArray = [Some("foo"), Some("bar"), Some("baz")]
Expand Down