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
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
use crate::search::*;
use crate::util::*;
use chrono::{DateTime, Utc};
use serde::ser::Serialize;
use std::fmt::Debug;

#[doc(hidden)]
pub trait Origin: Debug + PartialEq + Serialize + Clone {
    type Pivot: Debug + PartialEq + Serialize + Clone;
}

impl Origin for DateTime<Utc> {
    type Pivot = Time;
}

impl Origin for GeoPoint {
    type Pivot = Distance;
}

/// Boosts the [relevance score](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-filter-context.html#relevance-scores)
/// of documents closer to a provided `origin` date or point.
/// For example, you can use this query to give more weight to documents
/// closer to a certain date or location.
///
/// You can use the `distance_feature` query to find the nearest neighbors to a location.
/// You can also use the query in a [bool](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html)
/// search’s `should` filter to add boosted relevance scores to the `bool` query’s scores.
///
/// **How the `distance_feature` query calculates relevance scores**
///
/// The `distance_feature` query dynamically calculates the distance between the
/// `origin` value and a document's field values. It then uses this distance as a
/// feature to boost the
/// [relevance-scores](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-filter-context.html#relevance-scores)
/// of closer documents.
///
/// The `distance_feature` query calculates a document's
/// [relevance score](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-filter-context.html#relevance-scores)
/// as follows:
///
/// ```text
/// relevance score = boost * pivot / (pivot + distance)
/// ```
///
/// The `distance` is the absolute difference between the `origin` value and a
/// document's field value.
///
/// **Skip non-competitive hits**
///
/// Unlike the
/// [`function_score`](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html)
/// query or other ways to change
/// [relevance scores](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-filter-context.html#relevance-scores)
/// , the `distance_feature` query efficiently skips non-competitive hits when the
/// [`track_total_hits`](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-uri-request.html)
/// parameter is **not** `true`.
///
/// To create distance feature query date query:
/// ```
/// # use elasticsearch_dsl::Time;
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # use chrono::prelude::*;
/// # let query =
/// Query::distance_feature("test", Utc.ymd(2014, 7, 8).and_hms(9, 1, 0), Time::Days(7))
///     .boost(1.5)
///     .name("test");
/// ```
/// To create distance feature query geo query:
/// ```
/// # use elasticsearch_dsl::{Distance, GeoPoint};
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # let query =
/// Query::distance_feature("test", GeoPoint::coordinates(12.0, 13.0), Distance::Kilometers(15))
///     .boost(1.5)
///     .name("test");
/// ```
/// Distance Feature is built to allow only valid origin and pivot values,
/// the following won't compile:
/// ```compile_fail
/// # use elasticsearch_dsl::Distance;
/// # use chrono::prelude::*;
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # let query =
/// Query::distance_feature("test", Utc.ymd(2014, 7, 8).and_hms(9, 1, 0), Distance::Kilometers(15))
///     .boost(1.5)
///     .name("test");
/// ```
///
/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-distance-feature-query.html>
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct DistanceFeatureQuery<O: Origin> {
    #[serde(rename = "distance_feature")]
    inner: Inner<O>,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
struct Inner<O: Origin> {
    field: String,

    origin: O,

    pivot: <O as Origin>::Pivot,

    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    boost: Option<Boost>,

    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    _name: Option<String>,
}

impl Query {
    /// Creates an instance of [DistanceFeatureQuery](DistanceFeatureQuery)
    ///
    /// - `field` - Name of the field used to calculate distances. This field must meet the following criteria:<br>
    ///   - Be a [`date`](https://www.elastic.co/guide/en/elasticsearch/reference/current/date.html),
    /// [`date_nanos`](https://www.elastic.co/guide/en/elasticsearch/reference/current/date_nanos.html) or
    /// [`geo_point`](https://www.elastic.co/guide/en/elasticsearch/reference/current/geo-point.html) field
    ///   - Have an [index](https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-index.html)
    /// mapping parameter value of `true`, which is the default
    ///   - Have an [`doc_values`](https://www.elastic.co/guide/en/elasticsearch/reference/current/doc-values.html)
    /// mapping parameter value of `true`, which is the default
    /// - `origin` - Date or point of origin used to calculate distances.<br>
    /// If the `field` value is a
    /// [`date`](https://www.elastic.co/guide/en/elasticsearch/reference/current/date.html) or
    /// [`date_nanos`](https://www.elastic.co/guide/en/elasticsearch/reference/current/date_nanos.html)
    /// field, the `origin` value must be a
    /// [date](https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-bucket-daterange-aggregation.html#date-format-pattern).
    /// [Date Math](https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#date-math),
    /// such as `now-1h`, is supported.<br>
    /// If the `field` value is a
    /// [`geo_point`](https://www.elastic.co/guide/en/elasticsearch/reference/current/geo-point.html)
    /// field, the `origin` value must be a geopoint.
    /// - `pivot` - Distance from the `origin` at which relevance scores receive half of the boost value.<br>
    /// If the field value is a
    /// [`date`](https://www.elastic.co/guide/en/elasticsearch/reference/current/date.html) or
    /// [`date_nanos`](https://www.elastic.co/guide/en/elasticsearch/reference/current/date_nanos.html)
    /// field, the `pivot` value must be a
    /// [`time unit`](https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#time-units)
    /// , such as `1h` or `10d`.<br>
    /// If the `field` value is a
    /// [`geo_point`](https://www.elastic.co/guide/en/elasticsearch/reference/current/geo-point.html)
    /// field, the `pivot` value must be a
    /// [distance unit](https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#distance-units)
    /// , such as `1km` or `12m`.
    pub fn distance_feature<O: Origin>(
        field: impl Into<String>,
        origin: O,
        pivot: <O as Origin>::Pivot,
    ) -> DistanceFeatureQuery<O> {
        DistanceFeatureQuery {
            inner: Inner {
                field: field.into(),
                origin,
                pivot,
                boost: None,
                _name: None,
            },
        }
    }
}

impl<O: Origin> DistanceFeatureQuery<O> {
    add_boost_and_name!();
}

impl<O: Origin> ShouldSkip for DistanceFeatureQuery<O> {}

#[cfg(test)]
mod tests {
    use super::*;

    mod date {
        use super::*;
        use chrono::prelude::*;

        test_serialization! {
            with_required_fields(
                Query::distance_feature("test", Utc.ymd(2014, 7, 8).and_hms(9, 1, 0), Time::Days(7)),
                json!({
                    "distance_feature": {
                        "field": "test",
                        "origin": "2014-07-08T09:01:00Z",
                        "pivot": "7d",
                    }
                })
            );

            with_all_fields(
                Query::distance_feature("test", Utc.ymd(2014, 7, 8).and_hms(9, 1, 0), Time::Days(7))
                    .boost(1.5)
                    .name("test"),
                json!({
                    "distance_feature": {
                        "field": "test",
                        "origin": "2014-07-08T09:01:00Z",
                        "pivot": "7d",
                        "boost": 1.5,
                        "_name": "test",
                    }
                })
            );
        }
    }

    mod geo {
        use super::*;

        test_serialization! {
            with_required_fields(
                Query::distance_feature("test", GeoPoint::coordinates(12.0, 13.0), Distance::Kilometers(15)),
                json!({
                    "distance_feature": {
                        "field": "test",
                        "origin": [13.0, 12.0],
                        "pivot": "15km",
                    }
                })
            );

            with_all_fields(
                Query::distance_feature("test", GeoPoint::coordinates(12.0, 13.0), Distance::Kilometers(15))
                    .boost(2)
                    .name("test"),
                json!({
                    "distance_feature": {
                        "field": "test",
                        "origin": [13.0, 12.0],
                        "pivot": "15km",
                        "boost": 2,
                        "_name": "test",
                    }
                })
            );
        }
    }
}