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/// A delivery line of the query, given back with the results as the user
25/// wrote it, normalized: "92074 PARIS LA DEFENSE CEDEX 12". An address
26/// checked by the geocoder keeps it, even when the code is unknown.
27#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
28pub struct PostalLine {
29 pub code: Option<String>,
30 /// "PARIS LA DEFENSE CEDEX 12".
31 pub label: String,
32}
33
34impl PostalLine {
35 /// The whole line: code and label.
36 pub fn line(&self) -> String {
37 match &self.code {
38 Some(code) => format!("{code} {}", self.label),
39 None => self.label.clone(),
40 }
41 }
42}
43
44/// A delivery line found in a query ([`Profile::postal`]), and where the
45/// place it stands for is.
46#[derive(Debug, Clone)]
47pub struct Postal {
48 pub line: PostalLine,
49 /// Where the line is in the raw query: replaced before searching.
50 pub range: std::ops::Range<usize>,
51 /// The place named by the line, without the delivery words ("PARIS LA
52 /// DEFENSE"): looked up in the index's CEDEX table, searched when
53 /// nothing better is known.
54 pub locality: String,
55}
56
57/// How much a field weighs in the token → document boost.
58#[derive(Debug, Clone, Copy)]
59pub enum Boost {
60 Const(f64),
61 /// `matched` when the document `type` equals `doc_type`, else `otherwise`.
62 ByType {
63 doc_type: &'static str,
64 matched: f64,
65 otherwise: f64,
66 },
67}
68
69impl Boost {
70 pub fn value(&self, doc: &Document) -> f64 {
71 match *self {
72 Boost::Const(v) => v,
73 Boost::ByType {
74 doc_type,
75 matched,
76 otherwise,
77 } => {
78 if doc.get("type").and_then(|v| v.as_str()) == Some(doc_type) {
79 matched
80 } else {
81 otherwise
82 }
83 }
84 }
85 }
86}
87
88/// An indexed text field (addok's `FIELDS`).
89#[derive(Debug, Clone, Copy)]
90pub struct FieldSpec {
91 pub key: &'static str,
92 pub boost: Boost,
93 /// A document missing a required field is not indexed.
94 pub required: bool,
95}
96
97impl FieldSpec {
98 pub const fn new(key: &'static str) -> Self {
99 Self {
100 key,
101 boost: Boost::Const(1.0),
102 required: false,
103 }
104 }
105}
106
107pub trait Profile: Send + Sync {
108 /// Stored in the index; must be unique among registered profiles.
109 fn name(&self) -> &'static str;
110
111 /// Bump whenever token processing changes: an index built with another
112 /// version would no longer match the queries.
113 fn version(&self) -> u32;
114
115 /// Indexed text fields, with their boosts.
116 fn fields(&self) -> &[FieldSpec] {
117 default::FIELDS
118 }
119
120 /// Document keys usable as search filters.
121 fn filters(&self) -> &[&'static str] {
122 default::FILTERS
123 }
124
125 /// Keyboard used to limit fuzzy substitutions to neighbouring keys
126 /// (addok's `FUZZY_KEY_MAP`); `None` tries every letter.
127 fn fuzzy_key_map(&self) -> Option<crate::search::fuzzy::KeyMap> {
128 Some(crate::search::fuzzy::AZERTY)
129 }
130
131 /// Number of results addok computes at least, whatever the requested
132 /// limit; the best `limit` of them are returned. It changes which
133 /// collectors run (a bucket is "full" or "dry" relative to it).
134 fn min_limit(&self) -> usize {
135 1
136 }
137
138 /// Results scoring below this are dropped (addok's `MIN_SCORE`).
139 fn min_score(&self) -> f64 {
140 crate::settings::MIN_SCORE
141 }
142
143 /// Synonyms applied to index and query tokens.
144 fn synonyms(&self) -> Option<&Synonyms> {
145 None
146 }
147
148 /// addok's `QUERY_PROCESSORS`: string cleanup applied to the ASCII
149 /// folded query only, before tokenizing.
150 fn process_query(&self, query: &str) -> String {
151 query.to_string()
152 }
153
154 /// A delivery line of the raw query that is not a place (France: CEDEX),
155 /// searched as the place it stands for and given back with the results.
156 /// Not part of addok: `None` by default.
157 fn postal(&self, _query: &str) -> Option<Postal> {
158 None
159 }
160
161 /// addok's `PROCESSORS` after `tokenize` and `normalize`, run on index
162 /// and query text alike.
163 fn process_tokens(&self, tokens: Vec<Token>) -> Vec<Token> {
164 let tokens = default::flag_housenumber(tokens);
165 match self.synonyms() {
166 Some(synonyms) => synonyms.apply(tokens),
167 None => tokens,
168 }
169 }
170
171 /// Labels a result is compared against, best one first.
172 fn make_labels(&self, doc: &Document, housenumber: Option<&str>) -> Vec<String> {
173 default::make_labels(doc, housenumber)
174 }
175
176 /// The label shown for a result, given the ASCII folded query (empty
177 /// when reverse geocoding). `None` shows the first label, like addok's
178 /// `str(result)`.
179 fn display_label(
180 &self,
181 _doc: &Document,
182 _housenumber: Option<&str>,
183 _query: &str,
184 ) -> Option<String> {
185 None
186 }
187}
188
189/// Index-time text processing (`addok.helpers.index.preprocess`).
190pub fn preprocess(profile: &dyn Profile, text: &str) -> Vec<Token> {
191 profile.process_tokens(tokenize(text))
192}
193
194/// Query-time text processing (`addok.helpers.search.preprocess_query`), on
195/// an already ASCII-folded query.
196pub fn preprocess_query(profile: &dyn Profile, query: &str) -> Vec<Token> {
197 profile.process_tokens(tokenize(&profile.process_query(query)))
198}
199
200/// Profiles an index can be built with.
201pub fn by_name(name: &str) -> Option<Arc<dyn Profile>> {
202 match name {
203 "default" => Some(Arc::new(default::DefaultProfile)),
204 "fr" => Some(Arc::new(fr::FrProfile::new())),
205 "lu" => Some(Arc::new(lu::LuProfile)),
206 "be" => Some(Arc::new(be::BeProfile)),
207 _ => None,
208 }
209}
210
211pub fn names() -> &'static [&'static str] {
212 &["default", "fr", "lu", "be"]
213}