elasticsearch_dsl/search/queries/term_level/exists_query.rs
1use crate::search::*;
2use crate::util::*;
3
4/// Returns documents that contain an indexed value for a field.
5///
6/// An indexed value may not exist for a document’s field due to a variety of reasons:
7///
8/// - The field in the source JSON is `null` or `[]`
9/// - The field has `"index" : false` set in the mapping
10/// - The length of the field value exceeded an `ignore_above` setting in the mapping
11/// - The field value was malformed and `ignore_malformed` was defined in the mapping
12///
13/// To create exists query:
14/// ```
15/// # use elasticsearch_dsl::queries::*;
16/// # use elasticsearch_dsl::queries::params::*;
17/// # let query =
18/// Query::exists("test");
19/// ```
20/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-exists-query.html>
21#[derive(Debug, Clone, PartialEq, Serialize)]
22#[serde(remote = "Self")]
23pub struct ExistsQuery {
24 field: String,
25
26 #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
27 boost: Option<f32>,
28
29 #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
30 _name: Option<String>,
31}
32
33impl Query {
34 /// Creates an instance of [`ExistsQuery`]
35 ///
36 /// - `field` - Name of the field you wish to search.
37 /// While a field is deemed non-existent if the JSON value is `null` or `[]`,
38 /// these values will indicate the field does exist:
39 /// - Empty strings, such as `""` or `"-"`
40 /// - Arrays containing `null` and another value, such as `[null, "foo"]`
41 /// - A custom [`null-value`](https://www.elastic.co/guide/en/elasticsearch/reference/current/null-value.html), defined in field mapping
42 pub fn exists<T>(field: T) -> ExistsQuery
43 where
44 T: ToString,
45 {
46 ExistsQuery {
47 field: field.to_string(),
48 boost: None,
49 _name: None,
50 }
51 }
52}
53
54impl ExistsQuery {
55 add_boost_and_name!();
56}
57
58impl ShouldSkip for ExistsQuery {}
59
60serialize_with_root!("exists": ExistsQuery);
61
62#[cfg(test)]
63mod tests {
64 use super::*;
65
66 #[test]
67 fn serialization() {
68 assert_serialize_query(
69 Query::exists("test"),
70 json!({
71 "exists": {
72 "field": "test"
73 }
74 }),
75 );
76
77 assert_serialize_query(
78 Query::exists("test").boost(2).name("test"),
79 json!({
80 "exists": {
81 "field": "test",
82 "boost": 2.0,
83 "_name": "test"
84 }
85 }),
86 );
87 }
88}