1use indexmap::IndexMap;
9use std::collections::BTreeMap;
10
11use crate::lexer::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 terms: Vec<(String, StoreTermHashed, usize)> = lexer.collect();
64 let term_count = terms.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, (term, term_hash, _)) in terms.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: {term:?}");
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!(?term, "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, (term, _, original_len)) in terms.iter().enumerate() {
114 let Some(suggestions) = fst_action.lookup_begins(term, *original_len) else {
115 tracing::trace!("did not get any completed word for term {term:?}");
116 continue 'terms;
117 };
118
119 merge_suggestions(
120 suggestions,
121 &mut scoring_matrix,
122 term,
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, (term, _, original_word_len)) in terms.iter().enumerate() {
143 let max_typo_factor = typo_factor(*original_word_len);
144 let mut typo_factor = 1u32;
145
146 while alternates_try > 0 && typo_factor <= max_typo_factor {
150 let Some(suggestions) = fst_action.lookup_typos(term, typo_factor) else {
151 tracing::trace!("did not get any completed word for term {term:?}");
152 continue 'terms;
153 };
154
155 merge_suggestions(
156 suggestions,
157 &mut scoring_matrix,
158 term,
159 idx,
160 term_count,
161 &kv_action,
162 &mut alternates_try,
163 higher_limit,
164 );
165
166 typo_factor += 1;
167 }
168 }
169 }
170
171 #[cfg(debug_assertions)]
172 tracing::debug!(?scoring_matrix);
173
174 let found_iids = scoring_matrix
177 .into_iter()
178 .map(|(iid, scores)| (iid, scores.into_iter().sum()));
179
180 let all_iids = sorted_groups(found_iids).flat_map(|(_, v)| v);
182
183 let (limit_usize, offset_usize) = (limit as usize, offset as usize);
186 let mut result_oids = Vec::with_capacity(limit_usize);
187
188 'paging: for (index, found_iid) in all_iids.skip(offset_usize).enumerate() {
189 if index >= limit_usize {
191 break 'paging;
192 }
193
194 if let Ok(Some(oid)) = kv_action.get_iid_to_oid(found_iid) {
196 result_oids.push(oid);
197 } else {
198 tracing::error!("failed getting search executor iid-to-oid");
199 }
200 }
201
202 tracing::info!("got search executor final oids: {:?}", result_oids);
203
204 return Ok(result_oids);
205 }
206
207 Err(())
208 }
209}
210
211#[allow(clippy::too_many_arguments)] fn merge_suggestions(
213 suggestions: impl Iterator<Item = (String, QueryMatchScore)>,
214 scoring_matrix: &mut IndexMap<StoreObjectIID, Vec<QueryMatchScore>>,
215 term: &String,
216 term_idx: usize,
217 term_count: usize,
218 kv_action: &StoreKVAction<'_>,
219 alternates_try: &mut usize,
220 higher_limit: usize,
221) {
222 'suggestions: for (suggested_word, suggestion_score) in suggestions {
223 if suggested_word.eq(term) {
225 continue;
226 }
227
228 tracing::trace!(?term, ?suggested_word, "got completed word for term");
229
230 let suggested_term_hash = StoreTermHash::from(&suggested_word);
231 let suggested_iids = match kv_action.get_term_to_iids(suggested_term_hash) {
232 Ok(Some(suggested_iids)) => suggested_iids,
233 Ok(None) => continue,
234 Err(_) => continue,
235 };
236
237 for suggested_iid in suggested_iids.into_iter().take(*alternates_try) {
238 *alternates_try = unsafe { alternates_try.unchecked_sub(1) };
240
241 let inserted = update_score(
242 scoring_matrix,
243 suggested_iid,
244 suggestion_score,
245 term_idx,
246 term_count,
247 );
248
249 if inserted {
250 if scoring_matrix.len() >= higher_limit {
253 tracing::trace!(?term, "got enough completed results for term");
254
255 break 'suggestions;
256 }
257 }
258 }
259 }
260
261 tracing::trace!(
262 ?term,
263 "done completing results for term, now {} total results",
264 scoring_matrix.len()
265 );
266}
267
268fn update_score(
269 scoring_matrix: &mut IndexMap<StoreObjectIID, Vec<QueryMatchScore>>,
270 iid: StoreObjectIID,
271 score: QueryMatchScore,
272 term_idx: usize,
273 term_count: usize,
274) -> bool {
275 match scoring_matrix.entry(iid) {
276 indexmap::map::Entry::Occupied(mut occupied_entry) => {
278 let entry_score = unsafe { occupied_entry.get_mut().get_unchecked_mut(term_idx) };
280
281 let new_score = score.min(*entry_score);
282
283 tracing::trace!(entry_score, new_score, "Updating to min score");
284 *entry_score = new_score;
285
286 false
287 }
288 indexmap::map::Entry::Vacant(vacant_entry) => {
290 let mut scores = vec![MISSING_MATCH_SCORE; term_count];
291
292 tracing::trace!(new_score = score, "Inserting new score");
293 unsafe { *scores.get_unchecked_mut(term_idx) = score };
295
296 vacant_entry.insert(scores);
297
298 true
299 }
300 }
301}
302
303fn sorted_groups(
304 map: impl ExactSizeIterator<Item = (StoreObjectIID, QueryMatchScore)>,
305) -> impl ExactSizeIterator<Item = (QueryMatchScore, Vec<StoreObjectIID>)> {
306 let mut btree: BTreeMap<QueryMatchScore, Vec<StoreObjectIID>> = BTreeMap::new();
307
308 for (k, v) in map.into_iter() {
309 btree.entry(v).or_default().push(k);
310 }
311
312 btree.into_iter()
313}