opensearch-dsl 0.3.1

Strongly typed OpenSearch DSL
Documentation
use serde::Serialize;

use crate::{search::*, util::*};

/// Returns documents that contain an **exact** term in a provided field.
///
/// You can use the term query to find documents based on a precise value such
/// as a price, a product ID, or a username.
///
/// To create a term query with numeric values:
/// ```
/// # use opensearch_dsl::queries::*;
/// # use opensearch_dsl::queries::params::*;
/// # let query =
/// Query::term("test", 123);
/// ```
/// To create a term query with string values and optional fields:
/// ```
/// # use opensearch_dsl::queries::*;
/// # use opensearch_dsl::queries::params::*;
/// # let query =
/// Query::term("test", "username").boost(2).name("test");
/// ```
/// <https://www.elastic.co/guide/en/opensearch/reference/current/query-dsl-term-query.html>
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(remote = "Self")]
pub struct TermQuery {
    #[serde(skip)]
    field: String,

    value: Option<Term>,

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

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

impl Query {
    /// Creates an instance of [`TermQuery`]
    ///
    /// - `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 term<T, U>(field: T, value: U) -> TermQuery
    where
        T: ToString,
        U: Serialize,
    {
        TermQuery {
            field: field.to_string(),
            value: Term::new(value),
            boost: None,
            _name: None,
        }
    }
}

impl TermQuery {
    add_boost_and_name!();
}

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

serialize_with_root_keyed!("term": TermQuery);
deserialize_with_root_keyed!("term": TermQuery);

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

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

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

        assert_serialize_query(
            Query::bool().filter(Query::term("test", None::<String>)),
            json!({ "bool": {} }),
        )
    }
}