elastic_query_builder/query/
geo_distance_query.rs

1use crate::query::QueryTrait;
2use serde_json::{json, Value};
3
4#[derive(Default)]
5pub struct GeoDistanceQuery {
6    field: String,
7    geo: Geo,
8    distance: String,
9}
10
11#[derive(Default)]
12pub struct Geo {
13    pub lat: f64,
14    pub lon: f64,
15}
16
17impl Geo {
18    pub fn new(lat: f64, lon: f64) -> Geo {
19        Geo { lat, lon }
20    }
21}
22
23impl GeoDistanceQuery {
24    pub fn new(field: &str, geo: Geo, distance: &str) -> GeoDistanceQuery {
25        let mut value = GeoDistanceQuery::default();
26        value.field = field.to_string();
27        value.distance = distance.to_string();
28        value.geo = geo;
29        return value;
30    }
31}
32
33impl QueryTrait for GeoDistanceQuery {
34    fn build(&self) -> Value {
35        let name = self.query_name();
36        let field = self.field.to_string();
37        let distance = self.distance.to_string();
38        let lat = self.geo.lat.to_string();
39        let lon = self.geo.lon.to_string();
40        json!({
41            name: {
42                "distance":distance,
43                field:{
44                        "lat" : lat,
45                        "lon" : lon,
46                    }
47            }
48        })
49    }
50
51    fn query_name(&self) -> String {
52        return "geo_distance".to_string();
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use crate::query::geo_distance_query::{Geo, GeoDistanceQuery};
59    use crate::query::QueryTrait;
60
61    #[test]
62    fn build() {
63        assert_eq!(
64            GeoDistanceQuery::new("id", Geo::new(35.68944, 139.69167), "10km").build().to_string(),
65            "{\"geo_distance\":{\"distance\":\"10km\",\"id\":{\"lat\":\"35.68944\",\"lon\":\"139.69167\"}}}"
66        );
67    }
68}