1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, Default, Serialize, Deserialize)]
4pub struct SearchHit {
5 pub id: String,
6 #[serde(skip_serializing_if = "Option::is_none")]
7 pub score: Option<f64>,
8 #[serde(default)]
9 pub source: serde_json::Value,
10 #[serde(skip_serializing_if = "Option::is_none")]
11 pub highlight: Option<serde_json::Value>,
12}
13
14#[derive(Debug, Clone, Default, Serialize, Deserialize)]
15pub struct SearchResult {
16 #[serde(default)]
17 pub hits: Vec<SearchHit>,
18 #[serde(default)]
19 pub total: usize,
20 #[serde(skip_serializing_if = "Option::is_none")]
21 pub aggregations: Option<serde_json::Value>,
22 #[serde(skip_serializing_if = "Option::is_none")]
23 pub facets: Option<serde_json::Value>,
24 #[serde(skip_serializing_if = "Option::is_none")]
25 pub raw: Option<serde_json::Value>,
26}
27
28impl SearchResult {
29 pub fn ids(&self) -> Vec<String> {
30 self.hits.iter().map(|hit| hit.id.clone()).collect()
31 }
32
33 pub(crate) fn without_hits(self) -> Self {
40 Self {
41 hits: Vec::new(),
42 ..self
43 }
44 }
45}
46
47#[cfg(test)]
48mod tests {
49 use super::*;
50
51 #[test]
52 fn without_hits_keeps_total() {
53 let result = SearchResult {
54 hits: vec![SearchHit {
55 id: "a".to_string(),
56 ..SearchHit::default()
57 }],
58 total: 42,
59 ..SearchResult::default()
60 };
61 let cleared = result.without_hits();
62 assert!(cleared.hits.is_empty());
63 assert_eq!(cleared.total, 42, "total 是分页前的全量匹配数,不能被清掉");
64 }
65}