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    ///
40    /// cfg 必须与调用方一致(只有这三个驱动需要它):Collection/ES 的 `total` 本来就
41    /// 是分页前算的,不需要清 hits。不门控时默认构建会报 `without_hits` never used。
42    #[cfg(any(feature = "meilisearch", feature = "typesense", feature = "algolia"))]
43    pub(crate) fn without_hits(self) -> Self {
44        Self {
45            hits: Vec::new(),
46            ..self
47        }
48    }
49}
50
51#[cfg(all(
52    test,
53    any(feature = "meilisearch", feature = "typesense", feature = "algolia")
54))]
55mod tests {
56    use super::*;
57
58    #[test]
59    fn without_hits_keeps_total() {
60        let result = SearchResult {
61            hits: vec![SearchHit {
62                id: "a".to_string(),
63                ..SearchHit::default()
64            }],
65            total: 42,
66            ..SearchResult::default()
67        };
68        let cleared = result.without_hits();
69        assert!(cleared.hits.is_empty());
70        assert_eq!(cleared.total, 42, "total 是分页前的全量匹配数,不能被清掉");
71    }
72}