Skip to main content

rust_scout/
result.rs

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    /// 清空 `hits`,保留 `total` 等其余字段。
34    ///
35    /// 供 `take(0)` 的契约对齐使用:Collection 与 ES 的 `total` 是「分页之前」的
36    /// 全量匹配数,所以 `take(0)` 返回的是「命中总数 + 空 hits」。后端的 total 只能
37    /// 从后端拿,因此那几个驱动仍会发一次请求(只取 1 条),拿到后用这个方法把
38    /// hits 丢掉。没有它,同样的 `take(0)` 会在内存/ES 上报 N、在其它后端上报 0。
39    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}