1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
use crate::query::QueryTrait;
use serde_json::{json, Value};

#[derive(Default)]
pub struct GeoDistanceQuery {
    field: String,
    geo: Geo,
    distance: String,
}

#[derive(Default)]
pub struct Geo {
    pub lat: f64,
    pub lon: f64,
}

impl Geo {
    pub fn new(lat: f64, lon: f64) -> Geo {
        Geo { lat, lon }
    }
}

impl GeoDistanceQuery {
    pub fn new(field: &str, geo: Geo, distance: &str) -> GeoDistanceQuery {
        let mut value = GeoDistanceQuery::default();
        value.field = field.to_string();
        value.distance = distance.to_string();
        value.geo = geo;
        return value;
    }
}

impl QueryTrait for GeoDistanceQuery {
    fn build(&self) -> Value {
        let name = self.query_name();
        let field = self.field.to_string();
        let distance = self.distance.to_string();
        let lat = self.geo.lat.to_string();
        let lon = self.geo.lon.to_string();
        json!({
            name: {
                "distance":distance,
                field:{
                        "lat" : lat,
                        "lon" : lon,
                    }
            }
        })
    }

    fn query_name(&self) -> String {
        return "geo_distance".to_string();
    }
}

#[cfg(test)]
mod tests {
    use crate::query::geo_distance_query::{Geo, GeoDistanceQuery};
    use crate::query::QueryTrait;

    #[test]
    fn build() {
        assert_eq!(
            GeoDistanceQuery::new("id", Geo::new(35.68944, 139.69167), "10km").build().to_string(),
            "{\"geo_distance\":{\"distance\":\"10km\",\"id\":{\"lat\":\"35.68944\",\"lon\":\"139.69167\"}}}"
        );
    }
}