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 profile;
13pub mod readers;
14pub mod search;
15pub mod settings;
16#[cfg(feature = "signed")]
17pub mod signed;
18pub mod text;
19mod types;
20
21use std::collections::HashSet;
22use std::sync::Arc;
23
24pub use doc::Document;
25pub use error::GeocoderError;
26pub use index::{Index, IndexBuilder, Meta};
27pub use profile::Profile;
28pub use types::{ReverseOpts, SearchOpts, SearchResult};
29
30use search::results::{Scored, process_reverse};
31use search::{Helper, Query, expand, expand_cell};
32use settings::{DEFAULT_LIMIT, QUERY_MAX_LENGTH};
33
34/// An index opened with the profile it was built with.
35pub struct Geocoder {
36    index: Index,
37    profile: Arc<dyn Profile>,
38}
39
40impl Geocoder {
41    pub fn open(path: &std::path::Path) -> Result<Self, GeocoderError> {
42        let index = Index::open(path)?;
43        let profile = profile::by_name(&index.meta.profile).ok_or(GeocoderError::UnknownProfile)?;
44        if profile.version() != index.meta.profile_version {
45            return Err(GeocoderError::ProfileVersion {
46                profile: index.meta.profile.clone(),
47                index: index.meta.profile_version,
48                code: profile.version(),
49            });
50        }
51        Ok(Self { index, profile })
52    }
53
54    pub fn meta(&self) -> &Meta {
55        &self.index.meta
56    }
57
58    pub fn index(&self) -> &Index {
59        &self.index
60    }
61
62    pub fn profile(&self) -> &dyn Profile {
63        self.profile.as_ref()
64    }
65
66    /// Forward geocoding, like addok's `/search`.
67    pub fn search(&self, query: &str, opts: SearchOpts) -> Vec<SearchResult> {
68        if text::ascii(query.trim()).chars().count() > QUERY_MAX_LENGTH {
69            return Vec::new();
70        }
71        let limit = opts.limit.unwrap_or(DEFAULT_LIMIT);
72        let q = Query {
73            text: query,
74            // addok may be asked for more results than returned (see
75            // `Profile::min_limit`): the thresholds of its collectors depend
76            // on it.
77            limit: limit.max(self.profile.min_limit()),
78            autocomplete: opts.autocomplete.unwrap_or(true),
79            lat: opts.lat,
80            lon: opts.lon,
81            filters: self.filters(&opts.filters),
82        };
83        let mut results = Helper::new(&self.index, self.profile.as_ref(), &q).run();
84        results.truncate(limit);
85        results.into_iter().map(to_result).collect()
86    }
87
88    /// Same as [`Geocoder::search`] with autocomplete forced on.
89    pub fn autocomplete(&self, query: &str, opts: SearchOpts) -> Vec<SearchResult> {
90        self.search(
91            query,
92            SearchOpts {
93                autocomplete: Some(true),
94                ..opts
95            },
96        )
97    }
98
99    /// Reverse geocoding, like addok's `/reverse`.
100    pub fn reverse(&self, lat: f64, lon: f64, opts: ReverseOpts) -> Vec<SearchResult> {
101        let limit = opts.limit.unwrap_or(1);
102        let filters = self.filters(&opts.filters);
103        let type_filter = filters.iter().find(|(k, _)| k == "type").map(|(_, v)| v);
104        let check_housenumber =
105            type_filter.is_none_or(|values| values.iter().any(|v| v == "housenumber"));
106        let only_housenumber =
107            type_filter.is_some_and(|values| values.iter().all(|v| v == "housenumber"));
108        let masks: Vec<roaring::RoaringBitmap> = filters
109            .iter()
110            .map(|(key, values)| {
111                values
112                    .iter()
113                    .map(|v| self.index.filter(key, v))
114                    .fold(Default::default(), |a, b| a | b)
115            })
116            .collect();
117
118        let mut fetched: Vec<String> = Vec::new();
119        let mut keys: HashSet<u32> = HashSet::new();
120        let fetch = |cells: &[String], keys: &mut HashSet<u32>, fetched: &mut Vec<String>| {
121            for cell in cells {
122                let mut docs = self.index.geohash(cell);
123                for mask in &masks {
124                    docs &= mask;
125                }
126                keys.extend(docs.iter());
127                fetched.push(cell.clone());
128            }
129        };
130        let grow = |cells: &[String], fetched: &[String]| -> Vec<String> {
131            cells
132                .iter()
133                .flat_map(|c| expand_cell(c))
134                .filter(|n| !fetched.contains(n))
135                .collect()
136        };
137        let first = expand(lat, lon);
138        fetch(&first, &mut keys, &mut fetched);
139        if keys.is_empty() {
140            let next = grow(&first, &fetched);
141            fetch(&next, &mut keys, &mut fetched);
142        }
143
144        let mut results: Vec<Scored> = keys
145            .into_iter()
146            .filter_map(|id| {
147                let doc = self.index.document(id)?;
148                process_reverse(
149                    self.profile.as_ref(),
150                    id,
151                    doc,
152                    lat,
153                    lon,
154                    check_housenumber,
155                    only_housenumber,
156                )
157            })
158            .collect();
159        results.sort_by(|a, b| {
160            b.score()
161                .partial_cmp(&a.score())
162                .unwrap_or(std::cmp::Ordering::Equal)
163        });
164        results.truncate(limit);
165        results.into_iter().map(to_result).collect()
166    }
167
168    /// Keep the filters the profile knows, their values trimmed, deduplicated,
169    /// limited to `MAX_FILTER_VALUES` and sorted (addok 1.3's
170    /// `_normalize_filter_values`). Several values are OR-ed.
171    fn filters(
172        &self,
173        filters: &std::collections::HashMap<String, Vec<String>>,
174    ) -> Vec<(String, Vec<String>)> {
175        let mut out: Vec<(String, Vec<String>)> = self
176            .profile
177            .filters()
178            .iter()
179            .filter_map(|&name| {
180                let mut values: Vec<String> = Vec::new();
181                for v in filters.get(name)? {
182                    let v = v.trim().to_string();
183                    if !v.is_empty() && !values.contains(&v) {
184                        values.push(v);
185                    }
186                }
187                values.truncate(settings::MAX_FILTER_VALUES);
188                values.sort();
189                (!values.is_empty()).then(|| (name.to_string(), values))
190            })
191            .collect();
192        out.sort();
193        out
194    }
195}
196
197fn to_result(r: Scored) -> SearchResult {
198    SearchResult {
199        label: r.label(),
200        score: r.score() as f32,
201        housenumber: r.housenumber.clone(),
202        lat: r.lat(),
203        lon: r.lon(),
204        distance_km: r.distance_km,
205        doc: serde_json::Value::Object(r.doc),
206    }
207}