1use serde::{Deserialize, Serialize};
2
3use crate::SearchDocument;
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct SearchBuilder {
7 #[serde(default)]
8 pub query: String,
9 #[serde(skip_serializing_if = "Option::is_none")]
10 pub index: Option<String>,
11 #[serde(default)]
12 pub wheres: Vec<Where>,
13 #[serde(default)]
14 pub where_ins: Vec<(String, Vec<serde_json::Value>)>,
15 #[serde(default)]
16 pub where_not_ins: Vec<(String, Vec<serde_json::Value>)>,
17 #[serde(default)]
18 pub orders: Vec<Order>,
19 #[serde(default)]
20 pub options: serde_json::Value,
21 #[serde(skip_serializing_if = "Option::is_none")]
22 pub take: Option<usize>,
23 #[serde(skip_serializing_if = "Option::is_none")]
24 pub skip: Option<usize>,
25}
26
27#[derive(Debug, Clone, Serialize, Deserialize)]
28pub struct Where {
29 pub field: String,
30 pub value: serde_json::Value,
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
34pub struct Order {
35 pub field: String,
36 pub desc: bool,
37}
38
39impl Default for SearchBuilder {
40 fn default() -> Self {
41 Self {
42 query: String::new(),
43 index: None,
44 wheres: Vec::new(),
45 where_ins: Vec::new(),
46 where_not_ins: Vec::new(),
47 orders: Vec::new(),
48 options: serde_json::Value::Object(Default::default()),
49 take: None,
50 skip: None,
51 }
52 }
53}
54
55impl SearchBuilder {
56 pub fn new(query: impl Into<String>) -> Self {
57 Self {
58 query: query.into(),
59 ..Self::default()
60 }
61 }
62
63 pub fn within(mut self, index: impl Into<String>) -> Self {
64 self.index = Some(index.into());
65 self
66 }
67
68 pub fn where_field(
69 mut self,
70 field: impl Into<String>,
71 value: impl Into<serde_json::Value>,
72 ) -> Self {
73 self.wheres.push(Where {
74 field: field.into(),
75 value: value.into(),
76 });
77 self
78 }
79
80 pub fn where_in(
81 mut self,
82 field: impl Into<String>,
83 values: impl IntoIterator<Item = impl Into<serde_json::Value>>,
84 ) -> Self {
85 let values = values.into_iter().map(Into::into).collect();
86 self.where_ins.push((field.into(), values));
87 self
88 }
89
90 pub fn where_not_in(
91 mut self,
92 field: impl Into<String>,
93 values: impl IntoIterator<Item = impl Into<serde_json::Value>>,
94 ) -> Self {
95 let values = values.into_iter().map(Into::into).collect();
96 self.where_not_ins.push((field.into(), values));
97 self
98 }
99
100 pub fn order_by(mut self, field: impl Into<String>, desc: bool) -> Self {
101 self.orders.push(Order {
102 field: field.into(),
103 desc,
104 });
105 self
106 }
107
108 pub fn take(mut self, limit: usize) -> Self {
109 self.take = Some(limit);
110 self
111 }
112
113 pub fn skip(mut self, offset: usize) -> Self {
114 self.skip = Some(offset);
115 self
116 }
117
118 pub fn option(mut self, key: impl Into<String>, value: impl Into<serde_json::Value>) -> Self {
119 if let serde_json::Value::Object(ref mut map) = self.options {
120 map.insert(key.into(), value.into());
121 }
122 self
123 }
124
125 pub fn matches(&self, doc: &SearchDocument) -> bool {
126 if !self.query.trim().is_empty() {
127 let needle = self.query.trim().to_lowercase();
128 let haystack = serde_json::to_string(&doc.fields)
129 .unwrap_or_default()
130 .to_lowercase();
131 if !haystack.contains(&needle) {
132 return false;
133 }
134 }
135
136 for where_ in &self.wheres {
137 if doc.get(&where_.field) != Some(&where_.value) {
138 return false;
139 }
140 }
141
142 for (field, values) in &self.where_ins {
143 let value = doc.get(field);
144 if !values.iter().any(|v| value == Some(v)) {
145 return false;
146 }
147 }
148
149 for (field, values) in &self.where_not_ins {
150 let value = doc.get(field);
151 if values.iter().any(|v| value == Some(v)) {
152 return false;
153 }
154 }
155
156 true
157 }
158
159 pub fn sort_hits(&self, hits: &mut Vec<crate::SearchHit>) {
160 if self.orders.is_empty() {
161 hits.sort_by(|a, b| a.id.cmp(&b.id));
162 return;
163 }
164 hits.sort_by(|a, b| {
165 for order in &self.orders {
166 let left = a.source.get(&order.field).cloned();
167 let right = b.source.get(&order.field).cloned();
168 let cmp = order_cmp(&left, &right);
169 if cmp != std::cmp::Ordering::Equal {
170 return if order.desc { cmp.reverse() } else { cmp };
171 }
172 }
173 a.id.cmp(&b.id)
174 });
175 }
176}
177
178fn order_cmp(a: &Option<serde_json::Value>, b: &Option<serde_json::Value>) -> std::cmp::Ordering {
179 match (a, b) {
180 (None, None) => std::cmp::Ordering::Equal,
181 (None, Some(_)) => std::cmp::Ordering::Less,
182 (Some(_), None) => std::cmp::Ordering::Greater,
183 (Some(a), Some(b)) => value_cmp(a, b),
184 }
185}
186
187fn value_cmp(a: &serde_json::Value, b: &serde_json::Value) -> std::cmp::Ordering {
188 use serde_json::Value;
189 match (a, b) {
190 (Value::Null, Value::Null) => std::cmp::Ordering::Equal,
191 (Value::Null, _) => std::cmp::Ordering::Less,
192 (_, Value::Null) => std::cmp::Ordering::Greater,
193 (Value::Bool(a), Value::Bool(b)) => a.cmp(b),
194 (Value::Number(a), Value::Number(b)) => number_cmp(a, b),
195 (Value::String(a), Value::String(b)) => a.cmp(b),
196 _ => a.to_string().cmp(&b.to_string()),
197 }
198}
199
200fn number_cmp(a: &serde_json::Number, b: &serde_json::Number) -> std::cmp::Ordering {
201 match (a.as_i64(), b.as_i64()) {
202 (Some(a), Some(b)) => a.cmp(&b),
203 _ => {
204 let a = a.as_f64().unwrap_or(f64::NAN);
205 let b = b.as_f64().unwrap_or(f64::NAN);
206 if a.is_nan() && b.is_nan() {
207 std::cmp::Ordering::Equal
208 } else {
209 a.partial_cmp(&b).unwrap_or(std::cmp::Ordering::Less)
210 }
211 }
212 }
213}