Skip to main content

geocoder_core/
lib.rs

1//! Address geocoding, ported from addok.
2//!
3//! - [`profile`]: country specific text processing (`default`, `fr`, `lu`, `be`).
4//! - [`readers`]: data sources converted to addok's document format.
5//! - [`IndexBuilder`] / [`Index`]: the on-disk index.
6//! - [`Geocoder`]: search and reverse geocoding.
7//! - `signed` (feature `signed`): signed manifests of prebuilt indexes.
8
9pub mod doc;
10mod error;
11pub mod index;
12pub mod postal;
13pub mod profile;
14pub mod readers;
15pub mod search;
16pub mod settings;
17#[cfg(feature = "signed")]
18pub mod signed;
19pub mod text;
20mod types;
21
22use std::collections::HashSet;
23use std::sync::Arc;
24
25pub use doc::Document;
26pub use error::GeocoderError;
27pub use index::{Index, IndexBuilder, Meta};
28pub use profile::Profile;
29pub use types::{ReverseOpts, SearchOpts, SearchResult};
30
31use search::results::{Scored, process_reverse};
32use search::{Helper, Query, expand, expand_cell};
33use settings::{DEFAULT_LIMIT, QUERY_MAX_LENGTH};
34
35/// An index opened with the profile it was built with.
36pub struct Geocoder {
37    index: Index,
38    profile: Arc<dyn Profile>,
39}
40
41impl Geocoder {
42    pub fn open(path: &std::path::Path) -> Result<Self, GeocoderError> {
43        let span = tracing::info_span!(
44            "geocoder.open",
45            sentry.op = "geocoder.open",
46            path = %path.display(),
47            profile = tracing::field::Empty,
48            documents = tracing::field::Empty,
49        );
50        let _entered = span.enter();
51        let index = Index::open(path)?;
52        span.record("profile", index.meta.profile.as_str());
53        span.record("documents", index.meta.documents);
54        let profile = profile::by_name(&index.meta.profile).ok_or(GeocoderError::UnknownProfile)?;
55        if profile.version() != index.meta.profile_version {
56            return Err(GeocoderError::ProfileVersion {
57                profile: index.meta.profile.clone(),
58                index: index.meta.profile_version,
59                code: profile.version(),
60            });
61        }
62        Ok(Self { index, profile })
63    }
64
65    pub fn meta(&self) -> &Meta {
66        &self.index.meta
67    }
68
69    pub fn index(&self) -> &Index {
70        &self.index
71    }
72
73    pub fn profile(&self) -> &dyn Profile {
74        self.profile.as_ref()
75    }
76
77    /// Forward geocoding, like addok's `/search`.
78    ///
79    /// Runs in a `geocoder.search` span (INFO) describing the query's shape,
80    /// never its text: token counts, the collector that settled it, the
81    /// documents read and scored, the results.
82    pub fn search(&self, query: &str, opts: SearchOpts) -> Vec<SearchResult> {
83        let limit = opts.limit.unwrap_or(DEFAULT_LIMIT);
84        let autocomplete = opts.autocomplete.unwrap_or(true);
85        let span = tracing::info_span!(
86            "geocoder.search",
87            sentry.op = "geocoder.search",
88            profile = self.profile.name(),
89            autocomplete,
90            limit,
91            near = opts.lat.is_some() && opts.lon.is_some(),
92            filters = opts.filters.len(),
93            tokens = tracing::field::Empty,
94            meaningful = tracing::field::Empty,
95            common = tracing::field::Empty,
96            collector = tracing::field::Empty,
97            bucket = tracing::field::Empty,
98            scored = tracing::field::Empty,
99            scoring_ms = tracing::field::Empty,
100            results = tracing::field::Empty,
101            postal = tracing::field::Empty,
102        );
103        let _entered = span.enter();
104        if text::ascii(query.trim()).chars().count() > QUERY_MAX_LENGTH {
105            span.record("results", 0);
106            return Vec::new();
107        }
108        let filters = self.filters(&opts.filters);
109        // addok may be asked for more results than returned (see
110        // `Profile::min_limit`): the thresholds of its collectors depend
111        // on it.
112        let wanted = limit.max(self.profile.min_limit());
113        let run = |text: &str, filters: Vec<(String, Vec<String>)>| {
114            let q = Query {
115                text,
116                limit: wanted,
117                autocomplete,
118                lat: opts.lat,
119                lon: opts.lon,
120                filters,
121            };
122            Helper::new(&self.index, self.profile.as_ref(), &q).run()
123        };
124
125        let postal = self.profile.postal(query);
126        let (mut results, stats) = match &postal {
127            None => run(query, filters),
128            Some(p) => {
129                let plan = self.postal_plan(query, p, &filters);
130                span.record("postal", plan.route);
131                let restricted = plan.filters != filters;
132                let best = |r: &(Vec<Scored>, _)| r.0.first().map_or(0.0, Scored::score);
133                let mut found = run(&plan.text, plan.filters.clone());
134                if restricted {
135                    // Restricted to the right municipalities, the locality
136                    // helps when it names one (LILLE) and hurts when it does
137                    // not (PARIS LA DEFENSE): both are tried.
138                    let names_it = found
139                        .0
140                        .first()
141                        .is_some_and(|r| names_city(&r.doc, &p.locality));
142                    if !names_it {
143                        let without = run(&plan.without_locality, plan.filters);
144                        if best(&without) > best(&found) {
145                            found = without;
146                        }
147                    }
148                }
149                if best(&found) < POSTAL_FALLBACK_SCORE && plan.text != plan.fallback {
150                    // The table may be wrong or stale, the locality not a
151                    // place: the query as before, anywhere, if it does better.
152                    let anywhere = run(&plan.fallback, filters);
153                    if best(&anywhere) > best(&found) {
154                        span.record("postal", "fallback");
155                        anywhere
156                    } else {
157                        found
158                    }
159                } else {
160                    found
161                }
162            }
163        };
164        results.truncate(limit);
165        span.record("tokens", stats.tokens);
166        span.record("meaningful", stats.meaningful);
167        span.record("common", stats.common);
168        if let Some(collector) = stats.collector {
169            span.record("collector", collector);
170        }
171        span.record("bucket", stats.bucket);
172        span.record("scored", stats.scored);
173        span.record("scoring_ms", stats.scoring.as_secs_f64() * 1000.0);
174        span.record("results", results.len());
175        results
176            .into_iter()
177            .map(to_result)
178            .map(|r| match &postal {
179                Some(p) => with_postal(r, &p.line),
180                None => r,
181            })
182            .collect()
183    }
184
185    /// What to search for a query carrying a delivery line:
186    /// - its code is a real postcode: the line, without the delivery words;
187    /// - the code is known: the municipalities it serves, as a filter;
188    /// - the locality is known (a business district, a new town): idem;
189    /// - otherwise the locality as written.
190    ///
191    /// A `citycode` filter given by the caller wins over the table's.
192    fn postal_plan(
193        &self,
194        query: &str,
195        p: &profile::Postal,
196        filters: &[(String, Vec<String>)],
197    ) -> PostalPlan {
198        let with = |middle: &str| {
199            let text = format!(
200                "{} {middle} {}",
201                &query[..p.range.start],
202                &query[p.range.end..]
203            );
204            text.split_whitespace().collect::<Vec<_>>().join(" ")
205        };
206        // The query as is: addok-france keeps the department of the code,
207        // what the geocoder did before CEDEX lines were handled.
208        let fallback = query.to_string();
209        let filtered = |route: &'static str, citycodes: &[String]| {
210            let mut out = filters.to_vec();
211            if !out.iter().any(|(k, _)| k == "citycode") {
212                out.push(("citycode".into(), citycodes.to_vec()));
213                out.sort();
214            }
215            // The locality stays: it names the municipality among those of
216            // the code (59012 LILLE CEDEX serves Lille and Dunkerque).
217            PostalPlan {
218                route,
219                text: with(&p.locality),
220                without_locality: with(""),
221                filters: out,
222                fallback: fallback.clone(),
223            }
224        };
225        let plain = |route: &'static str, text: String| PostalPlan {
226            route,
227            without_locality: text.clone(),
228            text,
229            filters: filters.to_vec(),
230            fallback: fallback.clone(),
231        };
232        let table = self.index.cedex();
233        let by_code = p
234            .line
235            .code
236            .as_deref()
237            .zip(table)
238            .map_or(&[][..], |(code, t)| t.by_code(code));
239        let by_locality = table.map_or(&[][..], |t| t.by_locality(&p.locality));
240        match p.line.code.as_deref() {
241            Some(code) if !self.index.filter("postcode", code).is_empty() => {
242                plain("postcode", with(&format!("{code} {}", p.locality)))
243            }
244            _ if !by_code.is_empty() => filtered("code", by_code),
245            _ if !by_locality.is_empty() => filtered("locality", by_locality),
246            _ => plain("unknown", with(&p.locality)),
247        }
248    }
249
250    /// Same as [`Geocoder::search`] with autocomplete forced on.
251    pub fn autocomplete(&self, query: &str, opts: SearchOpts) -> Vec<SearchResult> {
252        self.search(
253            query,
254            SearchOpts {
255                autocomplete: Some(true),
256                ..opts
257            },
258        )
259    }
260
261    /// Reverse geocoding, like addok's `/reverse`.
262    pub fn reverse(&self, lat: f64, lon: f64, opts: ReverseOpts) -> Vec<SearchResult> {
263        let limit = opts.limit.unwrap_or(1);
264        let span = tracing::info_span!(
265            "geocoder.reverse",
266            sentry.op = "geocoder.reverse",
267            profile = self.profile.name(),
268            limit,
269            filters = opts.filters.len(),
270            candidates = tracing::field::Empty,
271            results = tracing::field::Empty,
272        );
273        let _entered = span.enter();
274        let filters = self.filters(&opts.filters);
275        let type_filter = filters.iter().find(|(k, _)| k == "type").map(|(_, v)| v);
276        let check_housenumber =
277            type_filter.is_none_or(|values| values.iter().any(|v| v == "housenumber"));
278        let only_housenumber =
279            type_filter.is_some_and(|values| values.iter().all(|v| v == "housenumber"));
280        let masks: Vec<roaring::RoaringBitmap> = filters
281            .iter()
282            .map(|(key, values)| {
283                values
284                    .iter()
285                    .map(|v| self.index.filter(key, v))
286                    .fold(Default::default(), |a, b| a | b)
287            })
288            .collect();
289
290        let mut fetched: Vec<String> = Vec::new();
291        let mut keys: HashSet<u32> = HashSet::new();
292        let fetch = |cells: &[String], keys: &mut HashSet<u32>, fetched: &mut Vec<String>| {
293            for cell in cells {
294                let mut docs = self.index.geohash(cell);
295                for mask in &masks {
296                    docs &= mask;
297                }
298                keys.extend(docs.iter());
299                fetched.push(cell.clone());
300            }
301        };
302        let grow = |cells: &[String], fetched: &[String]| -> Vec<String> {
303            cells
304                .iter()
305                .flat_map(|c| expand_cell(c))
306                .filter(|n| !fetched.contains(n))
307                .collect()
308        };
309        let first = expand(lat, lon);
310        fetch(&first, &mut keys, &mut fetched);
311        if keys.is_empty() {
312            let next = grow(&first, &fetched);
313            fetch(&next, &mut keys, &mut fetched);
314        }
315
316        span.record("candidates", keys.len());
317        let mut results: Vec<Scored> = keys
318            .into_iter()
319            .filter_map(|id| {
320                let doc = self.index.document(id)?;
321                process_reverse(
322                    self.profile.as_ref(),
323                    id,
324                    doc,
325                    lat,
326                    lon,
327                    check_housenumber,
328                    only_housenumber,
329                )
330            })
331            .collect();
332        results.sort_by(|a, b| {
333            b.score()
334                .partial_cmp(&a.score())
335                .unwrap_or(std::cmp::Ordering::Equal)
336        });
337        results.truncate(limit);
338        span.record("results", results.len());
339        results.into_iter().map(to_result).collect()
340    }
341
342    /// Keep the filters the profile knows, their values trimmed, deduplicated,
343    /// limited to `MAX_FILTER_VALUES` and sorted (addok 1.3's
344    /// `_normalize_filter_values`). Several values are OR-ed.
345    fn filters(
346        &self,
347        filters: &std::collections::HashMap<String, Vec<String>>,
348    ) -> Vec<(String, Vec<String>)> {
349        let mut out: Vec<(String, Vec<String>)> = self
350            .profile
351            .filters()
352            .iter()
353            .filter_map(|&name| {
354                let mut values: Vec<String> = Vec::new();
355                for v in filters.get(name)? {
356                    let v = v.trim().to_string();
357                    if !v.is_empty() && !values.contains(&v) {
358                        values.push(v);
359                    }
360                }
361                values.truncate(settings::MAX_FILTER_VALUES);
362                values.sort();
363                (!values.is_empty()).then(|| (name.to_string(), values))
364            })
365            .collect();
366        out.sort();
367        out
368    }
369}
370
371/// Below this, a search restricted to the municipalities of a CEDEX is
372/// tried again without the restriction.
373const POSTAL_FALLBACK_SCORE: f64 = 0.5;
374
375/// Whether one of the document's cities is `locality` ("PARIS LA DEFENSE",
376/// "ST QUENTIN"), ignoring case, accents and punctuation.
377fn names_city(doc: &Document, locality: &str) -> bool {
378    let words = |s: &str| -> Vec<String> {
379        text::ascii(s)
380            .to_uppercase()
381            .split(|c: char| !c.is_ascii_alphanumeric())
382            .filter(|w| !w.is_empty())
383            .map(|w| match w {
384                "ST" => "SAINT".to_string(),
385                "STE" => "SAINTE".to_string(),
386                w => w.to_string(),
387            })
388            .collect()
389    };
390    let wanted = words(locality);
391    !wanted.is_empty()
392        && doc::str_values(doc, "city")
393            .iter()
394            .any(|city| words(city) == wanted)
395}
396
397struct PostalPlan {
398    /// For the `geocoder.search` span: how the place was found.
399    route: &'static str,
400    text: String,
401    /// `text` without the locality, tried too when restricted.
402    without_locality: String,
403    filters: Vec<(String, Vec<String>)>,
404    /// Searched when `text` finds nothing.
405    fallback: String,
406}
407
408fn to_result(r: Scored) -> SearchResult {
409    SearchResult {
410        label: r.label(),
411        score: r.score() as f32,
412        housenumber: r.housenumber.clone(),
413        lat: r.lat(),
414        lon: r.lon(),
415        distance_km: r.distance_km,
416        doc: serde_json::Value::Object(r.doc),
417        postal: None,
418        postal_label: None,
419    }
420}
421
422/// The delivery line given back, and the mail label: the street part of the
423/// result (none for a municipality), then the line.
424fn with_postal(mut r: SearchResult, line: &profile::PostalLine) -> SearchResult {
425    let name = r
426        .doc
427        .get("name")
428        .and_then(|n| match n {
429            serde_json::Value::Array(a) => a.first(),
430            n => Some(n),
431        })
432        .and_then(|n| n.as_str())
433        .map(str::to_string);
434    let kind = r
435        .doc
436        .get("type")
437        .and_then(|t| t.as_str())
438        .unwrap_or_default();
439    let street = match (kind, name) {
440        ("municipality", _) | (_, None) => None,
441        (_, Some(name)) => Some(match &r.housenumber {
442            Some(hn) => format!("{hn} {name}"),
443            None => name,
444        }),
445    };
446    r.postal_label = Some(match street {
447        Some(street) => format!("{street} {}", line.line()),
448        None => line.line(),
449    });
450    r.postal = Some(line.clone());
451    r
452}