geolith-search-builder 0.3.2

Builds geocoding indexes from Overture Maps and OpenStreetMap: Postgres COPY files, Photon and Pelias bulk files, and the search part of a .glx file
Documentation
//! Overture buildings Elasticsearch bulk serializer.
//!
//! Buildings use a separate index with a flat Overture-schema document —
//! NOT the Pelias document model. `_id` is the raw lowercased building ID,
//! `centroid` is `{lat, lon}`, `geometry` is `GeoJSON` stored as ES
//! `geo_shape`, and `bbox_shape` is an envelope.
//!
//! # Format
//!
//! ```json
//! {"index":{"_index":"overture-buildings","_id":"08b2a1..."}}
//! {"id":"08b2a1...","source":"overture","theme":"buildings","type":"building",...}
//! ```

use std::io::Write;

use geo::Centroid;
use serde_json::{Map, Value, json};

use geolith::source::input::InputFeature;
use geolith::source::reader::SOURCE_ID_PROP;
use geolith::tile::feature::PropValue;

/// Elasticsearch bulk writer for Overture building documents.
pub struct OvertureBuildingsWriter<W: Write> {
    writer: W,
    index_name: String,
    count: u64,
}

impl<W: Write> OvertureBuildingsWriter<W> {
    /// Create a new buildings bulk writer targeting `index_name`.
    pub fn new(writer: W, index_name: impl Into<String>) -> Self {
        Self {
            writer,
            index_name: index_name.into(),
            count: 0,
        }
    }

    /// Write a single Overture building feature as a bulk action + document pair.
    ///
    /// Features without a resolvable ID or centroid are skipped (returns
    /// `Ok(false)`).
    ///
    /// # Errors
    ///
    /// The writer's [`std::io::Error`] when the action or the document line
    /// cannot be written.
    pub fn write_feature(&mut self, feature: &InputFeature) -> std::io::Result<bool> {
        let Some(doc) = building_to_doc(feature) else {
            return Ok(false);
        };
        let id = doc["id"].as_str().unwrap_or_default().to_string();
        let action = json!({"index": {"_index": self.index_name, "_id": id}});
        writeln!(self.writer, "{action}")?;
        writeln!(self.writer, "{doc}")?;
        self.count += 1;
        Ok(true)
    }

    /// Return the number of documents written.
    #[must_use]
    pub const fn count(&self) -> u64 {
        self.count
    }

    /// Flush the underlying writer.
    ///
    /// # Errors
    ///
    /// The writer's [`std::io::Error`] when the flush fails.
    pub fn flush(&mut self) -> std::io::Result<()> {
        self.writer.flush()
    }
}

/// Convert an Overture building feature to a flat ES document.
///
/// Returns `None` when the feature lacks an ID or a computable centroid.
#[must_use]
pub fn building_to_doc(feature: &InputFeature) -> Option<Value> {
    let id = match feature.properties.get(SOURCE_ID_PROP) {
        Some(PropValue::Str(s)) if !s.is_empty() => s.to_lowercase(),
        _ => feature.id.to_string(),
    };
    let centroid = match feature.geometry.as_ref() {
        geo::Geometry::Point(p) => Some((p.x(), p.y())),
        other => other.centroid().map(|c| (c.x(), c.y())),
    };
    let (lon, lat) = centroid?;

    let mut doc = Map::new();
    doc.insert("id".to_string(), json!(id));
    doc.insert("source".to_string(), json!("overture"));
    doc.insert("theme".to_string(), json!("buildings"));
    doc.insert("type".to_string(), json!("building"));
    doc.insert("centroid".to_string(), json!({"lat": lat, "lon": lon}));

    if let Some(name) = prop_str(feature, "names.primary") {
        doc.insert(
            "name".to_string(),
            json!({"primary": name, "default": name}),
        );
        doc.insert("names".to_string(), json!({"primary": name}));
    }
    for key in ["class", "subtype", "facade_material", "roof_shape"] {
        if let Some(v) = prop_str(feature, key) {
            doc.insert(key.to_string(), json!(v));
        }
    }
    for key in ["height", "min_height", "roof_height"] {
        if let Some(v) = prop_f64(feature, key) {
            doc.insert(key.to_string(), json!(v));
        }
    }
    for key in ["num_floors", "num_floors_underground", "level", "version"] {
        if let Some(v) = prop_i64(feature, key) {
            doc.insert(key.to_string(), json!(v));
        }
    }
    if let Some(PropValue::Bool(b)) = feature.properties.get("is_underground") {
        doc.insert("is_underground".to_string(), json!(b));
    }

    if let Some([xmin, ymin, xmax, ymax]) = feature.bbox {
        doc.insert(
            "bbox".to_string(),
            json!({"xmin": xmin, "xmax": xmax, "ymin": ymin, "ymax": ymax}),
        );
        doc.insert(
            "bbox_shape".to_string(),
            json!({"type": "envelope", "coordinates": [[xmin, ymax], [xmax, ymin]]}),
        );
    }

    let geojson_value = geojson::GeometryValue::from(feature.geometry.as_ref());
    doc.insert(
        "geometry".to_string(),
        serde_json::to_value(&geojson_value).ok()?,
    );

    Some(Value::Object(doc))
}

