Skip to main content

sonic/executor/
search.rs

1// Sonic
2//
3// Fast, lightweight and schema-less search backend
4// Copyright: 2019, Valerian Saliou <valerian@valeriansaliou.name>
5// Copyright: 2026, Rémi Bardon <remi@remibardon.name>
6// License: Mozilla Public License v2.0 (MPL v2.0)
7
8use 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            // Important: acquire database access read lock, and reference it in context. This \
31            //   prevents the database from being erased while using it in this block.
32            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            // Important: acquire bucket store read lock
54            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            // Collect all terms so we know the count right ahead.
62            // PERF: This helps allocating the correct amounts of memory.
63            let terms: Vec<(String, StoreTermHashed, usize)> = lexer.collect();
64            let term_count = terms.len();
65
66            // Store scores for each found IID. Results will then be sorted by
67            // score before being returned. Scores are basically the sum of
68            // Levenshtein distances for each term in the query. Lower score
69            // means better result.
70            // NOTE: We use `IndexMap` instead of `HashMap` to preserve
71            //   insertion order, which correlates to reverse data ingestion
72            //   order.
73            // NOTE: `capacity = 24` to reduce initial grows.
74            let mut scoring_matrix: IndexMap<StoreObjectIID, Vec<QueryMatchScore>> =
75                IndexMap::with_capacity(24usize.min(usize::from(limit)));
76
77            // Look for exact matches.
78            '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                    // Assign a score of `0` as those are exact matches.
88                    let inserted = update_score(&mut scoring_matrix, iid, 0, idx, term_count);
89
90                    if inserted {
91                        // Higher limit now reached?
92                        // Stop acquiring new suggested IIDs now.
93                        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            // Look for words containing `term` as prefix.
106            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            // Look for words like `term` (fuzzy matching).
136            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                    // TODO: Rework the Levenshtein query feature to avoid repeating
147                    //   the same query over and over again. Maybe try to see if
148                    //   `fst_levenshtein` can return distances in its response.
149                    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            // Flatten scores, taking into account missing matches (thanks to
175            // `MISSING_MATCH_SCORE`).
176            let found_iids = scoring_matrix
177                .into_iter()
178                .map(|(iid, scores)| (iid, scores.into_iter().sum()));
179
180            // Sort found IIDs, then flatten.
181            let all_iids = sorted_groups(found_iids).flat_map(|(_, v)| v);
182
183            // Resolve OIDs from IIDs
184            // Notice: we also proceed paging from there
185            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                // Stop there?
190                if index >= limit_usize {
191                    break 'paging;
192                }
193
194                // Read IID-to-OID for this found IID
195                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)] // We’ll refactor this someday, and it’ not public anyway.
212fn 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        // Do not load base results twice for same term as base term
224        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            // SAFETY: We can reach at most `alternates_try`.
239            *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                // Higher limit now reached?
251                // Stop acquiring new suggested IIDs now.
252                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        // If entry already exists, use lowest score.
277        indexmap::map::Entry::Occupied(mut occupied_entry) => {
278            // SAFETY: We always initialize vecs with `term_count` entries.
279            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        // If entry does not exist, insert score.
289        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            // SAFETY: `scores` has `term_count` elements.
294            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}