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::postal::CedexTable;
19use crate::profile::{Profile, preprocess};
20use crate::settings::{GEOHASH_PRECISION, IMPORTANCE_WEIGHT, MAX_EDGE_NGRAMS, MIN_EDGE_NGRAMS};
21use crate::text::edge_ngrams;
22use crate::types::{DocId, TokenId};
23
24pub struct IndexBuilder {
28 profile: Arc<dyn Profile>,
29 token_ids: HashMap<String, TokenId>,
30 token_strings: Vec<String>,
31 postings: Vec<Vec<(DocId, f32)>>,
32 pairs: Vec<RoaringBitmap>,
33 geohashes: HashMap<String, RoaringBitmap>,
34 filters: HashMap<String, RoaringBitmap>,
35 doc_offsets: Vec<u64>,
36 doc_blobs: Vec<u8>,
37 cache: HashMap<String, Vec<String>>,
39 skipped: usize,
40 cedex: Option<CedexTable>,
41}
42
43impl IndexBuilder {
44 pub fn new(profile: Arc<dyn Profile>) -> Self {
45 Self {
46 profile,
47 token_ids: HashMap::new(),
48 token_strings: Vec::new(),
49 postings: Vec::new(),
50 pairs: Vec::new(),
51 geohashes: HashMap::new(),
52 filters: HashMap::new(),
53 doc_offsets: vec![0],
54 doc_blobs: Vec::new(),
55 cache: HashMap::new(),
56 skipped: 0,
57 cedex: None,
58 }
59 }
60
61 pub fn set_cedex(&mut self, table: CedexTable) {
63 self.cedex = Some(table);
64 }
65
66 pub fn documents(&self) -> usize {
67 self.doc_offsets.len() - 1
68 }
69
70 pub fn skipped(&self) -> usize {
72 self.skipped
73 }
74
75 fn preprocess(&mut self, text: &str) -> Vec<String> {
76 if let Some(hit) = self.cache.get(text) {
77 return hit.clone();
78 }
79 let tokens: Vec<String> = preprocess(self.profile.as_ref(), text)
80 .into_iter()
81 .map(|t| t.value)
82 .collect();
83 if self.cache.len() > 2_000_000 {
84 self.cache.clear();
85 }
86 self.cache.insert(text.to_string(), tokens.clone());
87 tokens
88 }
89
90 pub fn add_document(&mut self, mut doc: Document) -> Result<bool, GeocoderError> {
92 let profile = Arc::clone(&self.profile);
93 if profile
94 .fields()
95 .iter()
96 .any(|f| f.required && !doc.get(f.key).is_some_and(truthy))
97 {
98 self.skipped += 1;
99 return Ok(false);
100 }
101 let (Some(lat), Some(lon)) = (first_f64(&doc, "lat"), first_f64(&doc, "lon")) else {
102 self.skipped += 1;
103 return Ok(false);
104 };
105 let doc_id = self.documents() as DocId;
106
107 let mut housenumber_cells = Vec::new();
109 if let Some(Value::Object(housenumbers)) = doc.remove("housenumbers") {
110 let mut prepared = serde_json::Map::new();
111 for (number, data) in housenumbers {
112 let key = self.preprocess(&number).concat();
113 let mut data = match data {
114 Value::Object(o) => o,
115 _ => continue,
116 };
117 if let (Some(lat), Some(lon)) = (first_f64(&data, "lat"), first_f64(&data, "lon")) {
118 housenumber_cells.push(encode_geohash(lat, lon)?);
119 }
120 data.insert("raw".into(), Value::String(number));
121 prepared.insert(key, Value::Object(data));
122 }
123 doc.insert("housenumbers".into(), Value::Object(prepared));
124 }
125 let has_housenumbers = doc.get("housenumbers").is_some_and(truthy);
126
127 let tokens = self.field_tokens(&doc);
128 let ids: Vec<TokenId> = tokens.iter().map(|(t, _)| self.token_id(t)).collect();
129 for (&id, (_, boost)) in ids.iter().zip(&tokens) {
130 self.postings[id as usize].push((doc_id, *boost as f32));
131 }
132 for &id in &ids {
134 let pairs = &mut self.pairs[id as usize];
135 for &other in &ids {
136 if other != id {
137 pairs.insert(other);
138 }
139 }
140 }
141
142 for &name in profile.filters() {
144 let Some(values) = doc.get(name).filter(|v| truthy(v)) else {
145 continue;
146 };
147 let values: Vec<String> = match values {
148 Value::Array(a) => a.iter().map(py_str).collect(),
149 v => vec![py_str(v)],
150 };
151 for value in values {
152 self.filters
153 .entry(format!("{name}|{value}"))
154 .or_default()
155 .insert(doc_id);
156 }
157 }
158 if has_housenumbers && profile.filters().contains(&"type") {
159 self.filters
160 .entry("type|housenumber".into())
161 .or_default()
162 .insert(doc_id);
163 }
164
165 housenumber_cells.push(encode_geohash(lat, lon)?);
167 for cell in housenumber_cells {
168 self.geohashes.entry(cell).or_default().insert(doc_id);
169 }
170
171 let mut encoder = ZlibEncoder::new(Vec::new(), Compression::fast());
172 serde_json::to_writer(&mut encoder, &doc)?;
173 self.doc_blobs.extend_from_slice(&encoder.finish()?);
174 self.doc_offsets.push(self.doc_blobs.len() as u64);
175 Ok(true)
176 }
177
178 pub fn field_tokens(&mut self, doc: &Document) -> Vec<(String, f64)> {
181 let profile = Arc::clone(&self.profile);
182 let importance = first_f64(doc, "importance").unwrap_or(0.0) * IMPORTANCE_WEIGHT;
183 let mut tokens: Vec<(String, f64)> = Vec::new();
184 for field in profile.fields() {
185 let Some(values) = doc.get(field.key).filter(|v| truthy(v)) else {
186 continue;
187 };
188 let boost = field.boost.value(doc) + importance;
189 let values: Vec<String> = match values {
190 Value::Array(a) => a.iter().map(py_str).collect(),
191 v => vec![py_str(v)],
192 };
193 for value in values {
194 let els = self.preprocess(&value);
195 if els.is_empty() {
196 continue;
197 }
198 let token_boost = 1.0 / els.len() as f64 * boost;
199 for token in els {
200 match tokens.iter_mut().find(|(t, _)| *t == token) {
201 Some((_, b)) if *b < token_boost => *b = token_boost,
202 Some(_) => {}
203 None => tokens.push((token, token_boost)),
204 }
205 }
206 }
207 }
208 tokens
209 }
210
211 fn token_id(&mut self, token: &str) -> TokenId {
212 if let Some(&id) = self.token_ids.get(token) {
213 return id;
214 }
215 let id = self.token_strings.len() as TokenId;
216 self.token_ids.insert(token.to_string(), id);
217 self.token_strings.push(token.to_string());
218 self.postings.push(Vec::new());
219 self.pairs.push(RoaringBitmap::new());
220 id
221 }
222
223 pub fn build(self, path: &Path) -> Result<(), GeocoderError> {
225 let meta = Meta {
226 profile: self.profile.name().to_string(),
227 profile_version: self.profile.version(),
228 documents: self.documents() as u32,
229 tokens: self.token_strings.len() as u32,
230 };
231
232 let token_fst = {
233 let mut sorted: Vec<(&str, u64)> = self
234 .token_strings
235 .iter()
236 .enumerate()
237 .map(|(i, t)| (t.as_str(), i as u64))
238 .collect();
239 sorted.sort_unstable_by(|a, b| a.0.cmp(b.0));
240 build_fst(sorted)?
241 };
242
243 let mut posting_offsets = Vec::with_capacity((self.postings.len() + 1) * 8);
245 let mut by_doc = Vec::new();
246 let mut by_score = Vec::new();
247 let mut entries = 0u64;
248 posting_offsets.write_u64::<LittleEndian>(0)?;
249 for list in &self.postings {
250 for &(doc, boost) in list {
251 by_doc.write_u32::<LittleEndian>(doc)?;
252 by_doc.write_f32::<LittleEndian>(boost)?;
253 }
254 let mut ordered = list.clone();
255 ordered.sort_unstable_by(|a, b| rank(a.1 as f64, a.0, b.1 as f64, b.0));
256 for (doc, _) in ordered {
257 by_score.write_u32::<LittleEndian>(doc)?;
258 }
259 entries += list.len() as u64;
260 posting_offsets.write_u64::<LittleEndian>(entries)?;
261 }
262
263 let (pair_offsets, pair_blobs) = bitmap_table(self.pairs.iter())?;
264
265 let mut ngrams: HashMap<String, RoaringBitmap> = HashMap::new();
270 for (id, token) in self.token_strings.iter().enumerate() {
271 for ngram in edge_ngrams(token, MIN_EDGE_NGRAMS, MAX_EDGE_NGRAMS) {
272 ngrams.entry(ngram).or_default().insert(id as u32);
273 }
274 }
275 let (ngram_fst, ngram_offsets, ngram_blobs) = keyed_bitmaps(ngrams)?;
276 let (geohash_fst, geohash_offsets, geohash_blobs) = keyed_bitmaps(self.geohashes)?;
277 let (filter_fst, filter_offsets, filter_blobs) = keyed_bitmaps(self.filters)?;
278
279 let mut doc_offsets = Vec::with_capacity(self.doc_offsets.len() * 8);
280 for offset in &self.doc_offsets {
281 doc_offsets.write_u64::<LittleEndian>(*offset)?;
282 }
283
284 let meta_bytes = serde_json::to_vec(&meta)?;
285 let cedex = self.cedex.as_ref().map(CedexTable::to_bytes).transpose()?;
286 let mut sections: Vec<(SectionKind, &[u8])> = vec![
287 (SectionKind::Meta, &meta_bytes),
288 (SectionKind::TokenFst, &token_fst),
289 (SectionKind::PostingOffsets, &posting_offsets),
290 (SectionKind::PostingsByDoc, &by_doc),
291 (SectionKind::PostingsByScore, &by_score),
292 (SectionKind::PairOffsets, &pair_offsets),
293 (SectionKind::PairBlobs, &pair_blobs),
294 (SectionKind::NgramFst, &ngram_fst),
295 (SectionKind::NgramOffsets, &ngram_offsets),
296 (SectionKind::NgramBlobs, &ngram_blobs),
297 (SectionKind::GeohashFst, &geohash_fst),
298 (SectionKind::GeohashOffsets, &geohash_offsets),
299 (SectionKind::GeohashBlobs, &geohash_blobs),
300 (SectionKind::FilterFst, &filter_fst),
301 (SectionKind::FilterOffsets, &filter_offsets),
302 (SectionKind::FilterBlobs, &filter_blobs),
303 (SectionKind::DocOffsets, &doc_offsets),
304 (SectionKind::DocBlobs, &self.doc_blobs),
305 ];
306 if let Some(cedex) = &cedex {
307 sections.push((SectionKind::Postal, cedex));
308 }
309 write_sections(path, §ions)
310 }
311}
312
313pub(crate) fn rank(score_a: f64, doc_a: DocId, score_b: f64, doc_b: DocId) -> Ordering {
316 score_b
317 .partial_cmp(&score_a)
318 .unwrap_or(Ordering::Equal)
319 .then_with(|| tie_break(doc_b).cmp(&tie_break(doc_a)))
320}
321
322fn encode_geohash(lat: f64, lon: f64) -> Result<String, GeocoderError> {
323 Ok(geohash::encode(
324 geohash::Coord { x: lon, y: lat },
325 GEOHASH_PRECISION,
326 )?)
327}
328
329fn build_fst(sorted: Vec<(&str, u64)>) -> Result<Vec<u8>, GeocoderError> {
330 let mut builder = MapBuilder::memory();
331 for (key, value) in sorted {
332 builder.insert(key, value)?;
333 }
334 Ok(builder.into_inner()?)
335}
336
337fn bitmap_table<'a>(
338 bitmaps: impl Iterator<Item = &'a RoaringBitmap>,
339) -> Result<(Vec<u8>, Vec<u8>), GeocoderError> {
340 let mut offsets = Vec::new();
341 let mut blobs = Vec::new();
342 offsets.write_u64::<LittleEndian>(0)?;
343 for bitmap in bitmaps {
344 bitmap.serialize_into(&mut blobs)?;
345 offsets.write_u64::<LittleEndian>(blobs.len() as u64)?;
346 }
347 Ok((offsets, blobs))
348}
349
350type KeyedSections = (Vec<u8>, Vec<u8>, Vec<u8>);
352
353fn keyed_bitmaps(map: HashMap<String, RoaringBitmap>) -> Result<KeyedSections, GeocoderError> {
354 let mut entries: Vec<(String, RoaringBitmap)> = map.into_iter().collect();
355 entries.sort_unstable_by(|a, b| a.0.cmp(&b.0));
356 let fst = build_fst(
357 entries
358 .iter()
359 .enumerate()
360 .map(|(i, (k, _))| (k.as_str(), i as u64))
361 .collect(),
362 )?;
363 let (offsets, blobs) = bitmap_table(entries.iter().map(|(_, b)| b))?;
364 Ok((fst, offsets, blobs))
365}
366
367fn write_sections(path: &Path, sections: &[(SectionKind, &[u8])]) -> Result<(), GeocoderError> {
368 let mut w = BufWriter::new(std::fs::File::create(path)?);
369 w.write_all(MAGIC)?;
370 w.write_u32::<LittleEndian>(VERSION)?;
371 w.write_u32::<LittleEndian>(sections.len() as u32)?;
372
373 let headers_end = (16 + sections.len() * SECTION_HEADER_SIZE) as u64;
374 let mut offset = align8(headers_end);
375 let mut headers = Vec::with_capacity(sections.len());
376 for (kind, data) in sections {
377 headers.push(SectionHeader {
378 kind: *kind,
379 offset,
380 length: data.len() as u64,
381 });
382 offset = align8(offset + data.len() as u64);
383 }
384 for h in &headers {
385 w.write_u8(h.kind as u8)?;
386 w.write_u64::<LittleEndian>(h.offset)?;
387 w.write_u64::<LittleEndian>(h.length)?;
388 }
389 let mut position = headers_end;
390 for (h, (_, data)) in headers.iter().zip(sections) {
391 w.write_all(&vec![0u8; (h.offset - position) as usize])?;
392 w.write_all(data)?;
393 position = h.offset + data.len() as u64;
394 }
395 w.flush()?;
396 Ok(())
397}
398
399fn align8(offset: u64) -> u64 {
400 (offset + 7) & !7
401}