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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
use crate::search::*;
use crate::util::*;
use chrono::{DateTime, Utc};
use serde::ser::{Serialize, SerializeMap, Serializer};
use std::fmt::Debug;
/// Each document is scored by the defined functions. The parameter `score_mode` specifies how
/// the computed scores are combined
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FunctionScoreMode {
/// Scores are multiplied (default)
Multiply,
/// Scores are summed
Sum,
/// Scores are averaged
Avg,
/// The first function that has a matching filter is applied
First,
/// Maximum score is used
Max,
/// Minimum score is used
Min,
}
impl Default for FunctionScoreMode {
fn default() -> Self {
Self::Multiply
}
}
/// The newly computed score is combined with the score of the query. The parameter
/// `boost_mode` defines how.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FunctionBoostMode {
/// Query score and function score is multiplied (default)
Multiply,
/// Only function score is used, the query score is ignored
Replace,
/// Query score and function score are added
Sum,
/// Average
Avg,
/// Max of query score and function score
Max,
/// Min of query score and function score
Min,
}
impl Default for FunctionBoostMode {
fn default() -> Self {
Self::Multiply
}
}
macro_rules! function {
($name:ident { $($variant:ident($query:ty)),+ $(,)? }) => {
/// Functions available for use in [FunctionScoreQuery](crate::FunctionScoreQuery)
#[derive(Debug, Clone, PartialEq, Serialize)]
#[allow(missing_docs)]
#[serde(untagged)]
pub enum $name {
$(
$variant($query),
)*
}
$(
impl From<$query> for $name {
fn from(q: $query) -> Self {
$name::$variant(q)
}
}
)+
$(
impl From<$query> for Option<$name> {
fn from(q: $query) -> Self {
Some($name::$variant(q))
}
}
)+
};
}
function!(Function {
Weight(Weight),
RandomScore(RandomScore),
FieldValueFactor(FieldValueFactor),
DecayDateTime(Decay<DateTime<Utc>>),
DecayLocation(Decay<GeoLocation>),
DecayI8(Decay<i8>),
DecayI16(Decay<i16>),
DecayI32(Decay<i32>),
DecayI64(Decay<i64>),
DecayU8(Decay<u8>),
DecayU16(Decay<u16>),
DecayU32(Decay<u32>),
DecayU64(Decay<u64>),
Script(Script),
});
impl Function {
/// Creates an instance of [Weight](Weight)
pub fn weight(weight: f32) -> Weight {
Weight::new(weight)
}
/// Creates an instance of [RandomScore](RandomScore)
pub fn random_score() -> RandomScore {
RandomScore::new()
}
/// Creates an instance of [FieldValueFactor](FieldValueFactor)
///
/// - `field` - Field to be extracted from the document.
pub fn field_value_factor<T>(field: T) -> FieldValueFactor
where
T: ToString,
{
FieldValueFactor::new(field)
}
/// Creates an instance of [Decay](Decay)
///
/// - `function` - Decay function variant
/// - `field` - Field to apply function to
/// - `origin` - The point of origin used for calculating distance. Must be given as a number
/// for numeric field, date for date fields and geo point for geo fields. Required for geo and
/// numeric field. For date fields the default is `now`. Date math (for example now-1h) is
/// supported for origin.
/// - `scale` - Required for all types. Defines the distance from origin + offset at which the
/// computed score will equal `decay` parameter. For geo fields: Can be defined as number+unit
/// (1km, 12m,…). Default unit is meters. For date fields: Can to be defined as a number+unit
/// ("1h", "10d",…). Default unit is milliseconds. For numeric field: Any number.
pub fn decay<T, O>(
function: DecayFunction,
field: T,
origin: O,
scale: <O as Origin>::Scale,
) -> Decay<O>
where
T: ToString,
O: Origin,
{
Decay::new(function, field, origin, scale)
}
/// Creates an instance of script
///
/// - `source` - script source
pub fn script<T>(source: T) -> Script
where
T: ToString,
{
Script::new(source)
}
}
/// The `weight` score allows you to multiply the score by the provided weight.
///
/// This can sometimes be desired since boost value set on specific queries gets normalized, while
/// for this score function it does not
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize)]
pub struct Weight {
weight: f32,
}
impl Weight {
/// Creates an instance of [Weight](Weight)
pub fn new(weight: f32) -> Self {
Self { weight }
}
}
/// The `random_score` generates scores that are uniformly distributed from `0` up to but not
/// including `1`.
///
/// By default, it uses the internal Lucene doc ids as a source of randomness, which is very
/// efficient but unfortunately not reproducible since documents might be renumbered by merges.
///
/// In case you want scores to be reproducible, it is possible to provide a `seed` and `field`. The
/// final score will then be computed based on this seed, the minimum value of `field` for the
/// considered document and a salt that is computed based on the index name and shard id so that
/// documents that have the same value but are stored in different indexes get different scores.
/// Note that documents that are within the same shard and have the same value for `field` will
/// however get the same score, so it is usually desirable to use a field that has unique values
/// for all documents. A good default choice might be to use the `_seq_no` field, whose only
/// drawback is that scores will change if the document is updated since update operations also
/// update the value of the `_seq_no` field.
#[derive(Debug, Default, Clone, PartialEq, Serialize)]
pub struct RandomScore {
random_score: RandomScoreInner,
}
#[derive(Debug, Default, Clone, PartialEq, Serialize)]
struct RandomScoreInner {
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
seed: Option<Term>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
field: Option<String>,
}
impl RandomScore {
/// Creates an instance of [RandomScore](RandomScore)
pub fn new() -> Self {
Default::default()
}
/// Sets seed value
pub fn seed<T>(mut self, seed: T) -> Self
where
T: Serialize,
{
self.random_score.seed = Term::new(seed);
self
}
/// Sets field value
pub fn field<T>(mut self, field: T) -> Self
where
T: ToString,
{
self.random_score.field = Some(field.to_string());
self
}
}
/// The `field_value_factor` function allows you to use a field from a document to influence the
/// score.
/// It’s similar to using the `script_score` function, however, it avoids the overhead of scripting.
/// If used on a multi-valued field, only the first value of the field is used in calculations.
///
/// As an example, imagine you have a document indexed with a numeric `my-int` field and wish to
/// influence the score of a document with this field, an example doing so would look like:
/// ```
/// # use elasticsearch_dsl::{FieldValueFactor, FieldValueFactorModifier};
/// # fn main() {
/// # let _ =
/// FieldValueFactor::new("my-int")
/// .factor(1.2)
/// .modifier(FieldValueFactorModifier::Sqrt)
/// .missing(1.0)
/// # ;}
/// ```
/// Which will translate into the following formula for scoring:
/// ```text
/// sqrt(1.2 * doc['my-int'].value)
/// ```
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct FieldValueFactor {
field_value_factor: FieldValueFactorInner,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
struct FieldValueFactorInner {
field: String,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
factor: Option<f32>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
modifier: Option<FieldValueFactorModifier>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
missing: Option<f32>,
}
impl FieldValueFactor {
/// Creates an instance of [FieldValueFactor](FieldValueFactor)
///
/// - `field` - Field to be extracted from the document.
pub fn new<T>(field: T) -> Self
where
T: ToString,
{
Self {
field_value_factor: FieldValueFactorInner {
field: field.to_string(),
factor: None,
modifier: None,
missing: None,
},
}
}
/// Factor to multiply the field value with
pub fn factor(mut self, factor: f32) -> Self {
self.field_value_factor.factor = Some(factor);
self
}
/// Modifier to apply to the field value
pub fn modifier(mut self, modifier: FieldValueFactorModifier) -> Self {
self.field_value_factor.modifier = Some(modifier);
self
}
/// Value used if the document doesn’t have that field. The modifier and factor are still
/// applied to it as though it were read from the document
pub fn missing(mut self, missing: f32) -> Self {
self.field_value_factor.missing = Some(missing);
self
}
}
/// Modifier to apply to the field value
///
/// Defaults to [none](FieldValueFactorModifier::None)
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum FieldValueFactorModifier {
/// Do not apply any multiplier to the field value
None,
/// Take the [common logarithm](https://en.wikipedia.org/wiki/Common_logarithm) of the field
/// value
///
/// Because this function will return a negative value and cause an error if used on values
/// between `0` and `1`, it is recommended to use [log1p](FieldValueFactorModifier::Log1P)
/// instead.
Log,
/// Add 1 to the field value and take the common logarithm
Log1P,
/// Add 2 to the field value and take the common logarithm
Log2P,
/// Take the [natural logarithm](https://en.wikipedia.org/wiki/Natural_logarithm) of the field
/// value.
///
/// Because this function will return a negative value and cause an error if used on values
/// between `0` and `1`, it is recommended to use [ln1p](FieldValueFactorModifier::Ln1P)
/// instead.
Ln,
/// Add 1 to the field value and take the natural logarithm
Ln1P,
/// Add 2 to the field value and take the natural logarithm
Ln2P,
/// Square the field value (multiply it by itself)
Square,
/// Take the [square root](https://en.wikipedia.org/wiki/Square_root) of the field value
Sqrt,
/// [Reciprocate](https://en.wikipedia.org/wiki/Multiplicative_inverse) the field value, same
/// as `1/x` where `x` is the field’s value
Reciprocal,
}
#[doc(hidden)]
pub trait Origin: Debug + PartialEq + Serialize + Clone {
type Scale: Debug + PartialEq + Serialize + Clone;
type Offset: Debug + PartialEq + Serialize + Clone;
}
impl Origin for DateTime<Utc> {
type Scale = Time;
type Offset = Time;
}
impl Origin for GeoLocation {
type Scale = Distance;
type Offset = Distance;
}
macro_rules! impl_origin_for_numbers {
($($name:ident ),+) => {
$(
impl Origin for $name {
type Scale = Self;
type Offset = Self;
}
)+
}
}
impl_origin_for_numbers![i8, i16, i32, i64, u8, u16, u32, u64, f32, f64];
/// Decay functions score a document with a function that decays depending on the distance of a
/// numeric field value of the document from a user given origin. This is similar to a range query,
/// but with smooth edges instead of boxes.
///
/// To use distance scoring on a query that has numerical fields, the user has to define an
/// `origin` and a `scale` for each field. The `origin` is needed to define the “central point”
/// from which the distance is calculated, and the `scale` to define the rate of decay.
#[derive(Debug, Clone, PartialEq)]
pub struct Decay<T: Origin> {
function: DecayFunction,
inner: DecayFieldInner<T>,
}
#[derive(Debug, Clone, PartialEq)]
struct DecayFieldInner<T: Origin> {
field: String,
inner: DecayInner<T>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
struct DecayInner<O>
where
O: Origin,
{
origin: O,
scale: <O as Origin>::Scale,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
offset: Option<<O as Origin>::Offset>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
decay: Option<f32>,
}
impl<O> Decay<O>
where
O: Origin,
{
/// Creates an instance of [Decay](Decay)
///
/// - `function` - Decay function variant
/// - `field` - Field to apply function to
/// - `origin` - The point of origin used for calculating distance. Must be given as a number
/// for numeric field, date for date fields and geo point for geo fields. Required for geo and
/// numeric field. For date fields the default is `now`. Date math (for example now-1h) is
/// supported for origin.
/// - `scale` - Required for all types. Defines the distance from origin + offset at which the
/// computed score will equal `decay` parameter. For geo fields: Can be defined as number+unit
/// (1km, 12m,…). Default unit is meters. For date fields: Can to be defined as a number+unit
/// ("1h", "10d",…). Default unit is milliseconds. For numeric field: Any number.
pub fn new<T>(function: DecayFunction, field: T, origin: O, scale: <O as Origin>::Scale) -> Self
where
T: ToString,
{
Self {
function,
inner: DecayFieldInner {
field: field.to_string(),
inner: DecayInner {
origin,
scale,
offset: None,
decay: None,
},
},
}
}
/// If an `offset` is defined, the decay function will only compute the decay function for
/// documents with a distance greater than the defined `offset`.
///
/// The default is `0`.
pub fn offset(mut self, offset: <O as Origin>::Offset) -> Self {
self.inner.inner.offset = Some(offset);
self
}
/// The `decay` parameter defines how documents are scored at the distance given at `scale`. If
/// no `decay` is defined, documents at the distance `scale` will be scored `0.5`.
pub fn decay(mut self, decay: f32) -> Self {
self.inner.inner.decay = Some(decay);
self
}
}
impl<T: Origin> Serialize for Decay<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(Some(1))?;
map.serialize_entry(&self.function, &self.inner)?;
map.end()
}
}
impl<T: Origin> Serialize for DecayFieldInner<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(Some(1))?;
map.serialize_entry(&self.field, &self.inner)?;
map.end()
}
}
/// Decay function variants
///
/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html#_supported_decay_functions>
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DecayFunction {
/// Linear decay
Linear,
/// Exponential decay
Exp,
/// Gauss decay
Gauss,
}
/// The script_score function allows you to wrap another query and customize the scoring of it
/// optionally with a computation derived from other numeric field values in the doc using a script
/// expression
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Script {
script_score: ScriptInnerWrapper,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
struct ScriptInnerWrapper {
script: ScriptInner,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
struct ScriptInner {
source: String,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
params: Option<serde_json::Value>,
}
impl Script {
/// Creates an instance of [Script]
///
/// - `source` - script source
pub fn new<T>(source: T) -> Self
where
T: ToString,
{
Self {
script_score: ScriptInnerWrapper {
script: ScriptInner {
source: source.to_string(),
params: None,
},
},
}
}
/// Sets params value
pub fn params(mut self, params: serde_json::Value) -> Self {
self.script_score.script.params = Some(params);
self
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::prelude::*;
#[test]
fn serialization() {
assert_serialize(
Decay::new(
DecayFunction::Gauss,
"test",
Utc.ymd(2014, 7, 8).and_hms(9, 1, 0),
Time::Days(7),
),
json!({
"gauss": {
"test": {
"origin": "2014-07-08T09:01:00Z",
"scale": "7d",
}
}
}),
);
assert_serialize(
Decay::new(DecayFunction::Linear, "test", 1, 2),
json!({
"linear": {
"test": {
"origin": 1,
"scale": 2,
}
}
}),
);
}
}