elasticsearch_dsl/search/queries/specialized/
script_score_query.rs

1use crate::search::*;
2use crate::util::*;
3
4/// A query allowing you to modify the score of documents that are retrieved by
5/// a query. This can be useful if, for example, a score function is
6/// computationally expensive and it is sufficient to compute the score on a
7/// filtered set of documents.
8///
9/// To create script score query:
10/// ```
11/// # use elasticsearch_dsl::queries::*;
12/// # use elasticsearch_dsl::queries::params::*;
13/// # let query =
14/// Query::script_score(
15///     Query::r#match("message", "elasticsearch"),
16///     Script::source("doc['my-int'].value / 10"),
17/// );
18/// ```
19/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-script-score-query.html>
20#[derive(Debug, Clone, PartialEq, Serialize)]
21#[serde(remote = "Self")]
22pub struct ScriptScoreQuery {
23    query: Box<Query>,
24
25    script: Script,
26
27    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
28    min_score: Option<f32>,
29
30    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
31    boost: Option<f32>,
32
33    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
34    _name: Option<String>,
35}
36
37impl Query {
38    /// Creates an instance of [`ScriptScoreQuery`]
39    ///
40    /// - `query` - Query used to return documents
41    /// - `script` - Script used to compute the score of documents returned by
42    ///   the `query`
43    pub fn script_score<Q>(query: Q, script: Script) -> ScriptScoreQuery
44    where
45        Q: Into<Query>,
46    {
47        ScriptScoreQuery {
48            query: Box::new(query.into()),
49            script,
50            min_score: None,
51            boost: None,
52            _name: None,
53        }
54    }
55}
56
57impl ScriptScoreQuery {
58    add_boost_and_name!();
59}
60
61impl ShouldSkip for ScriptScoreQuery {}
62
63serialize_with_root!("script_score": ScriptScoreQuery);
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[test]
70    fn serialization() {
71        assert_serialize_query(
72            Query::script_score(
73                Query::r#match("message", "elasticsearch"),
74                Script::source("doc['my-int'].value / 10"),
75            )
76            .name("_named_query")
77            .boost(1.1),
78            json!({
79                "script_score": {
80                    "_name": "_named_query",
81                    "boost": 1.1,
82                    "query": { "match": { "message": { "query": "elasticsearch" } } },
83                    "script": {
84                        "source": "doc['my-int'].value / 10"
85                    }
86                }
87            }),
88        );
89    }
90}