-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Add xxhash algorithms in SQL and expression api #14367
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
Closed
Spaarsh
wants to merge
15
commits into
apache:main
from
Spaarsh:14044/enhancement/add-xxhash-algorithms-in-expression-API
Closed
Changes from 4 commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
a682d1e
Added hash module with xxhash32 and xxhash64 functions.
Spaarsh 25ebf13
Added support for individual values and for ingesting various types o…
Spaarsh 5fcc67b
Refactored code
Spaarsh 6353e6b
license fix
Spaarsh 741fa18
Optional seed added
Spaarsh 4d24759
Fixed test failings
Spaarsh 5f85511
Fixed clippy failing for unnecessary cast
Spaarsh 0d15f9c
Fixed CI test fails
Spaarsh a729942
Added support for Null inputs and corrected output for empty inputs
Spaarsh 60e4db7
Fixed failing fmt checks
Spaarsh f8e871b
Added hash test file (xxhash32 and xxhash64)
Spaarsh 564af36
Minor fix
Spaarsh ed2324f
Implemented feedback items
Spaarsh 18b1937
Fixed fmt and .md test fails
Spaarsh 25fd5c4
Merge branch '14044/enhancement/adding-xxhash-algorithms-in-expressio…
Spaarsh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| // 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 | ||
| // | ||
| // 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. | ||
|
|
||
| //! "xxhash" DataFusion functions | ||
|
|
||
| use datafusion_expr::ScalarUDF; | ||
| use std::sync::Arc; | ||
|
|
||
| pub mod xxhash; | ||
| make_udf_function!(xxhash::XxHash32Func, xxhash32); | ||
| make_udf_function!(xxhash::XxHash64Func, xxhash64); | ||
|
|
||
| pub mod expr_fn { | ||
| export_functions!(( | ||
| xxhash32, | ||
| "Computes the XXHash32 hash of a binary string.", | ||
| input | ||
| ),( | ||
| xxhash64, | ||
| "Computes the XXHash64 hash of a binary string.", | ||
| input | ||
| )); | ||
| } | ||
|
|
||
| /// Returns all DataFusion functions defined in this package | ||
| pub fn functions() -> Vec<Arc<ScalarUDF>> { | ||
| vec![xxhash32(), xxhash64()] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,279 @@ | ||
| // 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 | ||
| // | ||
| // 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 arrow::array::{Array, StringArray, Int32Array, Int64Array, UInt32Array, UInt64Array}; | ||
| use arrow::datatypes::DataType; | ||
| use datafusion_common::{Result, ScalarValue}; | ||
| use datafusion_expr::{ | ||
| ColumnarValue, Documentation, ScalarUDFImpl, Signature, Volatility, | ||
| }; | ||
| use twox_hash::{XxHash64, XxHash32}; | ||
| use datafusion_macros::user_doc; | ||
| use std::any::Any; | ||
| use std::hash::Hasher; | ||
| use datafusion_common::DataFusionError; | ||
| use std::sync::Arc; | ||
|
|
||
| #[user_doc( | ||
| doc_section(label = "Hashing Functions"), | ||
| description = "Computes the XXHash64 hash of a binary string.", | ||
| syntax_example = "xxhash64(expression)", | ||
| sql_example = r#"```sql | ||
| > select xxhash64('foo'); | ||
| +-------------------------------------------+ | ||
| | xxhash64(Utf8("foo")) | | ||
| +-------------------------------------------+ | ||
| | <xxhash64_result> | | ||
| +-------------------------------------------+ | ||
| ```"#, | ||
| standard_argument(name = "expression", prefix = "String") | ||
| )] | ||
| #[derive(Debug)] | ||
| pub struct XxHash64Func { | ||
| signature: Signature, | ||
| } | ||
|
|
||
| impl Default for XxHash64Func { | ||
| fn default() -> Self { | ||
| Self::new() | ||
| } | ||
| } | ||
|
|
||
| impl XxHash64Func { | ||
| pub fn new() -> Self { | ||
| use DataType::*; | ||
| Self { | ||
| signature: Signature::uniform( | ||
| 1, | ||
| vec![Utf8View, Utf8, LargeUtf8, Binary, LargeBinary], | ||
| Volatility::Immutable, | ||
| ), | ||
| } | ||
| } | ||
|
|
||
| pub fn hash_scalar(&self, value: &ColumnarValue) -> Result<String> { | ||
| let value_str = to_string_from_scalar(value)?; | ||
| hash_value(&value_str, XxHash64::default(), HashType::U64) | ||
| } | ||
| } | ||
|
|
||
| impl ScalarUDFImpl for XxHash64Func { | ||
| fn as_any(&self) -> &dyn Any { | ||
| self | ||
| } | ||
|
|
||
| fn name(&self) -> &str { | ||
| "xxhash64" | ||
| } | ||
|
|
||
| fn signature(&self) -> &Signature { | ||
| &self.signature | ||
| } | ||
|
|
||
| fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { | ||
| Ok(DataType::Utf8) | ||
| } | ||
|
|
||
| fn invoke_batch( | ||
| &self, | ||
| args: &[ColumnarValue], | ||
| _number_rows: usize, | ||
| ) -> Result<ColumnarValue> { | ||
| let input_data = &args[0]; | ||
|
|
||
| let result = match input_data { | ||
| ColumnarValue::Array(array) => { | ||
| let hash_results = process_array(array, XxHash64::default(), HashType::U64)?; | ||
| let hash_array = StringArray::from(hash_results); | ||
| Arc::new(hash_array) as Arc<dyn Array> | ||
| }, | ||
| ColumnarValue::Scalar(scalar) => { | ||
| let hash_result = self.hash_scalar(&ColumnarValue::Scalar(scalar.clone()))?; | ||
| let hash_array = StringArray::from(vec![hash_result]); | ||
| Arc::new(hash_array) as Arc<dyn Array> | ||
| } | ||
| }; | ||
|
|
||
| Ok(ColumnarValue::Array(result)) | ||
| } | ||
|
|
||
| fn documentation(&self) -> Option<&Documentation> { | ||
| self.doc() | ||
| } | ||
| } | ||
|
|
||
| #[user_doc( | ||
| doc_section(label = "Hashing Functions"), | ||
| description = "Computes the XXHash32 hash of a binary string.", | ||
| syntax_example = "xxhash32(expression)", | ||
| sql_example = r#"```sql | ||
| > select xxhash32('foo'); | ||
| +-------------------------------------------+ | ||
| | xxhash32(Utf8("foo")) | | ||
| +-------------------------------------------+ | ||
| | <xxhash32_result> | | ||
| +-------------------------------------------+ | ||
| ```"#, | ||
| standard_argument(name = "expression", prefix = "String") | ||
| )] | ||
| #[derive(Debug)] | ||
| pub struct XxHash32Func { | ||
| signature: Signature, | ||
| } | ||
|
|
||
| impl Default for XxHash32Func { | ||
| fn default() -> Self { | ||
| Self::new() | ||
| } | ||
| } | ||
|
|
||
| impl XxHash32Func { | ||
| pub fn new() -> Self { | ||
| use DataType::*; | ||
| Self { | ||
| signature: Signature::uniform( | ||
| 1, | ||
| vec![Utf8View, Utf8, LargeUtf8, Binary, LargeBinary], | ||
| Volatility::Immutable, | ||
| ), | ||
| } | ||
| } | ||
|
|
||
| pub fn hash_scalar(&self, value: &ColumnarValue) -> Result<String> { | ||
| let value_str = to_string_from_scalar(value)?; | ||
| hash_value(&value_str, XxHash32::default(), HashType::U32) | ||
| } | ||
| } | ||
|
|
||
| impl ScalarUDFImpl for XxHash32Func { | ||
| fn as_any(&self) -> &dyn Any { | ||
| self | ||
| } | ||
|
|
||
| fn name(&self) -> &str { | ||
| "xxhash32" | ||
| } | ||
|
|
||
| fn signature(&self) -> &Signature { | ||
| &self.signature | ||
| } | ||
|
|
||
| fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { | ||
| Ok(DataType::Utf8) | ||
| } | ||
|
|
||
| fn invoke_batch( | ||
| &self, | ||
| args: &[ColumnarValue], | ||
| _number_rows: usize, | ||
| ) -> Result<ColumnarValue> { | ||
| let input_data = &args[0]; | ||
|
|
||
| let result = match input_data { | ||
| ColumnarValue::Array(array) => { | ||
| let hash_results = process_array(array, XxHash32::default(), HashType::U32)?; | ||
| let hash_array = StringArray::from(hash_results); | ||
| Arc::new(hash_array) as Arc<dyn Array> | ||
| }, | ||
| ColumnarValue::Scalar(scalar) => { | ||
| let hash_result = self.hash_scalar(&ColumnarValue::Scalar(scalar.clone()))?; | ||
| let hash_array = StringArray::from(vec![hash_result]); | ||
| Arc::new(hash_array) as Arc<dyn Array> | ||
| } | ||
| }; | ||
|
|
||
| Ok(ColumnarValue::Array(result)) | ||
| } | ||
|
|
||
| fn documentation(&self) -> Option<&Documentation> { | ||
| self.doc() | ||
| } | ||
| } | ||
|
|
||
| // Helper functions | ||
|
|
||
| fn to_string_from_scalar(value: &ColumnarValue) -> Result<String> { | ||
| match value { | ||
| ColumnarValue::Scalar(scalar) => match scalar { | ||
| ScalarValue::Utf8(Some(v)) => Ok(v.clone()), | ||
| ScalarValue::Int32(Some(v)) => Ok(v.to_string()), | ||
| ScalarValue::Int64(Some(v)) => Ok(v.to_string()), | ||
| ScalarValue::UInt32(Some(v)) => Ok(v.to_string()), | ||
| ScalarValue::UInt64(Some(v)) => Ok(v.to_string()), | ||
| _ => Err(DataFusionError::Internal("Unsupported scalar type".to_string())), | ||
| }, | ||
| _ => Err(DataFusionError::Internal("Expected a scalar value".to_string())), | ||
| } | ||
| } | ||
|
|
||
| #[derive(Clone)] | ||
| pub enum HashType { | ||
| U32, | ||
| U64, | ||
| } | ||
|
|
||
| fn hash_value<T: Hasher>(value_str: &str, mut hasher: T, hash_type: HashType) -> Result<String, DataFusionError> { | ||
| hasher.write(value_str.as_bytes()); | ||
| let hash = hasher.finish(); | ||
| match hash_type { | ||
| HashType::U32 => { | ||
| let hash_u32 = hash as u32; | ||
| Ok(hex::encode(hash_u32.to_be_bytes())) | ||
| }, | ||
| HashType::U64 => { | ||
| let hash_u64 = hash as u64; | ||
| Ok(hex::encode(hash_u64.to_be_bytes())) | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| fn process_array<T: Hasher>(array: &dyn Array, mut hasher: T, hash_type: HashType) -> Result<Vec<String>> { | ||
| let mut hash_results: Vec<String> = Vec::with_capacity(array.len()); | ||
|
Spaarsh marked this conversation as resolved.
Outdated
|
||
| for i in 0..array.len() { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Instead of downcasting the array for every single element in it see if you can do it once up front. |
||
| if array.is_null(i) { | ||
| hash_results.push(String::from("00000000")); // Handle null values | ||
| continue; | ||
| } | ||
|
|
||
| let value_str = match array.data_type() { | ||
| DataType::Utf8 => { | ||
| let string_array = array.as_any().downcast_ref::<StringArray>().unwrap(); | ||
| string_array.value(i).to_string() | ||
| } | ||
| DataType::Int32 => { | ||
| let int_array = array.as_any().downcast_ref::<Int32Array>().unwrap(); | ||
| int_array.value(i).to_string() | ||
| } | ||
| DataType::Int64 => { | ||
| let int_array = array.as_any().downcast_ref::<Int64Array>().unwrap(); | ||
| int_array.value(i).to_string() | ||
| } | ||
| DataType::UInt32 => { | ||
| let uint_array = array.as_any().downcast_ref::<UInt32Array>().unwrap(); | ||
| uint_array.value(i).to_string() | ||
| } | ||
| DataType::UInt64 => { | ||
| let uint_array = array.as_any().downcast_ref::<UInt64Array>().unwrap(); | ||
| uint_array.value(i).to_string() | ||
| } | ||
| _ => return Err(DataFusionError::Internal("Unsupported array type".to_string())), | ||
| }; | ||
|
|
||
| hash_results.push(hash_value(&value_str, &mut hasher, hash_type.clone())?); | ||
| } | ||
| Ok(hash_results) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The types you say you accept here do not match the types handled in
process_arrayorto_string_from_scalar. You should likely handle all these and the int ones you are handling in those.Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sure I'll fix this. I had actually made several changes that had not been pushed. Due do a glitch in my device they got wiped off 😅
I removed the Int types from being accepted as input since I was thinking that allowing any other form of input other than a string wouldn't be ideal and I am anyway casting them to the Utf8 type. And all the hash functions expect their input to be of that form only. Even the crate I am using expects the same. Allowing for multiple types doesn't serve much of a purpose now that I think about it. I would love your thoughts on this!
And should I convert this issue to draft? Since I am still adding the optional seed argument.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
If it's still a wip, sure, mark as draft with a WIP in the description helps a lot. Some hashes do allow binary input (See md5 for example, so that is normally reasonable.