-
Notifications
You must be signed in to change notification settings - Fork 2k
Spark soundex function implementation #20725
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
Open
kazantsev-maksim
wants to merge
23
commits into
apache:main
Choose a base branch
from
kazantsev-maksim:spark_soundex
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+334
−10
Open
Changes from all commits
Commits
Show all changes
23 commits
Select commit
Hold shift + click to select a range
f232898
Spark soundex function implementation
2cd58fe
Merge branch 'main' into spark_soundex
kazantsev-maksim e2aadb3
Add more tests
2a426d7
Merge remote-tracking branch 'origin/spark_soundex' into spark_soundex
e53f738
Merge branch 'main' into spark_soundex
kazantsev-maksim 37c3390
Clippy fixing
6f0480e
Merge remote-tracking branch 'origin/spark_soundex' into spark_soundex
5058986
Clippy fixing
5682c4f
Fix compute_soundex
9b014ec
Fix compute_soundex
74569b4
Fix compute_soundex
b89175e
Clippy fixing
25c763d
Ad more slt tests
3965da1
Add more slt tests
1153124
fix
1a867bf
fix
6d47d83
fix
061c6b1
fix
d7852bf
fix
cab229a
fix
1af1d30
fix
a63709a
fix
bb5f6f0
fix
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,146 @@ | ||
| // 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::{ArrayRef, OffsetSizeTrait, StringArray}; | ||
| use arrow::datatypes::DataType; | ||
| use datafusion::logical_expr::{ColumnarValue, Signature, Volatility}; | ||
| use datafusion_common::cast::as_generic_string_array; | ||
| use datafusion_common::utils::take_function_args; | ||
| use datafusion_common::{Result, exec_err}; | ||
| use datafusion_expr::{ScalarFunctionArgs, ScalarUDFImpl}; | ||
| use datafusion_functions::utils::make_scalar_function; | ||
| use std::any::Any; | ||
| use std::sync::Arc; | ||
|
|
||
| /// Spark-compatible `soundex` expression | ||
| /// <https://spark.apache.org/docs/latest/api/sql/index.html#soundex> | ||
| #[derive(Debug, PartialEq, Eq, Hash)] | ||
| pub struct SparkSoundex { | ||
| signature: Signature, | ||
| } | ||
|
|
||
| impl Default for SparkSoundex { | ||
| fn default() -> Self { | ||
| Self::new() | ||
| } | ||
| } | ||
|
|
||
| impl SparkSoundex { | ||
| pub fn new() -> Self { | ||
| Self { | ||
| signature: Signature::string(1, Volatility::Immutable), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl ScalarUDFImpl for SparkSoundex { | ||
| fn as_any(&self) -> &dyn Any { | ||
| self | ||
| } | ||
|
|
||
| fn name(&self) -> &str { | ||
| "soundex" | ||
| } | ||
|
|
||
| fn signature(&self) -> &Signature { | ||
| &self.signature | ||
| } | ||
|
|
||
| fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { | ||
| Ok(DataType::Utf8) | ||
| } | ||
|
|
||
| fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { | ||
| make_scalar_function(spark_soundex_inner, vec![])(&args.args) | ||
| } | ||
| } | ||
|
|
||
| fn spark_soundex_inner(arg: &[ArrayRef]) -> Result<ArrayRef> { | ||
| let [array] = take_function_args("soundex", arg)?; | ||
| match &array.data_type() { | ||
| DataType::Utf8 => soundex::<i32>(array), | ||
| DataType::LargeUtf8 => soundex::<i64>(array), | ||
| other => { | ||
| exec_err!("unsupported data type {other:?} for function `soundex`") | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn soundex<T: OffsetSizeTrait>(array: &ArrayRef) -> Result<ArrayRef> { | ||
| let str_array = as_generic_string_array::<T>(array)?; | ||
|
|
||
| let result = str_array | ||
| .iter() | ||
| .map(|s| s.map(compute_soundex)) | ||
| .collect::<StringArray>(); | ||
|
|
||
| Ok(Arc::new(result)) | ||
| } | ||
|
|
||
| const US_ENGLISH_MAPPING: [u8; 26] = [ | ||
| b'0', b'1', b'2', b'3', b'0', b'1', b'2', b'7', b'0', b'2', b'2', b'4', b'5', b'5', | ||
| b'0', b'1', b'2', b'6', b'2', b'3', b'0', b'1', b'7', b'2', b'0', b'2', | ||
| ]; | ||
|
|
||
| fn compute_soundex(s: &str) -> String { | ||
| let bytes = s.as_bytes(); | ||
| if bytes.is_empty() { | ||
| return String::new(); | ||
| } | ||
|
|
||
| let mut first_ch = bytes[0]; | ||
|
|
||
| if first_ch.is_ascii_lowercase() { | ||
| first_ch -= 32; | ||
| } else if !first_ch.is_ascii_uppercase() { | ||
| return s.to_string(); | ||
| } | ||
|
|
||
| let mut soundex_code = [first_ch, b'0', b'0', b'0']; | ||
| let mut sxi = 1; | ||
| let idx = (first_ch - b'A') as usize; | ||
| let mut last_code = US_ENGLISH_MAPPING[idx]; | ||
|
|
||
| for i in bytes.iter().skip(1) { | ||
| let mut b = *i; | ||
|
|
||
| if b.is_ascii_lowercase() { | ||
| b -= 32; | ||
| } else if !b.is_ascii_uppercase() { | ||
| last_code = b'0'; | ||
| continue; | ||
| } | ||
|
|
||
| let idx = (b - b'A') as usize; | ||
| let code = US_ENGLISH_MAPPING[idx]; | ||
|
|
||
| if code == b'7' { | ||
| continue; | ||
| } else { | ||
| if code != b'0' && code != last_code { | ||
| soundex_code[sxi] = code; | ||
| sxi += 1; | ||
| if sxi > 3 { | ||
| break; | ||
| } | ||
| } | ||
| last_code = code; | ||
| } | ||
| } | ||
|
|
||
| String::from_utf8_lossy(&soundex_code).to_string() | ||
| } |
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
Oops, something went wrong.
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.
Hey! I had actually started working on a Spark soundex implementation too and didn't realize there was already a PR for it. Happy to see this moving forward!
I had put together a battery of edge-case tests validated against Spark JVM that might be useful. The current SLT coverage is a bit thin — there are some tricky Soundex behaviors that are easy to get wrong:
Spark-3.5
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.
Big thanks to @davidlghellin for the test cases.