Skip to main content

geocoder_core/profile/be/
mod.rs

1//! Belgium. Names are indexed in every official language of their region
2//! (`name`, `city` lists, the region's language first). The French
3//! processing applies to all of them (the same on index and query, so
4//! Dutch words are only normalized, never mismatched), with Dutch
5//! abbreviations and the Benelux housenumber and postcode handling.
6//!
7//! Labels follow the Belgian convention, "Rue de la Loi 16, 1000
8//! Bruxelles", in the language closest to the query: "Wetstraat 16, 1000
9//! Brussel" when the query is Dutch.
10
11use once_cell::sync::Lazy;
12
13use super::fr::{SYNONYMS_SOURCE, france, phonemicize};
14use super::{FieldSpec, Profile, benelux};
15use crate::doc::{Document, first_str, str_values};
16use crate::text::{Synonyms, Token, ascii, compare_ngrams};
17
18static SYNONYMS: Lazy<Synonyms> = Lazy::new(|| {
19    Synonyms::parse(&format!(
20        "{SYNONYMS_SOURCE}\n{}",
21        include_str!("synonyms.txt")
22    ))
23});
24
25const FILTERS: &[&str] = &["type", "citycode", "postcode"];
26
27pub struct BeProfile;
28
29impl Profile for BeProfile {
30    fn name(&self) -> &'static str {
31        "be"
32    }
33
34    fn version(&self) -> u32 {
35        1
36    }
37
38    fn min_score(&self) -> f64 {
39        0.3
40    }
41
42    fn min_limit(&self) -> usize {
43        10
44    }
45
46    fn fields(&self) -> &[FieldSpec] {
47        super::fr::FIELDS
48    }
49
50    fn filters(&self) -> &[&'static str] {
51        FILTERS
52    }
53
54    fn synonyms(&self) -> Option<&Synonyms> {
55        Some(&SYNONYMS)
56    }
57
58    fn process_query(&self, query: &str) -> String {
59        france::remove_leading_zeros(&benelux::clean_query(query))
60    }
61
62    fn process_tokens(&self, tokens: Vec<Token>) -> Vec<Token> {
63        let tokens = benelux::glue_ordinal(tokens);
64        let tokens: Vec<Token> = tokens.into_iter().map(france::fold_ordinal).collect();
65        let tokens = benelux::flag_housenumber(tokens);
66        let tokens = SYNONYMS.apply(tokens);
67        tokens
68            .into_iter()
69            .map(|t| t.with_value(phonemicize(&t.value)))
70            .collect()
71    }
72
73    /// The French combinations (number first) plus the Belgian ones
74    /// (number after the street), so both ways of writing score alike.
75    fn make_labels(&self, doc: &Document, housenumber: Option<&str>) -> Vec<String> {
76        let mut labels = belgian_labels(doc, housenumber);
77        labels.extend(france::make_labels(doc, housenumber));
78        labels
79    }
80
81    fn display_label(
82        &self,
83        doc: &Document,
84        housenumber: Option<&str>,
85        query: &str,
86    ) -> Option<String> {
87        let candidates = belgian_labels(doc, housenumber);
88        let query = ascii(query);
89        let mut best: Option<(f64, String)> = None;
90        for label in candidates {
91            let score = compare_ngrams(&ascii(&label), &query);
92            if best.as_ref().is_none_or(|(b, _)| score > *b) {
93                best = Some((score, label));
94            }
95        }
96        best.map(|(_, label)| label)
97    }
98}
99
100/// "Rue de la Loi 16, 1000 Bruxelles" for each language; "1000 Bruxelles"
101/// for a municipality or a locality.
102fn belgian_labels(doc: &Document, housenumber: Option<&str>) -> Vec<String> {
103    let postcode = first_str(doc, "postcode").unwrap_or_default();
104    let names = str_values(doc, "name");
105    let cities = str_values(doc, "city");
106    let is_street = !matches!(
107        doc.get("type").and_then(|v| v.as_str()),
108        Some("municipality" | "locality")
109    );
110    let place = |name: &str| format!("{postcode} {name}").trim().to_string();
111    let mut labels = Vec::new();
112    if !is_street {
113        for name in &names {
114            labels.push(place(name));
115        }
116        return labels;
117    }
118    // Each name in its language goes with the city in the same position
119    // (lists are ordered by language), else the first city.
120    for (i, name) in names.iter().enumerate() {
121        let city = cities
122            .get(i)
123            .or(cities.first())
124            .cloned()
125            .unwrap_or_default();
126        let street = match housenumber.filter(|h| !h.is_empty()) {
127            Some(hn) => format!("{name} {hn}"),
128            None => name.clone(),
129        };
130        labels.push(format!("{street}, {}", place(&city)));
131    }
132    labels
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138    use serde_json::json;
139
140    #[test]
141    fn labels_in_the_query_language() {
142        let doc: Document = serde_json::from_value(json!({
143            "type": "street", "name": ["Rue de la Loi", "Wetstraat"],
144            "postcode": "1000", "city": ["Bruxelles", "Brussel"]
145        }))
146        .unwrap();
147        let p = BeProfile;
148        assert_eq!(
149            p.display_label(&doc, Some("16"), "wetstraat 16 brussel")
150                .as_deref(),
151            Some("Wetstraat 16, 1000 Brussel")
152        );
153        assert_eq!(
154            p.display_label(&doc, Some("16"), "16 rue de la loi")
155                .as_deref(),
156            Some("Rue de la Loi 16, 1000 Bruxelles")
157        );
158    }
159}