-
Notifications
You must be signed in to change notification settings - Fork 752
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
feat(functions): add jaro_winkler string similarity function #16993
Open
maxjustus
wants to merge
1
commit into
databendlabs:main
Choose a base branch
from
maxjustus:string-distance
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.
+264
−1
Open
Changes from all commits
Commits
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 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 |
---|---|---|
|
@@ -19,13 +19,15 @@ use databend_common_base::base::uuid::Uuid; | |
use databend_common_expression::types::decimal::Decimal128Type; | ||
use databend_common_expression::types::number::SimpleDomain; | ||
use databend_common_expression::types::number::UInt64Type; | ||
use databend_common_expression::types::number::Float64Type; | ||
use databend_common_expression::types::string::StringColumnBuilder; | ||
use databend_common_expression::types::string::StringDomain; | ||
use databend_common_expression::types::ArrayType; | ||
use databend_common_expression::types::NumberType; | ||
use databend_common_expression::types::StringType; | ||
use databend_common_expression::unify_string; | ||
use databend_common_expression::vectorize_1_arg; | ||
use databend_common_expression::vectorize_2_arg; | ||
use databend_common_expression::vectorize_with_builder_1_arg; | ||
use databend_common_expression::vectorize_with_builder_2_arg; | ||
use databend_common_expression::vectorize_with_builder_3_arg; | ||
|
@@ -776,7 +778,18 @@ pub fn register(registry: &mut FunctionRegistry) { | |
output.commit_row(); | ||
}, | ||
), | ||
) | ||
); | ||
|
||
registry | ||
.register_passthrough_nullable_2_arg::<StringType, StringType, Float64Type, _, _>( | ||
"jaro_winkler", | ||
|_, _, _| FunctionDomain::Full, | ||
vectorize_2_arg::<StringType, StringType, Float64Type>( | ||
|s1, s2, _ctx| { | ||
jaro_winkler::jaro_winkler(s1, s2).into() | ||
}, | ||
), | ||
); | ||
} | ||
|
||
pub(crate) mod soundex { | ||
|
@@ -841,6 +854,190 @@ pub(crate) mod soundex { | |
} | ||
} | ||
|
||
// this implementation comes from https://github.com/joshuaclayton/jaro_winkler | ||
pub(crate) mod jaro_winkler { | ||
#![deny(missing_docs)] | ||
|
||
//! `jaro_winkler` is a crate for calculating Jaro-Winkler distance of two strings. | ||
//! | ||
//! # Examples | ||
//! | ||
//! ``` | ||
//! use jaro_winkler::jaro_winkler; | ||
//! | ||
//! assert_eq!(jaro_winkler("martha", "marhta"), 0.9611111111111111); | ||
//! assert_eq!(jaro_winkler("", "words"), 0.0); | ||
//! assert_eq!(jaro_winkler("same", "same"), 1.0); | ||
//! ``` | ||
|
||
enum DataWrapper { | ||
Vec(Vec<bool>), | ||
Bitwise(u128), | ||
} | ||
|
||
impl DataWrapper { | ||
fn build(len: usize) -> Self { | ||
if len <= 128 { | ||
DataWrapper::Bitwise(0) | ||
} else { | ||
let mut internal = Vec::with_capacity(len); | ||
internal.extend(std::iter::repeat(false).take(len)); | ||
DataWrapper::Vec(internal) | ||
} | ||
} | ||
|
||
fn get(&self, idx: usize) -> bool { | ||
match self { | ||
DataWrapper::Vec(v) => v[idx], | ||
DataWrapper::Bitwise(v1) => (v1 >> idx) & 1 == 1, | ||
} | ||
} | ||
|
||
fn set_true(&mut self, idx: usize) { | ||
match self { | ||
DataWrapper::Vec(v) => v[idx] = true, | ||
DataWrapper::Bitwise(v1) => *v1 |= 1 << idx, | ||
} | ||
} | ||
} | ||
|
||
/// Calculates the Jaro-Winkler distance of two strings. | ||
/// | ||
/// The return value is between 0.0 and 1.0, where 1.0 means the strings are equal. | ||
pub fn jaro_winkler(left_: &str, right_: &str) -> f64 { | ||
let llen = left_.len(); | ||
let rlen = right_.len(); | ||
|
||
let (left, right, s1_len, s2_len) = if llen < rlen { | ||
(right_, left_, rlen, llen) | ||
} else { | ||
(left_, right_, llen, rlen) | ||
}; | ||
|
||
match (s1_len, s2_len) { | ||
(0, 0) => return 1.0, | ||
(0, _) | (_, 0) => return 0.0, | ||
(_, _) => (), | ||
} | ||
|
||
if left == right { | ||
return 1.0; | ||
} | ||
|
||
let range = matching_distance(s1_len, s2_len); | ||
let mut s1m = DataWrapper::build(s1_len); | ||
let mut s2m = DataWrapper::build(s2_len); | ||
let mut matching: f64 = 0.0; | ||
let mut transpositions: f64 = 0.0; | ||
let left_as_bytes = left.as_bytes(); | ||
let right_as_bytes = right.as_bytes(); | ||
|
||
for i in 0..s2_len { | ||
let mut j = (i as isize - range as isize).max(0) as usize; | ||
let l = (i + range + 1).min(s1_len); | ||
while j < l { | ||
if right_as_bytes[i] == left_as_bytes[j] && !s1m.get(j) { | ||
s1m.set_true(j); | ||
s2m.set_true(i); | ||
matching += 1.0; | ||
break; | ||
} | ||
|
||
j += 1; | ||
} | ||
} | ||
|
||
if matching == 0.0 { | ||
return 0.0; | ||
} | ||
|
||
let mut l = 0; | ||
|
||
for i in 0..s2_len - 1 { | ||
if s2m.get(i) { | ||
let mut j = l; | ||
|
||
while j < s1_len { | ||
if s1m.get(j) { | ||
l = j + 1; | ||
break; | ||
} | ||
|
||
j += 1; | ||
} | ||
|
||
if right_as_bytes[i] != left_as_bytes[j] { | ||
transpositions += 1.0; | ||
} | ||
} | ||
} | ||
transpositions = (transpositions / 2.0).ceil(); | ||
|
||
let jaro = (matching / (s1_len as f64) | ||
+ matching / (s2_len as f64) | ||
+ (matching - transpositions) / matching) | ||
/ 3.0; | ||
|
||
let prefix_length = left_as_bytes | ||
.iter() | ||
.zip(right_as_bytes) | ||
.take(4) | ||
.take_while(|(l, r)| l == r) | ||
.count() as f64; | ||
|
||
jaro + prefix_length * 0.1 * (1.0 - jaro) | ||
} | ||
|
||
fn matching_distance(s1_len: usize, s2_len: usize) -> usize { | ||
let max = s1_len.max(s2_len) as f32; | ||
((max / 2.0).floor() - 1.0) as usize | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
#[test] | ||
fn different_is_zero() { | ||
assert_eq!(jaro_winkler("foo", "bar"), 0.0); | ||
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. |
||
} | ||
|
||
#[test] | ||
fn same_is_one() { | ||
assert_eq!(jaro_winkler("foo", "foo"), 1.0); | ||
assert_eq!(jaro_winkler("", ""), 1.0); | ||
} | ||
|
||
#[test] | ||
fn test_hello() { | ||
assert_eq!(jaro_winkler("hell", "hello"), 0.96); | ||
} | ||
|
||
macro_rules! assert_within { | ||
($x:expr, $y:expr, delta=$d:expr) => { | ||
assert!(($x - $y).abs() <= $d) | ||
}; | ||
} | ||
|
||
#[test] | ||
fn test_boundary() { | ||
let long_value = "test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests jaro running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s"; | ||
let longer_value = "test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured;test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured;test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured;test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured;test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests jaro running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s"; | ||
let result = jaro_winkler(long_value, longer_value); | ||
assert_within!(result, 0.82, delta = 0.01); | ||
} | ||
|
||
#[test] | ||
fn test_close_to_boundary() { | ||
let long_value = "test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests jaro running 0 tests test"; | ||
assert_eq!(long_value.len(), 129); | ||
let longer_value = "test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured;test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured;test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured;test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured;test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s Doc-tests jaro running 0 tests test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s"; | ||
let result = jaro_winkler(long_value, longer_value); | ||
assert_within!(result, 0.8, delta = 0.001); | ||
} | ||
} | ||
} | ||
|
||
#[inline] | ||
fn substr(builder: &mut StringColumnBuilder, str: &str, pos: i64, len: u64) { | ||
if pos == 0 || len == 0 { | ||
|
This file contains 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
64 changes: 64 additions & 0 deletions
64
tests/sqllogictests/suites/query/functions/02_0079_function_strings_jaro_winkler.test
This file contains 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,64 @@ | ||
query T | ||
SELECT jaro_winkler(NULL, 'hello') | ||
---- | ||
NULL | ||
|
||
query T | ||
SELECT jaro_winkler('hello', NULL) | ||
---- | ||
NULL | ||
|
||
query T | ||
SELECT jaro_winkler(NULL, NULL) | ||
---- | ||
NULL | ||
|
||
query T | ||
SELECT jaro_winkler('', '') | ||
---- | ||
1.0 | ||
|
||
query T | ||
SELECT jaro_winkler('hello', 'hello') | ||
---- | ||
1.0 | ||
|
||
query T | ||
SELECT jaro_winkler('hello', 'helo') | ||
---- | ||
0.9533333333333333 | ||
|
||
query T | ||
SELECT jaro_winkler('martha', 'marhta') | ||
---- | ||
0.9611111111111111 | ||
|
||
query T | ||
SELECT jaro_winkler('你好', '你好啊') | ||
---- | ||
0.9333333333333333 | ||
|
||
query T | ||
SELECT jaro_winkler('🦀hello', '🦀helo') | ||
---- | ||
0.9777777777777777 | ||
|
||
query T | ||
SELECT jaro_winkler('dixon', 'dicksonx') | ||
---- | ||
0.8133333333333332 | ||
|
||
query T | ||
SELECT jaro_winkler('duane', 'dwayne') | ||
---- | ||
0.8400000000000001 | ||
|
||
query T | ||
select jaro_winkler('asdf', 'as x c f'); | ||
---- | ||
0.6592592592592592 | ||
|
||
query T | ||
SELECT jaro_winkler('', 'hello') | ||
---- | ||
0.0 |
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.
The function jaro_winkler and mod jaro_winkler can refactor to file other.rs.