fn prop_str<'a>(feature: &'a InputFeature, key: &str) -> Option<&'a str> {
    match feature.properties.get(key) {
        Some(PropValue::Str(s)) if !s.is_empty() => Some(s),
        _ => None,
    }
}

fn prop_f64(feature: &InputFeature, key: &str) -> Option<f64> {
    match feature.properties.get(key) {
        Some(PropValue::F64(v)) => Some(*v),
        Some(PropValue::I64(v)) => Some(*v as f64),
        _ => None,
    }
}

fn prop_i64(feature: &InputFeature, key: &str) -> Option<i64> {
    match feature.properties.get(key) {
        Some(PropValue::I64(v)) => Some(*v),
        Some(PropValue::F64(v)) if v.fract() == 0.0 => Some(*v as i64),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use geolith::source::input::DataSource;
    use std::sync::Arc;

    fn building_feature(props: &[(&str, PropValue)]) -> InputFeature {
        let square = geo::Polygon::new(
            geo::LineString::from(vec![
                (0.0, 0.0),
                (1.0, 0.0),
                (1.0, 1.0),
                (0.0, 1.0),
                (0.0, 0.0),
            ]),
            vec![],
        );
        InputFeature {
            id: 99,
            geometry: Arc::new(geo::Geometry::Polygon(square)),
            properties: props
                .iter()
                .map(|(k, v)| (k.to_string(), v.clone()))
                .collect(),
            bbox: Some([0.0, 0.0, 1.0, 1.0]),
            source: DataSource::Overture {
                theme: "buildings".to_string(),
                otype: "building".to_string(),
            },
        }
    }

    #[test]
    fn building_doc_core_fields() {
        let feature = building_feature(&[
            (
                SOURCE_ID_PROP,
                PropValue::Str("08B2A100D388CFFF".to_string()),
            ),
            ("class", PropValue::Str("residential".to_string())),
            ("height", PropValue::F64(12.5)),
            ("num_floors", PropValue::I64(4)),
        ]);
        let doc = building_to_doc(&feature).expect("doc");
        assert_eq!(doc["id"], "08b2a100d388cfff", "id must be lowercased");
        assert_eq!(doc["source"], "overture");
        assert_eq!(doc["theme"], "buildings");
        assert_eq!(doc["type"], "building");
        assert_eq!(doc["class"], "residential");
        assert_eq!(doc["height"], 12.5);
        assert_eq!(doc["num_floors"], 4);
    }

    #[test]
    fn building_doc_centroid_is_lat_lon_object() {
        let feature = building_feature(&[]);
        let doc = building_to_doc(&feature).expect("doc");
        assert!((doc["centroid"]["lat"].as_f64().expect("lat") - 0.5).abs() < 1e-9);
        assert!((doc["centroid"]["lon"].as_f64().expect("lon") - 0.5).abs() < 1e-9);
    }

    #[test]
    fn building_doc_bbox_and_envelope() {
        let feature = building_feature(&[]);
        let doc = building_to_doc(&feature).expect("doc");
        assert_eq!(doc["bbox"]["xmin"], 0.0);
        assert_eq!(doc["bbox"]["ymax"], 1.0);
        assert_eq!(doc["bbox_shape"]["type"], "envelope");
        assert_eq!(
            doc["bbox_shape"]["coordinates"],
            json!([[0.0, 1.0], [1.0, 0.0]])
        );
    }

    #[test]
    fn building_doc_geometry_is_geojson_polygon() {
        let feature = building_feature(&[]);
        let doc = building_to_doc(&feature).expect("doc");
        assert_eq!(doc["geometry"]["type"], "Polygon");
        assert!(doc["geometry"]["coordinates"].is_array());
    }

    #[test]
    fn building_doc_falls_back_to_numeric_id() {
        let feature = building_feature(&[]);
        let doc = building_to_doc(&feature).expect("doc");
        assert_eq!(doc["id"], "99");
    }

    #[test]
    fn building_doc_includes_name_when_present() {
        let feature = building_feature(&[(
            "names.primary",
            PropValue::Str("Empire State Building".to_string()),
        )]);
        let doc = building_to_doc(&feature).expect("doc");
        assert_eq!(doc["name"]["primary"], "Empire State Building");
        assert_eq!(doc["name"]["default"], "Empire State Building");
        assert_eq!(doc["names"]["primary"], "Empire State Building");
    }

    #[test]
    fn building_doc_omits_absent_fields() {
        let feature = building_feature(&[]);
        let doc = building_to_doc(&feature).expect("doc");
        assert!(doc.get("class").is_none());
        assert!(doc.get("height").is_none());
        assert!(doc.get("name").is_none());
        assert!(doc.get("is_underground").is_none());
    }

    #[test]
    fn writer_outputs_action_doc_pairs() {
        let mut buf = Vec::new();
        let mut writer = OvertureBuildingsWriter::new(&mut buf, "overture-buildings");
        let feature = building_feature(&[(SOURCE_ID_PROP, PropValue::Str("abc".to_string()))]);
        assert!(writer.write_feature(&feature).expect("write"));
        assert_eq!(writer.count(), 1);
        let output = String::from_utf8(buf).expect("utf8");
        let lines: Vec<&str> = output.lines().collect();
        assert_eq!(lines.len(), 2);
        let action: Value = serde_json::from_str(lines[0]).expect("json");
        assert_eq!(action["index"]["_index"], "overture-buildings");
        assert_eq!(action["index"]["_id"], "abc");
        let doc: Value = serde_json::from_str(lines[1]).expect("json");
        assert_eq!(doc["theme"], "buildings");
    }

    #[test]
    fn building_doc_numeric_conversions_and_extra_fields() {
        let feature = building_feature(&[
            ("subtype", PropValue::Str("commercial".to_string())),
            ("facade_material", PropValue::Str("glass".to_string())),
            ("roof_shape", PropValue::Str("flat".to_string())),
            ("min_height", PropValue::I64(2)),
            ("roof_height", PropValue::F64(1.5)),
            ("num_floors_underground", PropValue::F64(1.0)),
            ("level", PropValue::I64(0)),
            ("version", PropValue::I64(2)),
            ("is_underground", PropValue::Bool(false)),
        ]);
        let doc = building_to_doc(&feature).expect("doc");
        assert_eq!(doc["subtype"], "commercial");
        assert_eq!(doc["facade_material"], "glass");
        assert_eq!(doc["roof_shape"], "flat");
        assert_eq!(doc["min_height"], 2.0, "I64 promoted to f64");
        assert_eq!(doc["roof_height"], 1.5);
        assert_eq!(doc["num_floors_underground"], 1, "whole F64 demoted to i64");
        assert_eq!(doc["level"], 0);
        assert_eq!(doc["version"], 2);
        assert_eq!(doc["is_underground"], false);
    }

    #[test]
    fn building_doc_skips_fractional_f64_for_int_fields() {
        let feature = building_feature(&[("num_floors", PropValue::F64(3.7))]);
        let doc = building_to_doc(&feature).expect("doc");
        assert!(
            doc.get("num_floors").is_none(),
            "fractional float must not become an int field"
        );
    }

    #[test]
    fn building_doc_none_for_point_without_bbox() {
        let feature = InputFeature {
            id: 1,
            geometry: Arc::new(geo::Geometry::Point(geo::Point::new(3.0, 4.0))),
            properties: std::collections::HashMap::new(),
            bbox: None,
            source: DataSource::Overture {
                theme: "buildings".to_string(),
                otype: "building".to_string(),
            },
        };
        let doc = building_to_doc(&feature).expect("point still has centroid");
        assert_eq!(doc["centroid"]["lon"], 3.0);
        assert!(doc.get("bbox").is_none());
        assert!(doc.get("bbox_shape").is_none());
    }

    #[test]
    fn writer_skips_feature_without_centroid() {
        let empty_multi = geo::MultiPolygon::<f64>(vec![]);
        let feature = InputFeature {
            id: 2,
            geometry: Arc::new(geo::Geometry::MultiPolygon(empty_multi)),
            properties: std::collections::HashMap::new(),
            bbox: None,
            source: DataSource::Overture {
                theme: "buildings".to_string(),
                otype: "building".to_string(),
            },
        };
        let mut buf = Vec::new();
        let mut writer = OvertureBuildingsWriter::new(&mut buf, "b");
        assert!(!writer.write_feature(&feature).expect("write"));
        assert_eq!(writer.count(), 0);
        assert!(buf.is_empty());
    }

    #[test]
    fn writer_flush_succeeds() {
        let mut probe = FlushProbe::default();
        let mut writer = OvertureBuildingsWriter::new(&mut probe, "b");
        let feature = building_feature(&[(SOURCE_ID_PROP, PropValue::Str("abc".to_string()))]);
        writer.write_feature(&feature).expect("write");
        writer.flush().expect("flush");
        assert!(probe.flushed, "flush reaches the underlying writer");
    }

    /// A sink that only records whether `flush` reached it.
    #[derive(Default)]
    struct FlushProbe {
        flushed: bool,
    }

    impl std::io::Write for FlushProbe {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            Ok(buf.len())
        }
        fn flush(&mut self) -> std::io::Result<()> {
            self.flushed = true;
            Ok(())
        }
    }
}