elasticsearch_dsl/search/queries/span/
span_term_query.rs

1use crate::util::*;
2use crate::{Query, Term};
3use serde::Serialize;
4
5/// Matches spans containing a term. The span term query maps to Lucene `SpanTermQuery`.
6///
7/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-span-term-query.html>
8#[derive(Debug, Clone, PartialEq, Serialize)]
9#[serde(remote = "Self")]
10pub struct SpanTermQuery {
11    #[serde(skip)]
12    field: String,
13
14    value: Option<Term>,
15
16    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
17    boost: Option<f32>,
18
19    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
20    _name: Option<String>,
21}
22
23impl Query {
24    /// Creates an instance of [`SpanTermQuery`]
25    ///
26    /// - `field` - Field you wish to search.
27    /// - `value` - Term you wish to find in the provided field.
28    ///   To return a document, the term must exactly match the field value, including whitespace and capitalization.
29    pub fn span_term<T, U>(field: T, value: U) -> SpanTermQuery
30    where
31        T: ToString,
32        U: Serialize,
33    {
34        SpanTermQuery {
35            field: field.to_string(),
36            value: Term::new(value),
37            boost: None,
38            _name: None,
39        }
40    }
41}
42
43impl SpanTermQuery {
44    add_boost_and_name!();
45}
46
47impl ShouldSkip for SpanTermQuery {
48    fn should_skip(&self) -> bool {
49        self.value.should_skip()
50    }
51}
52
53serialize_with_root_keyed!("span_term": SpanTermQuery);
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn serialization() {
61        assert_serialize_query(
62            Query::span_term("test", 123u32),
63            json!({
64                "span_term": {
65                    "test": {
66                        "value": 123
67                    }
68                }
69            }),
70        );
71
72        assert_serialize_query(
73            Query::span_term("test", 123).boost(2).name("test"),
74            json!({
75                "span_term": {
76                    "test": {
77                        "value": 123,
78                        "boost": 2.0,
79                        "_name": "test"
80                    }
81                }
82            }),
83        );
84    }
85}