Skip to main content

geocoder_core/profile/
mod.rs

1//! Country / language profiles.
2//!
3//! The engine (index, collectors, scoring) is generic. Everything that
4//! depends on how addresses are written in a given country goes through a
5//! [`Profile`]: query cleanup, token processing (housenumber detection,
6//! synonyms, phonetics), result labels, indexed fields and filters.
7//!
8//! Every method has a default mirroring core addok's configuration; a
9//! country overrides only what it needs, like addok plugins do. The same
10//! profile must be used to build and to query an index: its name and version
11//! are stored in the index and checked when it is opened.
12
13pub mod be;
14mod benelux;
15pub mod default;
16pub mod fr;
17pub mod lu;
18
19use std::sync::Arc;
20
21use crate::doc::Document;
22use crate::text::{Synonyms, Token, tokenize};
23
24/// How much a field weighs in the token → document boost.
25#[derive(Debug, Clone, Copy)]
26pub enum Boost {
27    Const(f64),
28    /// `matched` when the document `type` equals `doc_type`, else `otherwise`.
29    ByType {
30        doc_type: &'static str,
31        matched: f64,
32        otherwise: f64,
33    },
34}
35
36impl Boost {
37    pub fn value(&self, doc: &Document) -> f64 {
38        match *self {
39            Boost::Const(v) => v,
40            Boost::ByType {
41                doc_type,
42                matched,
43                otherwise,
44            } => {
45                if doc.get("type").and_then(|v| v.as_str()) == Some(doc_type) {
46                    matched
47                } else {
48                    otherwise
49                }
50            }
51        }
52    }
53}
54
55/// An indexed text field (addok's `FIELDS`).
56#[derive(Debug, Clone, Copy)]
57pub struct FieldSpec {
58    pub key: &'static str,
59    pub boost: Boost,
60    /// A document missing a required field is not indexed.
61    pub required: bool,
62}
63
64impl FieldSpec {
65    pub const fn new(key: &'static str) -> Self {
66        Self {
67            key,
68            boost: Boost::Const(1.0),
69            required: false,
70        }
71    }
72}
73
74pub trait Profile: Send + Sync {
75    /// Stored in the index; must be unique among registered profiles.
76    fn name(&self) -> &'static str;
77
78    /// Bump whenever token processing changes: an index built with another
79    /// version would no longer match the queries.
80    fn version(&self) -> u32;
81
82    /// Indexed text fields, with their boosts.
83    fn fields(&self) -> &[FieldSpec] {
84        default::FIELDS
85    }
86
87    /// Document keys usable as search filters.
88    fn filters(&self) -> &[&'static str] {
89        default::FILTERS
90    }
91
92    /// Keyboard used to limit fuzzy substitutions to neighbouring keys
93    /// (addok's `FUZZY_KEY_MAP`); `None` tries every letter.
94    fn fuzzy_key_map(&self) -> Option<crate::search::fuzzy::KeyMap> {
95        Some(crate::search::fuzzy::AZERTY)
96    }
97
98    /// Number of results addok computes at least, whatever the requested
99    /// limit; the best `limit` of them are returned. It changes which
100    /// collectors run (a bucket is "full" or "dry" relative to it).
101    fn min_limit(&self) -> usize {
102        1
103    }
104
105    /// Results scoring below this are dropped (addok's `MIN_SCORE`).
106    fn min_score(&self) -> f64 {
107        crate::settings::MIN_SCORE
108    }
109
110    /// Synonyms applied to index and query tokens.
111    fn synonyms(&self) -> Option<&Synonyms> {
112        None
113    }
114
115    /// addok's `QUERY_PROCESSORS`: string cleanup applied to the ASCII
116    /// folded query only, before tokenizing.
117    fn process_query(&self, query: &str) -> String {
118        query.to_string()
119    }
120
121    /// addok's `PROCESSORS` after `tokenize` and `normalize`, run on index
122    /// and query text alike.
123    fn process_tokens(&self, tokens: Vec<Token>) -> Vec<Token> {
124        let tokens = default::flag_housenumber(tokens);
125        match self.synonyms() {
126            Some(synonyms) => synonyms.apply(tokens),
127            None => tokens,
128        }
129    }
130
131    /// Labels a result is compared against, best one first.
132    fn make_labels(&self, doc: &Document, housenumber: Option<&str>) -> Vec<String> {
133        default::make_labels(doc, housenumber)
134    }
135
136    /// The label shown for a result, given the ASCII folded query (empty
137    /// when reverse geocoding). `None` shows the first label, like addok's
138    /// `str(result)`.
139    fn display_label(
140        &self,
141        _doc: &Document,
142        _housenumber: Option<&str>,
143        _query: &str,
144    ) -> Option<String> {
145        None
146    }
147}
148
149/// Index-time text processing (`addok.helpers.index.preprocess`).
150pub fn preprocess(profile: &dyn Profile, text: &str) -> Vec<Token> {
151    profile.process_tokens(tokenize(text))
152}
153
154/// Query-time text processing (`addok.helpers.search.preprocess_query`), on
155/// an already ASCII-folded query.
156pub fn preprocess_query(profile: &dyn Profile, query: &str) -> Vec<Token> {
157    profile.process_tokens(tokenize(&profile.process_query(query)))
158}
159
160/// Profiles an index can be built with.
161pub fn by_name(name: &str) -> Option<Arc<dyn Profile>> {
162    match name {
163        "default" => Some(Arc::new(default::DefaultProfile)),
164        "fr" => Some(Arc::new(fr::FrProfile::new())),
165        "lu" => Some(Arc::new(lu::LuProfile)),
166        "be" => Some(Arc::new(be::BeProfile)),
167        _ => None,
168    }
169}
170
171pub fn names() -> &'static [&'static str] {
172    &["default", "fr", "lu", "be"]
173}