-
Notifications
You must be signed in to change notification settings - Fork 16
/
function_score_query.rs
712 lines (615 loc) · 20.6 KB
/
function_score_query.rs
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
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>),
DecayF32(Decay<f32>),
DecayF64(Decay<f64>),
ScriptScore(ScriptScore),
});
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(source: Script) -> ScriptScore {
ScriptScore::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, PartialEq, Serialize)]
pub struct Weight {
weight: f32,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
filter: Option<Query>,
}
impl Weight {
/// Creates an instance of [Weight](Weight)
pub fn new(weight: f32) -> Self {
Self {
weight,
filter: None,
}
}
/// Add function filter
pub fn filter<T>(mut self, filter: T) -> Self
where
T: Into<Option<Query>>,
{
self.filter = filter.into();
self
}
}
/// 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,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
filter: Option<Query>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
weight: Option<f32>,
}
#[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()
}
/// Add function filter
pub fn filter<T>(mut self, filter: T) -> Self
where
T: Into<Option<Query>>,
{
self.filter = filter.into();
self
}
/// 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.
/// The number value is of type float.
pub fn weight<T>(mut self, weight: T) -> Self
where
T: num_traits::AsPrimitive<f32>,
{
self.weight = Some(weight.as_());
self
}
/// 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,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
filter: Option<Query>,
#[serde(skip_serializing_if = "ShouldSkip::should_skip")]
weight: Option<f32>,
}
#[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,
},
filter: None,
weight: None,
}
}
/// Add function filter
pub fn filter<T>(mut self, filter: T) -> Self
where
T: Into<Option<Query>>,
{
self.filter = filter.into();
self
}
/// 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.
/// The number value is of type float.
pub fn weight<T>(mut self, weight: T) -> Self
where
T: num_traits::AsPrimitive<f32>,
{
self.weight = Some(weight.as_());
self
}
/// 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 = "lowercase")]
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>,
filter: Option<Query>,
weight: Option<f32>,
}
#[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,
},
},
filter: None,
weight: None,
}
}
/// Add function filter
pub fn filter<T>(mut self, filter: T) -> Self
where
T: Into<Option<Query>>,
{
self.filter = filter.into();
self
}
/// 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.
/// The number value is of type float.
pub fn weight<T>(mut self, weight: T) -> Self
where
T: num_traits::AsPrimitive<f32>,
{
self.weight = Some(weight.as_());
self
}
/// 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(3))?;
map.serialize_entry(&self.function, &self.inner)?;
if let Some(filter) = &self.filter {
map.serialize_entry("filter", filter)?;
}
if let Some(weight) = &self.weight {
map.serialize_entry("weight", weight)?;
}
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 ScriptScore {
script_score: ScriptWrapper,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
struct ScriptWrapper {
script: Script,
}
impl ScriptScore {
/// Creates an instance of [Script]
///
/// - `script` - script source
pub fn new(script: Script) -> Self {
Self {
script_score: ScriptWrapper { script },
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::prelude::*;
#[test]
fn serialization() {
assert_serialize(
Decay::new(
DecayFunction::Gauss,
"test",
Utc.with_ymd_and_hms(2014, 7, 8, 9, 1, 0).single().unwrap(),
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,
}
}
}),
);
assert_serialize(
ScriptScore::new(Script::source("Math.log(2 + doc['my-int'].value)")),
json!({
"script_score": {
"script": {
"source": "Math.log(2 + doc['my-int'].value)"
}
}
}),
);
}
#[test]
fn float_decay() {
assert_serialize(
Decay::new(DecayFunction::Linear, "test", 0.1, 0.5),
json!({
"linear": {
"test": {
"origin": 0.1,
"scale": 0.5
}
}
}),
);
}
}