Skip to main content

memory/
search.rs

1//! Full-text ranking without a model: the same query over the same
2//! memories always gives the same order.
3//!
4//! Text is split into words (runs of letters and digits, lowercased). A
5//! query word hits a memory word that equals it (2 points) or starts with
6//! it (1 point), weighted by where the word is: title 4, description 2,
7//! text and links 1. A memory that hits more distinct query words always
8//! ranks above one that hits fewer; then more points; then the newer;
9//! then the id.
10
11use crate::Memory;
12
13/// Lowercased words of `text`.
14pub fn words(text: &str) -> Vec<String> {
15    text.split(|c: char| !c.is_alphanumeric())
16        .filter(|w| !w.is_empty())
17        .map(str::to_lowercase)
18        .collect()
19}
20
21/// The score of `m` for the query words, or 0 when none hits.
22pub fn score(terms: &[String], m: &Memory) -> u32 {
23    let fields: [(u32, Vec<String>); 4] = [
24        (4, words(&m.title)),
25        (2, words(&m.description)),
26        (1, words(&m.text)),
27        (1, words(&m.links.join(" "))),
28    ];
29    let mut hit = 0u32;
30    let mut points = 0u32;
31    for t in terms {
32        let mut p = 0u32;
33        for (weight, ws) in &fields {
34            for w in ws {
35                if w == t {
36                    p += 2 * weight;
37                } else if w.starts_with(t.as_str()) {
38                    p += weight;
39                }
40            }
41        }
42        if p > 0 {
43            hit += 1;
44            points += p;
45        }
46    }
47    if hit == 0 {
48        0
49    } else {
50        hit * 1000 + points.min(999)
51    }
52}
53
54/// The best `limit` of `items` for `query`, each with its score. An empty
55/// query keeps every item, newest first, without scores.
56pub fn rank(query: &str, items: Vec<Memory>, limit: usize) -> Vec<Memory> {
57    let mut terms = words(query);
58    terms.sort();
59    terms.dedup();
60    let mut out: Vec<Memory> = if terms.is_empty() {
61        items
62    } else {
63        items
64            .into_iter()
65            .filter_map(|mut m| {
66                let s = score(&terms, &m);
67                (s > 0).then(|| {
68                    m.score = Some(s);
69                    m
70                })
71            })
72            .collect()
73    };
74    out.sort_by(|a, b| {
75        b.score
76            .cmp(&a.score)
77            .then(b.updated_unix_ms.cmp(&a.updated_unix_ms))
78            .then(a.id.cmp(&b.id))
79    });
80    out.truncate(limit);
81    out
82}
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87    use crate::{Kind, Scope};
88
89    fn m(id: &str, title: &str, text: &str, updated: u64) -> Memory {
90        Memory {
91            id: id.into(),
92            scope: Scope::User,
93            kind: Kind::User,
94            title: title.into(),
95            description: String::new(),
96            text: text.into(),
97            links: vec![],
98            created_unix_ms: 0,
99            updated_unix_ms: updated,
100            path: None,
101            score: None,
102        }
103    }
104
105    #[test]
106    fn more_words_beat_more_points_and_ties_go_to_the_newer() {
107        let items = vec![
108            m("user/a", "tabs tabs tabs", "", 1),
109            m("user/b", "", "tabs and spaces", 1),
110            m("user/c", "", "tabs and spaces", 2),
111            m("user/d", "", "nothing here", 3),
112        ];
113        let ids: Vec<String> = rank("Spaces TABS", items.clone(), 10)
114            .into_iter()
115            .map(|m| m.id)
116            .collect();
117        assert_eq!(ids, ["user/c", "user/b", "user/a"]);
118        // A prefix hits too; an empty query lists the newest first.
119        assert_eq!(rank("spa", items.clone(), 1)[0].id, "user/c");
120        let all = rank("  ", items, 2);
121        assert_eq!(all.len(), 2);
122        assert_eq!(all[0].id, "user/d");
123        assert_eq!(all[0].score, None);
124    }
125}