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
use crate::util::*;
use crate::{Query, Term};
use serde::Serialize;

/// Matches spans containing a term. The span term query maps to Lucene `SpanTermQuery`.
///
/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-span-term-query.html>
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(remote = "Self")]
pub struct SpanTermQuery {
    #[serde(skip)]
    field: String,

    value: Option<Term>,

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

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

impl Query {
    /// Creates an instance of [`SpanTermQuery`]
    ///
    /// - `field` - Field you wish to search.
    /// - `value` - Term you wish to find in the provided field.
    /// To return a document, the term must exactly match the field value, including whitespace and capitalization.
    pub fn span_term<T, U>(field: T, value: U) -> SpanTermQuery
    where
        T: ToString,
        U: Serialize,
    {
        SpanTermQuery {
            field: field.to_string(),
            value: Term::new(value),
            boost: None,
            _name: None,
        }
    }
}

impl SpanTermQuery {
    add_boost_and_name!();
}

impl ShouldSkip for SpanTermQuery {
    fn should_skip(&self) -> bool {
        self.value.should_skip()
    }
}

serialize_with_root_keyed!("span_term": SpanTermQuery);

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

    #[test]
    fn serialization() {
        assert_serialize_query(
            Query::span_term("test", 123u32),
            json!({
                "span_term": {
                    "test": {
                        "value": 123
                    }
                }
            }),
        );

        assert_serialize_query(
            Query::span_term("test", 123).boost(2).name("test"),
            json!({
                "span_term": {
                    "test": {
                        "value": 123,
                        "boost": 2.0,
                        "_name": "test"
                    }
                }
            }),
        );
    }
}