Skip to main content

geocoder_core/index/
builder.rs

1use std::cmp::Ordering;
2use std::collections::HashMap;
3use std::io::{BufWriter, Write};
4use std::path::Path;
5use std::sync::Arc;
6
7use byteorder::{LittleEndian, WriteBytesExt};
8use flate2::Compression;
9use flate2::write::ZlibEncoder;
10use fst::MapBuilder;
11use roaring::RoaringBitmap;
12use serde_json::Value;
13
14use super::format::{MAGIC, Meta, SECTION_HEADER_SIZE, SectionHeader, SectionKind, VERSION};
15use super::tie_break;
16use crate::doc::{Document, first_f64, py_str, truthy};
17use crate::error::GeocoderError;
18use crate::profile::{Profile, preprocess};
19use crate::settings::{GEOHASH_PRECISION, IMPORTANCE_WEIGHT, MAX_EDGE_NGRAMS, MIN_EDGE_NGRAMS};
20use crate::text::edge_ngrams;
21use crate::types::{DocId, TokenId};
22
23/// Builds an index the way addok's batch import does: `prepare_housenumbers`,
24/// then the housenumbers, fields, pairs, filters and geohash indexers, then
25/// `addok ngrams`.
26pub struct IndexBuilder {
27    profile: Arc<dyn Profile>,
28    token_ids: HashMap<String, TokenId>,
29    token_strings: Vec<String>,
30    postings: Vec<Vec<(DocId, f32)>>,
31    pairs: Vec<RoaringBitmap>,
32    geohashes: HashMap<String, RoaringBitmap>,
33    filters: HashMap<String, RoaringBitmap>,
34    doc_offsets: Vec<u64>,
35    doc_blobs: Vec<u8>,
36    /// `addok.helpers.index._CACHE`: field values repeat a lot.
37    cache: HashMap<String, Vec<String>>,
38    skipped: usize,
39}
40
41impl IndexBuilder {
42    pub fn new(profile: Arc<dyn Profile>) -> Self {
43        Self {
44            profile,
45            token_ids: HashMap::new(),
46            token_strings: Vec::new(),
47            postings: Vec::new(),
48            pairs: Vec::new(),
49            geohashes: HashMap::new(),
50            filters: HashMap::new(),
51            doc_offsets: vec![0],
52            doc_blobs: Vec::new(),
53            cache: HashMap::new(),
54            skipped: 0,
55        }
56    }
57
58    pub fn documents(&self) -> usize {
59        self.doc_offsets.len() - 1
60    }
61
62    /// Documents rejected so far (missing required field or coordinates).
63    pub fn skipped(&self) -> usize {
64        self.skipped
65    }
66
67    fn preprocess(&mut self, text: &str) -> Vec<String> {
68        if let Some(hit) = self.cache.get(text) {
69            return hit.clone();
70        }
71        let tokens: Vec<String> = preprocess(self.profile.as_ref(), text)
72            .into_iter()
73            .map(|t| t.value)
74            .collect();
75        if self.cache.len() > 2_000_000 {
76            self.cache.clear();
77        }
78        self.cache.insert(text.to_string(), tokens.clone());
79        tokens
80    }
81
82    /// Index one document. Returns `false` when it is rejected.
83    pub fn add_document(&mut self, mut doc: Document) -> Result<bool, GeocoderError> {
84        let profile = Arc::clone(&self.profile);
85        if profile
86            .fields()
87            .iter()
88            .any(|f| f.required && !doc.get(f.key).is_some_and(truthy))
89        {
90            self.skipped += 1;
91            return Ok(false);
92        }
93        let (Some(lat), Some(lon)) = (first_f64(&doc, "lat"), first_f64(&doc, "lon")) else {
94            self.skipped += 1;
95            return Ok(false);
96        };
97        let doc_id = self.documents() as DocId;
98
99        // prepare_housenumbers: key them the way queries will read them.
100        let mut housenumber_cells = Vec::new();
101        if let Some(Value::Object(housenumbers)) = doc.remove("housenumbers") {
102            let mut prepared = serde_json::Map::new();
103            for (number, data) in housenumbers {
104                let key = self.preprocess(&number).concat();
105                let mut data = match data {
106                    Value::Object(o) => o,
107                    _ => continue,
108                };
109                if let (Some(lat), Some(lon)) = (first_f64(&data, "lat"), first_f64(&data, "lon")) {
110                    housenumber_cells.push(encode_geohash(lat, lon)?);
111                }
112                data.insert("raw".into(), Value::String(number));
113                prepared.insert(key, Value::Object(data));
114            }
115            doc.insert("housenumbers".into(), Value::Object(prepared));
116        }
117        let has_housenumbers = doc.get("housenumbers").is_some_and(truthy);
118
119        let tokens = self.field_tokens(&doc);
120        let ids: Vec<TokenId> = tokens.iter().map(|(t, _)| self.token_id(t)).collect();
121        for (&id, (_, boost)) in ids.iter().zip(&tokens) {
122            self.postings[id as usize].push((doc_id, *boost as f32));
123        }
124        // PairsIndexer.
125        for &id in &ids {
126            let pairs = &mut self.pairs[id as usize];
127            for &other in &ids {
128                if other != id {
129                    pairs.insert(other);
130                }
131            }
132        }
133
134        // FiltersIndexer.
135        for &name in profile.filters() {
136            let Some(values) = doc.get(name).filter(|v| truthy(v)) else {
137                continue;
138            };
139            let values: Vec<String> = match values {
140                Value::Array(a) => a.iter().map(py_str).collect(),
141                v => vec![py_str(v)],
142            };
143            for value in values {
144                self.filters
145                    .entry(format!("{name}|{value}"))
146                    .or_default()
147                    .insert(doc_id);
148            }
149        }
150        if has_housenumbers && profile.filters().contains(&"type") {
151            self.filters
152                .entry("type|housenumber".into())
153                .or_default()
154                .insert(doc_id);
155        }
156
157        // HousenumbersIndexer and GeohashIndexer.
158        housenumber_cells.push(encode_geohash(lat, lon)?);
159        for cell in housenumber_cells {
160            self.geohashes.entry(cell).or_default().insert(doc_id);
161        }
162
163        let mut encoder = ZlibEncoder::new(Vec::new(), Compression::fast());
164        serde_json::to_writer(&mut encoder, &doc)?;
165        self.doc_blobs.extend_from_slice(&encoder.finish()?);
166        self.doc_offsets.push(self.doc_blobs.len() as u64);
167        Ok(true)
168    }
169
170    /// `FieldsIndexer`: the document's tokens with their boost, each token
171    /// keeping its best boost across fields.
172    pub fn field_tokens(&mut self, doc: &Document) -> Vec<(String, f64)> {
173        let profile = Arc::clone(&self.profile);
174        let importance = first_f64(doc, "importance").unwrap_or(0.0) * IMPORTANCE_WEIGHT;
175        let mut tokens: Vec<(String, f64)> = Vec::new();
176        for field in profile.fields() {
177            let Some(values) = doc.get(field.key).filter(|v| truthy(v)) else {
178                continue;
179            };
180            let boost = field.boost.value(doc) + importance;
181            let values: Vec<String> = match values {
182                Value::Array(a) => a.iter().map(py_str).collect(),
183                v => vec![py_str(v)],
184            };
185            for value in values {
186                let els = self.preprocess(&value);
187                if els.is_empty() {
188                    continue;
189                }
190                let token_boost = 1.0 / els.len() as f64 * boost;
191                for token in els {
192                    match tokens.iter_mut().find(|(t, _)| *t == token) {
193                        Some((_, b)) if *b < token_boost => *b = token_boost,
194                        Some(_) => {}
195                        None => tokens.push((token, token_boost)),
196                    }
197                }
198            }
199        }
200        tokens
201    }
202
203    fn token_id(&mut self, token: &str) -> TokenId {
204        if let Some(&id) = self.token_ids.get(token) {
205            return id;
206        }
207        let id = self.token_strings.len() as TokenId;
208        self.token_ids.insert(token.to_string(), id);
209        self.token_strings.push(token.to_string());
210        self.postings.push(Vec::new());
211        self.pairs.push(RoaringBitmap::new());
212        id
213    }
214
215    /// Write the index to `path`.
216    pub fn build(self, path: &Path) -> Result<(), GeocoderError> {
217        let meta = Meta {
218            profile: self.profile.name().to_string(),
219            profile_version: self.profile.version(),
220            documents: self.documents() as u32,
221            tokens: self.token_strings.len() as u32,
222        };
223
224        let token_fst = {
225            let mut sorted: Vec<(&str, u64)> = self
226                .token_strings
227                .iter()
228                .enumerate()
229                .map(|(i, t)| (t.as_str(), i as u64))
230                .collect();
231            sorted.sort_unstable_by(|a, b| a.0.cmp(b.0));
232            build_fst(sorted)?
233        };
234
235        // Postings: by doc as indexed, and ordered like ZREVRANGE.
236        let mut posting_offsets = Vec::with_capacity((self.postings.len() + 1) * 8);
237        let mut by_doc = Vec::new();
238        let mut by_score = Vec::new();
239        let mut entries = 0u64;
240        posting_offsets.write_u64::<LittleEndian>(0)?;
241        for list in &self.postings {
242            for &(doc, boost) in list {
243                by_doc.write_u32::<LittleEndian>(doc)?;
244                by_doc.write_f32::<LittleEndian>(boost)?;
245            }
246            let mut ordered = list.clone();
247            ordered.sort_unstable_by(|a, b| rank(a.1 as f64, a.0, b.1 as f64, b.0));
248            for (doc, _) in ordered {
249                by_score.write_u32::<LittleEndian>(doc)?;
250            }
251            entries += list.len() as u64;
252            posting_offsets.write_u64::<LittleEndian>(entries)?;
253        }
254
255        let (pair_offsets, pair_blobs) = bitmap_table(self.pairs.iter())?;
256
257        // Edge ngrams of every token, numbers included: the Géoplateforme
258        // imports through stdin (`addok batch < file`), which keeps
259        // `EdgeNgramIndexer` on; `addok ngrams` then only adds the non
260        // numeric ones again. So "268" completes to the postcode "26800".
261        let mut ngrams: HashMap<String, RoaringBitmap> = HashMap::new();
262        for (id, token) in self.token_strings.iter().enumerate() {
263            for ngram in edge_ngrams(token, MIN_EDGE_NGRAMS, MAX_EDGE_NGRAMS) {
264                ngrams.entry(ngram).or_default().insert(id as u32);
265            }
266        }
267        let (ngram_fst, ngram_offsets, ngram_blobs) = keyed_bitmaps(ngrams)?;
268        let (geohash_fst, geohash_offsets, geohash_blobs) = keyed_bitmaps(self.geohashes)?;
269        let (filter_fst, filter_offsets, filter_blobs) = keyed_bitmaps(self.filters)?;
270
271        let mut doc_offsets = Vec::with_capacity(self.doc_offsets.len() * 8);
272        for offset in &self.doc_offsets {
273            doc_offsets.write_u64::<LittleEndian>(*offset)?;
274        }
275
276        let meta_bytes = serde_json::to_vec(&meta)?;
277        let sections: Vec<(SectionKind, &[u8])> = vec![
278            (SectionKind::Meta, &meta_bytes),
279            (SectionKind::TokenFst, &token_fst),
280            (SectionKind::PostingOffsets, &posting_offsets),
281            (SectionKind::PostingsByDoc, &by_doc),
282            (SectionKind::PostingsByScore, &by_score),
283            (SectionKind::PairOffsets, &pair_offsets),
284            (SectionKind::PairBlobs, &pair_blobs),
285            (SectionKind::NgramFst, &ngram_fst),
286            (SectionKind::NgramOffsets, &ngram_offsets),
287            (SectionKind::NgramBlobs, &ngram_blobs),
288            (SectionKind::GeohashFst, &geohash_fst),
289            (SectionKind::GeohashOffsets, &geohash_offsets),
290            (SectionKind::GeohashBlobs, &geohash_blobs),
291            (SectionKind::FilterFst, &filter_fst),
292            (SectionKind::FilterOffsets, &filter_offsets),
293            (SectionKind::FilterBlobs, &filter_blobs),
294            (SectionKind::DocOffsets, &doc_offsets),
295            (SectionKind::DocBlobs, &self.doc_blobs),
296        ];
297        write_sections(path, &sections)
298    }
299}
300
301/// Redis ordering of a sorted set read with `ZREVRANGE`: score descending,
302/// then member descending. Members are `d|<import order>`, compared as text.
303pub(crate) fn rank(score_a: f64, doc_a: DocId, score_b: f64, doc_b: DocId) -> Ordering {
304    score_b
305        .partial_cmp(&score_a)
306        .unwrap_or(Ordering::Equal)
307        .then_with(|| tie_break(doc_b).cmp(&tie_break(doc_a)))
308}
309
310fn encode_geohash(lat: f64, lon: f64) -> Result<String, GeocoderError> {
311    Ok(geohash::encode(
312        geohash::Coord { x: lon, y: lat },
313        GEOHASH_PRECISION,
314    )?)
315}
316
317fn build_fst(sorted: Vec<(&str, u64)>) -> Result<Vec<u8>, GeocoderError> {
318    let mut builder = MapBuilder::memory();
319    for (key, value) in sorted {
320        builder.insert(key, value)?;
321    }
322    Ok(builder.into_inner()?)
323}
324
325fn bitmap_table<'a>(
326    bitmaps: impl Iterator<Item = &'a RoaringBitmap>,
327) -> Result<(Vec<u8>, Vec<u8>), GeocoderError> {
328    let mut offsets = Vec::new();
329    let mut blobs = Vec::new();
330    offsets.write_u64::<LittleEndian>(0)?;
331    for bitmap in bitmaps {
332        bitmap.serialize_into(&mut blobs)?;
333        offsets.write_u64::<LittleEndian>(blobs.len() as u64)?;
334    }
335    Ok((offsets, blobs))
336}
337
338/// FST, offsets and bitmaps sections of a keyed bitmap table.
339type KeyedSections = (Vec<u8>, Vec<u8>, Vec<u8>);
340
341fn keyed_bitmaps(map: HashMap<String, RoaringBitmap>) -> Result<KeyedSections, GeocoderError> {
342    let mut entries: Vec<(String, RoaringBitmap)> = map.into_iter().collect();
343    entries.sort_unstable_by(|a, b| a.0.cmp(&b.0));
344    let fst = build_fst(
345        entries
346            .iter()
347            .enumerate()
348            .map(|(i, (k, _))| (k.as_str(), i as u64))
349            .collect(),
350    )?;
351    let (offsets, blobs) = bitmap_table(entries.iter().map(|(_, b)| b))?;
352    Ok((fst, offsets, blobs))
353}
354
355fn write_sections(path: &Path, sections: &[(SectionKind, &[u8])]) -> Result<(), GeocoderError> {
356    let mut w = BufWriter::new(std::fs::File::create(path)?);
357    w.write_all(MAGIC)?;
358    w.write_u32::<LittleEndian>(VERSION)?;
359    w.write_u32::<LittleEndian>(sections.len() as u32)?;
360
361    let headers_end = (16 + sections.len() * SECTION_HEADER_SIZE) as u64;
362    let mut offset = align8(headers_end);
363    let mut headers = Vec::with_capacity(sections.len());
364    for (kind, data) in sections {
365        headers.push(SectionHeader {
366            kind: *kind,
367            offset,
368            length: data.len() as u64,
369        });
370        offset = align8(offset + data.len() as u64);
371    }
372    for h in &headers {
373        w.write_u8(h.kind as u8)?;
374        w.write_u64::<LittleEndian>(h.offset)?;
375        w.write_u64::<LittleEndian>(h.length)?;
376    }
377    let mut position = headers_end;
378    for (h, (_, data)) in headers.iter().zip(sections) {
379        w.write_all(&vec![0u8; (h.offset - position) as usize])?;
380        w.write_all(data)?;
381        position = h.offset + data.len() as u64;
382    }
383    w.flush()?;
384    Ok(())
385}
386
387fn align8(offset: u64) -> u64 {
388    (offset + 7) & !7
389}