Skip to main content

geocoder_core/search/
mod.rs

1//! Port of addok 1.3's `Search` helper and its default results collectors:
2//!
3//! 1. only_commons_but_geohash_try_autocomplete
4//! 2. no_tokens_but_housenumbers_and_geohash
5//! 3. no_available_tokens_abort
6//! 4. only_commons
7//! 5. no_meaningful_but_common_try_autocomplete
8//! 6. only_commons_try_autocomplete
9//! 7. bucket_with_meaningful
10//! 8. reduce_with_other_commons
11//! 9. ensure_geohash_results_are_included_if_center_is_given
12//! 10. autocomplete_meaningful
13//! 11. fuzzy
14//! 12. extend_results_extrapoling_relations
15//! 13. extend_results_reducing_tokens
16//!
17//! A collector returning `true` stops the chain.
18
19mod collectors;
20pub mod fuzzy;
21pub mod results;
22
23use std::collections::{HashMap, HashSet};
24use std::time::{Duration, Instant};
25
26use roaring::RoaringBitmap;
27
28use crate::index::Index;
29use crate::index::builder::rank;
30use crate::profile::{Profile, preprocess_query};
31use crate::settings::{
32    BUCKET_MAX, BUCKET_MIN, COMMON_THRESHOLD, GEOHASH_PRECISION, MATCH_THRESHOLD, MAX_MEANINGFUL,
33};
34use crate::text::{Token, ascii};
35use crate::types::{DocId, TokenId};
36use results::{Context, Scored};
37
38/// A query token once looked up in the index.
39#[derive(Debug, Clone)]
40pub(crate) struct QToken {
41    pub token: Token,
42    pub id: Option<TokenId>,
43    pub frequency: usize,
44}
45
46impl QToken {
47    pub fn is_common(&self) -> bool {
48        self.frequency > COMMON_THRESHOLD
49    }
50}
51
52/// A Redis key taking part in an intersection.
53#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54pub(crate) enum Key {
55    Token(TokenId),
56    Geohash,
57    Filter(usize),
58}
59
60pub(crate) struct Helper<'a> {
61    pub index: &'a Index,
62    pub profile: &'a dyn Profile,
63    pub query: String,
64    pub wanted: usize,
65    pub autocomplete: bool,
66    pub fuzzy: bool,
67    pub lat: Option<f64>,
68    pub lon: Option<f64>,
69    pub filters: Vec<RoaringBitmap>,
70    pub check_housenumber: bool,
71    pub only_housenumber: bool,
72    /// All query tokens; the lists below index into it.
73    pub toks: Vec<QToken>,
74    pub tokens: Vec<usize>,
75    pub meaningful: Vec<usize>,
76    pub common: Vec<usize>,
77    pub not_found: Vec<usize>,
78    pub housenumbers: Vec<usize>,
79    pub last_token: Option<usize>,
80    pub should_match_threshold: usize,
81    pub keys: Vec<Key>,
82    pub matched_keys: HashSet<TokenId>,
83    pub bucket: Vec<DocId>,
84    bucket_set: HashSet<DocId>,
85    pub results: HashMap<DocId, Scored>,
86    results_order: Vec<DocId>,
87    geohash: Option<Option<RoaringBitmap>>,
88    /// Documents read and scored by `convert`, and the time spent doing so.
89    scored: usize,
90    scoring: Duration,
91}
92
93/// What a search went through, for its span.
94#[derive(Debug, Clone, Copy, Default)]
95pub(crate) struct Stats {
96    pub tokens: usize,
97    pub meaningful: usize,
98    pub common: usize,
99    /// The collector that stopped the chain, if any did.
100    pub collector: Option<&'static str>,
101    /// Candidates in the bucket once the collectors are done.
102    pub bucket: usize,
103    pub scored: usize,
104    pub scoring: Duration,
105}
106
107pub(crate) struct Query<'q> {
108    pub text: &'q str,
109    pub limit: usize,
110    pub autocomplete: bool,
111    pub lat: Option<f64>,
112    pub lon: Option<f64>,
113    /// (key, values) pairs already restricted to the profile's filters.
114    pub filters: Vec<(String, Vec<String>)>,
115}
116
117impl<'a> Helper<'a> {
118    pub fn new(index: &'a Index, profile: &'a dyn Profile, q: &Query) -> Self {
119        let filters = q
120            .filters
121            .iter()
122            .map(|(key, values)| {
123                let mut union = RoaringBitmap::new();
124                for value in values {
125                    union |= index.filter(key, value);
126                }
127                union
128            })
129            .collect();
130        let type_filter = q.filters.iter().find(|(k, _)| k == "type").map(|(_, v)| v);
131        let check_housenumber =
132            type_filter.is_none_or(|values| values.iter().any(|v| v == "housenumber"));
133        let only_housenumber =
134            type_filter.is_some_and(|values| values.iter().all(|v| v == "housenumber"));
135        Self {
136            index,
137            profile,
138            query: ascii(q.text.trim()),
139            wanted: q.limit,
140            autocomplete: q.autocomplete,
141            fuzzy: true,
142            lat: q.lat,
143            lon: q.lon,
144            filters,
145            check_housenumber,
146            only_housenumber,
147            toks: Vec::new(),
148            tokens: Vec::new(),
149            meaningful: Vec::new(),
150            common: Vec::new(),
151            not_found: Vec::new(),
152            housenumbers: Vec::new(),
153            last_token: None,
154            should_match_threshold: 0,
155            keys: Vec::new(),
156            matched_keys: HashSet::new(),
157            bucket: Vec::new(),
158            bucket_set: HashSet::new(),
159            results: HashMap::new(),
160            results_order: Vec::new(),
161            geohash: None,
162            scored: 0,
163            scoring: Duration::ZERO,
164        }
165    }
166
167    /// SEARCH_PREPROCESSORS: tokenize, search_tokens, select_tokens,
168    /// set_should_match_threshold.
169    pub fn preprocess(&mut self) {
170        let mut tokens = preprocess_query(self.profile, &self.query);
171        if let Some(last) = tokens.last_mut() {
172            last.is_last = true;
173        }
174        // Stable sort, longest first.
175        tokens.sort_by_key(|t| std::cmp::Reverse(t.value.chars().count()));
176        self.toks = tokens
177            .into_iter()
178            .map(|token| {
179                let id = self.index.token_id(&token.value);
180                let frequency = id.map(|id| self.index.frequency(id)).unwrap_or(0);
181                QToken {
182                    token,
183                    id,
184                    frequency,
185                }
186            })
187            .collect();
188        self.last_token = self.toks.iter().position(|t| t.token.is_last);
189
190        for i in 0..self.toks.len() {
191            let t = &self.toks[i];
192            if t.token.is_housenumber() {
193                self.housenumbers.push(i);
194                continue;
195            } else if t.is_common() {
196                self.common.push(i);
197            } else if t.id.is_some() {
198                self.meaningful.push(i);
199            } else {
200                self.not_found.push(i);
201            }
202            self.tokens.push(i);
203        }
204        let toks = &self.toks;
205        self.common.sort_by_key(|&i| toks[i].frequency);
206        self.meaningful.sort_by_key(|&i| toks[i].frequency);
207        if self.meaningful.len() > MAX_MEANINGFUL {
208            let extra = self.meaningful.split_off(MAX_MEANINGFUL);
209            self.common.extend(extra);
210        }
211        self.should_match_threshold = (2.0 / 3.0 * self.tokens.len() as f64).ceil() as usize;
212    }
213
214    pub fn value(&self, i: usize) -> &str {
215        &self.toks[i].token.value
216    }
217
218    /// Python's `token in some_list`, comparing by value.
219    pub fn in_list(&self, list: &[usize], i: usize) -> bool {
220        list.iter().any(|&j| self.value(j) == self.value(i))
221    }
222
223    pub fn key_of(&self, i: usize) -> Option<Key> {
224        self.toks[i].id.map(Key::Token)
225    }
226
227    pub fn keys_of(&self, list: &[usize]) -> Vec<Key> {
228        list.iter().filter_map(|&i| self.key_of(i)).collect()
229    }
230
231    /// Housenumber tokens joined in query order, like `_match_housenumber`.
232    pub fn housenumber_key(&self) -> String {
233        let mut hns: Vec<&QToken> = self.housenumbers.iter().map(|&i| &self.toks[i]).collect();
234        hns.sort_by(|a, b| a.token.positions.cmp(&b.token.positions));
235        hns.iter().map(|t| t.token.value.as_str()).collect()
236    }
237
238    /// Nearby documents, the center cell and its 8 neighbours.
239    pub fn geohash_key(&mut self) -> bool {
240        if self.geohash.is_none() {
241            let computed = match (self.lat, self.lon) {
242                // Python truthiness: a 0.0 coordinate counts as missing.
243                (Some(lat), Some(lon)) if lat != 0.0 && lon != 0.0 => {
244                    let mut union = RoaringBitmap::new();
245                    for cell in expand(lat, lon) {
246                        union |= self.index.geohash(&cell);
247                    }
248                    Some(union).filter(|u| !u.is_empty())
249                }
250                _ => None,
251            };
252            self.geohash = Some(computed);
253        }
254        matches!(self.geohash, Some(Some(_)))
255    }
256
257    // Bucket state.
258
259    pub fn bucket_full(&self) -> bool {
260        self.bucket.len() >= self.wanted && self.bucket.len() < BUCKET_MAX
261    }
262
263    pub fn bucket_overflow(&self) -> bool {
264        self.bucket.len() >= BUCKET_MAX
265    }
266
267    pub fn bucket_dry(&self) -> bool {
268        self.bucket.len() < self.wanted
269    }
270
271    pub fn bucket_empty(&self) -> bool {
272        self.bucket.is_empty()
273    }
274
275    pub fn only_commons(&self) -> bool {
276        !self.tokens.is_empty() && self.tokens.len() == self.common.len()
277    }
278
279    pub fn pass_should_match_threshold(&self) -> bool {
280        self.matched_keys.len() >= self.should_match_threshold
281    }
282
283    pub fn extend_bucket(&mut self, ids: Vec<DocId>) {
284        for id in ids {
285            if self.bucket_set.insert(id) {
286                self.bucket.push(id);
287            }
288        }
289    }
290
291    pub fn add_to_bucket(&mut self, keys: &[Key], limit: Option<usize>) {
292        self.matched_keys
293            .extend(keys.iter().filter_map(|k| match k {
294                Key::Token(t) => Some(*t),
295                _ => None,
296            }));
297        // `limit or (BUCKET_MAX - len(bucket))`, possibly not positive.
298        let limit = match limit {
299            Some(l) if l > 0 => l as isize,
300            _ => BUCKET_MAX as isize - self.bucket.len() as isize,
301        };
302        let ids = self.intersect(keys, limit);
303        self.extend_bucket(ids);
304    }
305
306    pub fn new_bucket(&mut self, keys: &[Key], limit: usize) {
307        self.matched_keys = keys
308            .iter()
309            .filter_map(|k| match k {
310                Key::Token(t) => Some(*t),
311                _ => None,
312            })
313            .collect();
314        let ids = self.intersect(keys, limit as isize);
315        self.bucket.clear();
316        self.bucket_set.clear();
317        self.extend_bucket(ids);
318    }
319
320    /// addok's `intersect` extends the list it receives with the filters.
321    /// When that list is `helper.keys` itself, the filters stay in it.
322    pub fn absorb_filters_into_keys(&mut self) {
323        for i in 0..self.filters.len() {
324            self.keys.push(Key::Filter(i));
325        }
326    }
327
328    /// `Search.intersect`: top documents of the keys (plus filters).
329    pub fn intersect(&mut self, keys: &[Key], limit: isize) -> Vec<DocId> {
330        let limit = if limit > 0 {
331            limit as usize
332        } else {
333            self.wanted.max(BUCKET_MAX)
334        };
335        if keys.is_empty() {
336            return Vec::new();
337        }
338        let mut all: Vec<Key> = Vec::with_capacity(keys.len() + self.filters.len());
339        for key in keys
340            .iter()
341            .copied()
342            .chain((0..self.filters.len()).map(Key::Filter))
343        {
344            if !all.contains(&key) {
345                all.push(key);
346            }
347        }
348        if all.len() == 1 {
349            return match all[0] {
350                Key::Token(t) => self.index.top(t, limit).collect(),
351                Key::Geohash => self.geohash_set().iter().collect(),
352                Key::Filter(i) => self.filters[i].iter().collect(),
353            };
354        }
355        self.zinter(&all, limit)
356    }
357
358    fn geohash_set(&mut self) -> RoaringBitmap {
359        self.geohash_key();
360        self.geohash.clone().flatten().unwrap_or_default()
361    }
362
363    /// `ZINTERSTORE` (scores summed, plain sets count 1) then `ZREVRANGE`.
364    fn zinter(&mut self, keys: &[Key], limit: usize) -> Vec<DocId> {
365        let mut tokens: Vec<TokenId> = Vec::new();
366        let mut sets: Vec<RoaringBitmap> = Vec::new();
367        for key in keys {
368            match *key {
369                Key::Token(t) => tokens.push(t),
370                Key::Geohash => sets.push(self.geohash_set()),
371                Key::Filter(i) => sets.push(self.filters[i].clone()),
372            }
373        }
374        let set_score = sets.len() as f64;
375        let mut scored: Vec<(DocId, f64)> = Vec::new();
376        if tokens.is_empty() {
377            let mut iter = sets.into_iter();
378            let mut inter = iter.next().unwrap_or_default();
379            for s in iter {
380                inter &= s;
381            }
382            scored.extend(inter.iter().map(|d| (d, set_score)));
383        } else {
384            let index = self.index;
385            tokens.sort_by_key(|&t| index.frequency(t));
386            let driver = index.postings(tokens[0]);
387            let others: Vec<_> = tokens[1..].iter().map(|&t| index.postings(t)).collect();
388            'docs: for (doc, boost) in driver.iter() {
389                let mut total = boost as f64;
390                for postings in &others {
391                    match postings.find(doc) {
392                        Some(b) => total += b as f64,
393                        None => continue 'docs,
394                    }
395                }
396                if sets.iter().any(|s| !s.contains(doc)) {
397                    continue;
398                }
399                scored.push((doc, total + set_score));
400            }
401        }
402        top(scored, limit)
403    }
404
405    /// Score the documents of the bucket not scored yet.
406    pub fn convert(&mut self) {
407        let housenumber = self.housenumber_key();
408        let ctx = Context {
409            profile: self.profile,
410            query: &self.query,
411            autocomplete: self.autocomplete,
412            lat: self.lat,
413            lon: self.lon,
414            check_housenumber: self.check_housenumber,
415            only_housenumber: self.only_housenumber,
416            housenumber: &housenumber,
417        };
418        let pending: Vec<DocId> = self
419            .bucket
420            .iter()
421            .copied()
422            .filter(|id| !self.results.contains_key(id))
423            .collect();
424        if pending.is_empty() {
425            return;
426        }
427        let started = Instant::now();
428        self.scored += pending.len();
429        for id in pending {
430            // A rejected document is not kept, and would be tried again.
431            if let Some(scored) = self
432                .index
433                .document(id)
434                .and_then(|doc| results::process(&ctx, id, doc))
435            {
436                self.results.insert(id, scored);
437                self.results_order.push(id);
438            }
439        }
440        self.scoring += started.elapsed();
441    }
442
443    pub fn cream(&self) -> usize {
444        self.results
445            .values()
446            .filter(|r| r.str_distance() >= MATCH_THRESHOLD)
447            .count()
448    }
449
450    pub fn has_cream(&mut self) -> bool {
451        if self.bucket_empty() || self.bucket_overflow() || self.bucket.len() > BUCKET_MIN {
452            return false;
453        }
454        self.convert();
455        self.cream() > 0
456    }
457
458    /// Run the collectors then rank, each in its own span (INFO) under the
459    /// caller's.
460    pub fn run(mut self) -> (Vec<Scored>, Stats) {
461        self.preprocess();
462        let collector = tracing::info_span!("geocoder.collect", sentry.op = "geocoder.collect")
463            .in_scope(|| collectors::run(&mut self));
464        let mut stats = Stats {
465            tokens: self.tokens.len(),
466            meaningful: self.meaningful.len(),
467            common: self.common.len(),
468            collector,
469            bucket: self.bucket.len(),
470            ..Stats::default()
471        };
472        let ranked = tracing::info_span!("geocoder.rank", sentry.op = "geocoder.rank")
473            .in_scope(|| self.render(&mut stats));
474        (ranked, stats)
475    }
476
477    fn render(mut self, stats: &mut Stats) -> Vec<Scored> {
478        self.convert();
479        stats.scored = self.scored;
480        stats.scoring = self.scoring;
481        let mut ranked: Vec<Scored> = self
482            .results_order
483            .iter()
484            .filter_map(|id| self.results.remove(id))
485            .collect();
486        // Stable, like Python's sort.
487        ranked.sort_by(|a, b| {
488            b.score()
489                .partial_cmp(&a.score())
490                .unwrap_or(std::cmp::Ordering::Equal)
491        });
492        ranked.truncate(self.wanted);
493        let min_score = self.profile.min_score();
494        ranked.retain(|r| r.score() >= min_score);
495        ranked
496    }
497}
498
499/// Best `limit` documents by summed score, Redis order.
500fn top(mut scored: Vec<(DocId, f64)>, limit: usize) -> Vec<DocId> {
501    let cmp = |a: &(DocId, f64), b: &(DocId, f64)| rank(a.1, a.0, b.1, b.0);
502    if scored.len() > limit {
503        scored.select_nth_unstable_by(limit, cmp);
504        scored.truncate(limit);
505    }
506    scored.sort_unstable_by(cmp);
507    scored.into_iter().map(|(d, _)| d).collect()
508}
509
510/// `geohash.expand`: the cell and its 8 neighbours.
511pub(crate) fn expand(lat: f64, lon: f64) -> Vec<String> {
512    let Ok(cell) = geohash::encode(geohash::Coord { x: lon, y: lat }, GEOHASH_PRECISION) else {
513        return Vec::new();
514    };
515    expand_cell(&cell)
516}
517
518pub(crate) fn expand_cell(cell: &str) -> Vec<String> {
519    let mut cells = vec![cell.to_string()];
520    if let Ok(n) = geohash::neighbors(cell) {
521        cells.extend([n.n, n.ne, n.e, n.se, n.s, n.sw, n.w, n.nw]);
522    }
523    cells
524}