1use indexmap::IndexMap;
9use std::collections::BTreeMap;
10
11use crate::lexer::{NormalizedToken, TokenLexer};
12use crate::query::{QueryMatchScore, QuerySearchID, QuerySearchLimit, QuerySearchOffset};
13use crate::store::StoreItem;
14use crate::store::fst::{StoreFSTActionBuilder, typo_factor};
15use crate::store::identifiers::{StoreObjectIID, StoreTermHash, StoreTermHashed};
16use crate::store::kv::{StoreKVAcquireMode, StoreKVAction, StoreKVActionBuilder};
17
18const MISSING_MATCH_SCORE: u16 = 100;
19
20impl super::Executor {
21 pub fn search(
22 &self,
23 item: StoreItem,
24 _event_id: QuerySearchID,
25 lexer: TokenLexer,
26 limit: QuerySearchLimit,
27 offset: QuerySearchOffset,
28 ) -> Result<Vec<String>, ()> {
29 if let StoreItem(collection, Some(bucket), None) = item {
30 let _kv_read_guard = self.kv_pool.lock_read_access();
33 let _fst_read_guard = self.fst_pool.lock_read_access();
34
35 let (Ok(kv_store), Ok(fst_store)) = (
36 self.kv_pool
37 .acquire(StoreKVAcquireMode::OpenOnly, collection),
38 self.fst_pool.acquire(collection, bucket),
39 ) else {
40 return Err(());
41 };
42
43 let (higher_limit, mut alternates_try) = (
44 self.app_conf.store.kv.retain_word_objects,
45 self.app_conf.search.query_alternates_try,
46 );
47
48 let (prefix_matching_enabled, fuzzy_matching_enabled) = (
49 self.fst_pool.fst_action_config.prefix_matching_enabled,
50 self.fst_pool.fst_action_config.fuzzy_matching_enabled,
51 );
52
53 executor_kv_lock_read!(kv_store);
55
56 let (kv_action, fst_action) = (
57 StoreKVActionBuilder::access(bucket, kv_store),
58 StoreFSTActionBuilder::access(fst_store),
59 );
60
61 let tokens: Vec<(NormalizedToken, StoreTermHashed, usize)> = lexer.collect();
64 let term_count = tokens.len();
65
66 let mut scoring_matrix: IndexMap<StoreObjectIID, Vec<QueryMatchScore>> =
75 IndexMap::with_capacity(24usize.min(usize::from(limit)));
76
77 'matches: for (idx, (token, term_hash, _)) in tokens.iter().enumerate() {
79 let iids = kv_action
80 .get_term_to_iids(*term_hash)
81 .unwrap_or(None)
82 .unwrap_or_default();
83
84 tracing::debug!("got exact search executor iids: {iids:?} for term: {token:?}");
85
86 for iid in iids.into_iter() {
87 let inserted = update_score(&mut scoring_matrix, iid, 0, idx, term_count);
89
90 if inserted {
91 if scoring_matrix.len() >= higher_limit {
94 tracing::trace!(?token, "got enough completed results for term");
95
96 break 'matches;
97 }
98 }
99 }
100 }
101
102 #[cfg(debug_assertions)]
103 tracing::debug!(?scoring_matrix);
104
105 if scoring_matrix.len() < higher_limit && alternates_try > 0 && prefix_matching_enabled
107 {
108 tracing::debug!(
109 "not enough iids were found ({}/{higher_limit}), looking for prefixes",
110 scoring_matrix.len(),
111 );
112
113 'terms: for (idx, (token, _, original_len)) in tokens.iter().enumerate() {
114 let Some(suggestions) = fst_action.lookup_begins(token, *original_len) else {
115 tracing::trace!("did not get any completed word for term {token:?}");
116 continue 'terms;
117 };
118
119 merge_suggestions(
120 suggestions,
121 &mut scoring_matrix,
122 token,
123 idx,
124 term_count,
125 &kv_action,
126 &mut alternates_try,
127 higher_limit,
128 );
129 }
130 }
131
132 #[cfg(debug_assertions)]
133 tracing::debug!(?scoring_matrix);
134
135 if scoring_matrix.len() < higher_limit && alternates_try > 0 && fuzzy_matching_enabled {
137 tracing::debug!(
138 "not enough iids were found ({}/{higher_limit}), looking for fuzzy matches",
139 scoring_matrix.len(),
140 );
141
142 'terms: for (idx, (token, _, original_word_len)) in tokens.iter().enumerate() {
143 let term = match token {
144 NormalizedToken::Word(term) => term,
145 NormalizedToken::Special(term) => {
147 tracing::debug!("skipping fuzzy search for {term:?}: term is special");
148 continue 'terms;
149 }
150 };
151
152 let max_typo_factor = typo_factor(*original_word_len);
153 let mut typo_factor = 1u32;
154
155 while alternates_try > 0 && typo_factor <= max_typo_factor {
159 let Some(suggestions) = fst_action.lookup_typos(term, typo_factor) else {
160 tracing::trace!("did not get any completed word for term {term:?}");
161 continue 'terms;
162 };
163
164 merge_suggestions(
165 suggestions,
166 &mut scoring_matrix,
167 term,
168 idx,
169 term_count,
170 &kv_action,
171 &mut alternates_try,
172 higher_limit,
173 );
174
175 typo_factor += 1;
176 }
177 }
178 }
179
180 #[cfg(debug_assertions)]
181 tracing::debug!(?scoring_matrix);
182
183 let one_term_is_special = tokens.iter().any(|(token, _, _)| token.is_special());
191 if one_term_is_special {
192 let mut to_remove = Vec::<StoreObjectIID>::new();
193
194 for (&iid, scores) in scoring_matrix.iter() {
195 if scores.contains(&MISSING_MATCH_SCORE) {
196 to_remove.push(iid);
197 }
198 }
199
200 for iid in to_remove {
201 scoring_matrix.swap_remove(&iid);
202 }
203 }
204
205 let found_iids = scoring_matrix
208 .into_iter()
209 .map(|(iid, scores)| (iid, scores.into_iter().sum()));
210
211 let all_iids = sorted_groups(found_iids).flat_map(|(_, v)| v);
213
214 let (limit_usize, offset_usize) = (limit as usize, offset as usize);
217 let mut result_oids = Vec::with_capacity(limit_usize);
218
219 'paging: for (index, found_iid) in all_iids.skip(offset_usize).enumerate() {
220 if index >= limit_usize {
222 break 'paging;
223 }
224
225 if let Ok(Some(oid)) = kv_action.get_iid_to_oid(found_iid) {
227 result_oids.push(oid);
228 } else {
229 tracing::error!("failed getting search executor iid-to-oid");
230 }
231 }
232
233 tracing::info!("got search executor final oids: {:?}", result_oids);
234
235 return Ok(result_oids);
236 }
237
238 Err(())
239 }
240}
241
242#[allow(clippy::too_many_arguments)] fn merge_suggestions(
244 suggestions: impl Iterator<Item = (String, QueryMatchScore)>,
245 scoring_matrix: &mut IndexMap<StoreObjectIID, Vec<QueryMatchScore>>,
246 term: &String,
247 term_idx: usize,
248 term_count: usize,
249 kv_action: &StoreKVAction<'_>,
250 alternates_try: &mut usize,
251 higher_limit: usize,
252) {
253 'suggestions: for (suggested_word, suggestion_score) in suggestions {
254 if suggested_word.eq(term) {
256 continue;
257 }
258
259 tracing::trace!(?term, ?suggested_word, "got completed word for term");
260
261 let suggested_term_hash = StoreTermHash::from(&suggested_word);
262 let suggested_iids = match kv_action.get_term_to_iids(suggested_term_hash) {
263 Ok(Some(suggested_iids)) => suggested_iids,
264 Ok(None) => continue,
265 Err(_) => continue,
266 };
267
268 for suggested_iid in suggested_iids.into_iter().take(*alternates_try) {
269 *alternates_try = unsafe { alternates_try.unchecked_sub(1) };
271
272 let inserted = update_score(
273 scoring_matrix,
274 suggested_iid,
275 suggestion_score,
276 term_idx,
277 term_count,
278 );
279
280 if inserted {
281 if scoring_matrix.len() >= higher_limit {
284 tracing::trace!(?term, "got enough completed results for term");
285
286 break 'suggestions;
287 }
288 }
289 }
290 }
291
292 tracing::trace!(
293 ?term,
294 "done completing results for term, now {} total results",
295 scoring_matrix.len()
296 );
297}
298
299fn update_score(
300 scoring_matrix: &mut IndexMap<StoreObjectIID, Vec<QueryMatchScore>>,
301 iid: StoreObjectIID,
302 score: QueryMatchScore,
303 term_idx: usize,
304 term_count: usize,
305) -> bool {
306 match scoring_matrix.entry(iid) {
307 indexmap::map::Entry::Occupied(mut occupied_entry) => {
309 let entry_score = unsafe { occupied_entry.get_mut().get_unchecked_mut(term_idx) };
311
312 let new_score = score.min(*entry_score);
313
314 tracing::trace!(entry_score, new_score, "Updating to min score");
315 *entry_score = new_score;
316
317 false
318 }
319 indexmap::map::Entry::Vacant(vacant_entry) => {
321 let mut scores = vec![MISSING_MATCH_SCORE; term_count];
322
323 tracing::trace!(new_score = score, "Inserting new score");
324 unsafe { *scores.get_unchecked_mut(term_idx) = score };
326
327 vacant_entry.insert(scores);
328
329 true
330 }
331 }
332}
333
334fn sorted_groups(
335 map: impl ExactSizeIterator<Item = (StoreObjectIID, QueryMatchScore)>,
336) -> impl ExactSizeIterator<Item = (QueryMatchScore, Vec<StoreObjectIID>)> {
337 let mut btree: BTreeMap<QueryMatchScore, Vec<StoreObjectIID>> = BTreeMap::new();
338
339 for (k, v) in map.into_iter() {
340 btree.entry(v).or_default().push(k);
341 }
342
343 btree.into_iter()
344}