Skip to main content

waratah_text_index/
doc.rs

1//! Tantivy document assembly and the bounded seeds derived from a lexical form.
2//!
3//! The partition derives the two bounded fields from the lexical it receives;
4//! the write path therefore carries only the encoded term, the lexical and the
5//! language tag.
6
7use tantivy::TantivyDocument;
8use waratah_storage::text_index::TextIndexDoc;
9
10use crate::schema::{TextSchema, language_value};
11
12/// Materialize the Tantivy document for `doc`.
13pub fn to_tantivy(doc: &TextIndexDoc, schema: &TextSchema, seed_chars: usize) -> TantivyDocument {
14    let mut document = TantivyDocument::new();
15    document.add_bytes(schema.term, &doc.term);
16    document.add_bytes(
17        schema.key,
18        &waratah_storage::text_index::text_index_key(&doc.predicate, &doc.term),
19    );
20    if !doc.predicate.is_empty() {
21        document.add_bytes(schema.predicate, &doc.predicate);
22    }
23    document.add_text(schema.text, &doc.lexical);
24    if let Some(prefix) = prefix_seed(&doc.lexical, seed_chars) {
25        document.add_text(schema.text_begin, prefix);
26    }
27    if let Some(suffix) = suffix_seed_reversed(&doc.lexical, seed_chars) {
28        document.add_text(schema.text_end, suffix);
29    }
30    document.add_text(schema.lang, language_value(doc.language.as_deref()));
31    document
32}
33
34/// First `seed_chars` characters of `lexical`, or `None` when it is empty.
35///
36/// Truncation is by `char`, never by byte: a byte slice could split a UTF-8
37/// sequence and produce a term that neither indexes nor compares correctly.
38pub fn prefix_seed(lexical: &str, seed_chars: usize) -> Option<&str> {
39    if lexical.is_empty() {
40        return None;
41    }
42    let mut chars = lexical.char_indices();
43    if let Some((end, _)) = chars.nth(seed_chars) {
44        return Some(&lexical[..end]);
45    }
46    Some(lexical)
47}
48
49/// The last `seed_chars` characters of `lexical`, reversed.
50///
51/// Reversing turns "ends with X" into "starts with reverse(X)", which the term
52/// dictionary can seek. `chars().rev()` reverses characters, so the result is
53/// valid UTF-8.
54pub fn suffix_seed_reversed(lexical: &str, seed_chars: usize) -> Option<String> {
55    if lexical.is_empty() {
56        return None;
57    }
58    Some(lexical.chars().rev().take(seed_chars).collect())
59}
60
61/// The reversed seed for a suffix *pattern*: the last `seed_chars` characters
62/// of the pattern, reversed, so it can be used as a prefix on `text_end`.
63pub fn suffix_pattern_seed_reversed(pattern: &str, seed_chars: usize) -> Option<String> {
64    suffix_seed_reversed(pattern, seed_chars)
65}
66
67#[cfg(test)]
68mod tests {
69    use super::*;
70
71    #[test]
72    fn prefix_takes_characters_not_bytes() {
73        assert_eq!(prefix_seed("abcdef", 3), Some("abc"));
74        assert_eq!(prefix_seed("abcdef", 6), Some("abcdef"));
75        assert_eq!(prefix_seed("abcdef", 64), Some("abcdef"));
76        assert_eq!(prefix_seed("ab", 3), Some("ab"));
77        assert_eq!(prefix_seed("", 3), None);
78        // Multi-byte: 3 characters is 3 chars, not 3 bytes.
79        assert_eq!(prefix_seed("héllo", 3), Some("hél"));
80        assert_eq!(prefix_seed("🌳🌲🌵x", 3), Some("🌳🌲🌵"));
81    }
82
83    #[test]
84    fn suffix_is_reversed_and_char_safe() {
85        assert_eq!(suffix_seed_reversed("abcdef", 2).as_deref(), Some("fe"));
86        assert_eq!(suffix_seed_reversed("abcdef", 6).as_deref(), Some("fedcba"));
87        assert_eq!(suffix_seed_reversed("ab", 5).as_deref(), Some("ba"));
88        assert_eq!(suffix_seed_reversed("", 2), None);
89        assert_eq!(suffix_seed_reversed("héllo", 2).as_deref(), Some("ol"));
90        assert_eq!(suffix_seed_reversed("x🌳🌲", 2).as_deref(), Some("🌲🌳"));
91    }
92
93    #[test]
94    fn suffix_pattern_seed_matches_the_document_side() {
95        assert_eq!(
96            suffix_pattern_seed_reversed("ef", 2).as_deref(),
97            suffix_seed_reversed("abcdef", 2).as_deref()
98        );
99    }
100
101    #[test]
102    fn a_prefix_seed_of_the_pattern_matches_the_document_prefix_for_short_patterns() {
103        for literal in ["abcdef", "ab", "", "héllo", "🌳🌲🌵x"] {
104            let stored = prefix_seed(literal, 16).unwrap_or("");
105            for pattern in ["", "a", "ab", "abc", "é", "🌳", "zz"] {
106                assert_eq!(
107                    literal.starts_with(pattern),
108                    stored.starts_with(pattern),
109                    "literal={literal:?} pattern={pattern:?}"
110                );
111            }
112        }
113    }
114
115    #[test]
116    fn document_fields_follow_the_seed_length() {
117        let schema = crate::schema::build(waratah_storage::text_index::DEFAULT_ANALYZER).unwrap();
118        let doc = TextIndexDoc::new_with_predicate(
119            vec![1, 2, 3],
120            vec![7],
121            "The Quick Fox",
122            Some("en".to_owned()),
123        );
124        let built = to_tantivy(&doc, &schema, 8);
125        assert_eq!(
126            built.len(),
127            7,
128            "term, key, predicate, text, begin, end, lang"
129        );
130        let mut seen: Vec<&str> = built
131            .field_values()
132            .map(|(field, _)| match field {
133                f if f == schema.term => "term",
134                f if f == schema.key => "key",
135                f if f == schema.predicate => "predicate",
136                f if f == schema.text => "text",
137                f if f == schema.text_begin => "text_begin",
138                f if f == schema.text_end => "text_end",
139                f if f == schema.lang => "lang",
140                _ => "unknown",
141            })
142            .collect();
143        seen.sort_unstable();
144        assert_eq!(
145            seen,
146            [
147                "key",
148                "lang",
149                "predicate",
150                "term",
151                "text",
152                "text_begin",
153                "text_end"
154            ]
155        );
156    }
157
158    #[test]
159    fn empty_lexical_still_carries_the_term_and_the_language() {
160        let schema = crate::schema::build(waratah_storage::text_index::DEFAULT_ANALYZER).unwrap();
161        let doc = TextIndexDoc::new(vec![9], "", None);
162        let built = to_tantivy(&doc, &schema, 8);
163        assert_eq!(
164            built.len(),
165            4,
166            "an empty lexical seeds neither bounded field; the scratch document has no predicate"
167        );
168        assert!(built.get_first(schema.lang).is_some());
169        assert!(
170            built.get_first(schema.key).is_some(),
171            "the key is always present"
172        );
173    }
174}