1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#![allow(clippy::inline_always)]
use crate::simple::internal::fuzzers::rapidfuzz::{
DamerauLevenshtein,
Hamming,
Indel,
Jaro,
JaroWinkler,
LcsSeq,
Levenshtein,
Osa,
Postfix,
Prefix,
};
use crate::simple::RapidfuzzMetric;
use std::collections::BTreeSet;
// -----------------------------------------------------------------------------
impl<K: std::hash::Hash + Ord> crate::simple::search_index::SearchIndex<K> {
/// Scans the entire search index for the closest matching _n_ keywords
/// using the provided keyword and configured string similarity metric. This
/// feature relies on the [rapidfuzz](https://crates.io/crates/rapidfuzz)
/// crate.
///
/// When the user's keyword that is meant to be autocompleted returns no
/// matches, this can be used to find the best matches for substitution.
///
/// All keywords in the search index will potentially be examined.
///
/// # Input
///
/// * `user_keyword` · This keyword is used to search the search index.
///
/// For example, if the user provided the misspelled word `nthing`, this
/// could potentially return `nothing` as an alternative keyword if it
/// was present in the index.
///
/// Note that this method expects the input to be normalized already, i.e.
/// if the search is meant to be case-insensitive then the input should be
/// in lowercase.
///
/// # Output
///
/// This method returns an iterator over the top _n_ autocompletion options.
///
/// Each item the returned iterator is comprised of a keyword, and the
/// records associated with each keyword.
///
/// The number of autocompletion options are defined by the
/// `maximum_autocomplete_options` option in the search index.
///
/// If no keywords or reasonable matches are found, this method will return
/// an empty iterator.
///
/// # Notes
///
/// * This method differs from `rapidfuzz_keyword_comparator` in that this
/// method will perform some common setup, and dynamically dispatch to the
/// generic method indicated by the chosen string similarity metric
/// (`DamerauLevenshtein`, `Jaro`, `Osa`, etc.)
///
/// # Basic Usage
///
/// ```ignore
/// # use indicium::simple::{AutocompleteType, Indexable, SearchIndex, SearchType};
/// # use pretty_assertions::assert_eq;
/// #
/// # struct MyStruct {
/// # title: String,
/// # year: u16,
/// # body: String,
/// # }
/// #
/// # impl Indexable for MyStruct {
/// # fn strings(&self) -> Vec<String> {
/// # vec![
/// # self.title.clone(),
/// # self.year.to_string(),
/// # self.body.clone(),
/// # ]
/// # }
/// # }
/// #
/// # let my_vec = vec![
/// # MyStruct {
/// # title: "Harold Godwinson".to_string(),
/// # year: 1066,
/// # body: "Last crowned Anglo-Saxon king of England.".to_string(),
/// # },
/// # MyStruct {
/// # title: "Edgar Ætheling".to_string(),
/// # year: 1066,
/// # body: "Last male member of the royal house of Cerdic of Wessex.".to_string(),
/// # },
/// # MyStruct {
/// # title: "William the Conqueror".to_string(),
/// # year: 1066,
/// # body: "First Norman monarch of England.".to_string(),
/// # },
/// # MyStruct {
/// # title: "William Rufus".to_string(),
/// # year: 1087,
/// # body: "Third son of William the Conqueror.".to_string(),
/// # },
/// # MyStruct {
/// # title: "Henry Beauclerc".to_string(),
/// # year: 1100,
/// # body: "Fourth son of William the Conqueror.".to_string(),
/// # },
/// # ];
/// #
/// # let mut search_index: SearchIndex<usize> = SearchIndex::default();
/// #
/// # my_vec
/// # .iter()
/// # .enumerate()
/// # .for_each(|(index, element)|
/// # search_index.insert(&index, element)
/// # );
/// #
/// // Note: This method expects the input to be normalized (i.e. in
/// // lowercase) already.
///
/// let keywords: Vec<&str> = search_index
/// .rapidfuzz_keyword("harry")
/// .map(|(keyword, _key)| keyword.as_str())
/// .collect();
///
/// assert_eq!(
/// keywords,
/// vec!["harold"]
/// );
/// ```
#[inline(always)]
pub(crate) fn rapidfuzz_keyword<'s>(
&'s self,
user_keyword: &str,
) -> impl Iterator<Item = (&'s kstring::KString, &'s BTreeSet<K>)> {
// This structure will track the top scoring keywords:
let mut top_scores =
crate::simple::internal::fuzzers::FuzzyTopScores::<K, f64>::with_capacity(
self.maximum_autocomplete_options
);
// This call to `index_range` builds a keyword index range to fuzzy
// match against.
//
// This is used to restrict fuzzy-matching to only strings that match
// the first _n_ characters in the user's keyword. This helps reduce
// required compute.
//
// For example, if the `index_range` is "super" and the user's keyword
// is "supersonic", only index keywords beginning with "super" will be
// fuzzy compared against the user's keyword: "supersonic" against
// "superalloy", "supersonic" against "supergiant" and so on...
if let Some(index_range) = self.index_range(user_keyword) {
match self.rapidfuzz_metric.as_ref() {
Some(RapidfuzzMetric::DamerauLevenshtein) => self
.rapidfuzz_keyword_comparator::<DamerauLevenshtein>(
user_keyword,
&index_range,
&mut top_scores
),
Some(RapidfuzzMetric::Hamming) => self
.rapidfuzz_keyword_comparator::<Hamming>(
user_keyword,
&index_range,
&mut top_scores
),
Some(RapidfuzzMetric::Indel) => self
.rapidfuzz_keyword_comparator::<Indel>(
user_keyword,
&index_range,
&mut top_scores
),
Some(RapidfuzzMetric::Jaro) => self
.rapidfuzz_keyword_comparator::<Jaro>(
user_keyword,
&index_range,
&mut top_scores
),
Some(RapidfuzzMetric::JaroWinkler) => self
.rapidfuzz_keyword_comparator::<JaroWinkler>(
user_keyword,
&index_range,
&mut top_scores
),
Some(RapidfuzzMetric::LcsSeq) => self
.rapidfuzz_keyword_comparator::<LcsSeq>(
user_keyword,
&index_range,
&mut top_scores
),
Some(RapidfuzzMetric::Levenshtein) => self
.rapidfuzz_keyword_comparator::<Levenshtein>(
user_keyword,
&index_range,
&mut top_scores
),
Some(RapidfuzzMetric::Osa) => self
.rapidfuzz_keyword_comparator::<Osa>(
user_keyword,
&index_range,
&mut top_scores
),
Some(RapidfuzzMetric::Postfix) => self
.rapidfuzz_keyword_comparator::<Postfix>(
user_keyword,
&index_range,
&mut top_scores
),
Some(RapidfuzzMetric::Prefix) => self
.rapidfuzz_keyword_comparator::<Prefix>(
user_keyword,
&index_range,
&mut top_scores
),
// If no string similarity metric was defined in the search
// index, fuzzy string matching is effectively turned off.
None => { /* Do nothing */ },
} // match
} // if
// Return the top scoring keywords that could be used as autocomplete
// options, and their keys, to the caller:
top_scores.results()
} // fn
} // impl