Skip to main content

waratah_text_index/
schema.rs

1//! Tantivy schema for the text index.
2//!
3//! One document per distinct string-literal term:
4//!
5//! | field | type | content |
6//! |---|---|---|
7//! | `term` | bytes, fast | encoded `EncodedTerm`; the candidate payload |
8//! | `text` | text, configured analyzer | full lexical, for `text:query` |
9//! | `text_begin` | text, raw tokenizer | first `seed_chars` characters |
10//! | `text_end` | text, raw tokenizer | **reversed** last `seed_chars` characters |
11//! | `lang` | text, raw tokenizer | language tag, or [`LANG_NONE`] |
12//!
13//! `text_begin` and `text_end` hold whole strings, not tokens, so a prefix
14//! query over them is string-prefix matching. The suffix field is reversed so
15//! that a suffix query is a prefix query on the reversed seed and the FST term
16//! dictionary can seek it; without the reversal a suffix query would have to
17//! walk the whole term dictionary.
18
19use tantivy::Index;
20use tantivy::schema::{
21    BytesOptions, Field, FieldType, IndexRecordOption, Schema, TextFieldIndexing, TextOptions,
22};
23use tantivy::tokenizer::{
24    Language, LowerCaser, RawTokenizer, RemoveLongFilter, SimpleTokenizer, Stemmer, TextAnalyzer,
25    WhitespaceTokenizer,
26};
27use waratah_storage::text_index::{LANG_NONE, RAW_TOKENIZER, registered_analyzer};
28
29use crate::error::TextIndexError;
30
31/// Encoded term bytes (fast field).
32pub const FIELD_TERM: &str = "term";
33/// Logical document identity `(predicate, literal)` (indexed; `delete_term`
34/// target for the upsert).
35pub const FIELD_KEY: &str = "key";
36/// Encoded predicate term (indexed; the predicate-scoping dimension).
37pub const FIELD_PREDICATE: &str = "predicate";
38/// Analyzed full lexical, used by `text:query`.
39pub const FIELD_TEXT: &str = "text";
40/// Bounded forward prefix of the lexical.
41pub const FIELD_TEXT_BEGIN: &str = "text_begin";
42/// Bounded reversed suffix of the lexical.
43pub const FIELD_TEXT_END: &str = "text_end";
44/// Language tag (raw), or [`LANG_NONE`].
45pub const FIELD_LANG: &str = "lang";
46
47/// Longest token the analyzers emit, in bytes. Tokens longer than this are
48/// dropped, which is the standard full-text behaviour for unbroken blobs and
49/// only affects `text:query` (the bounded prefix/suffix fields are raw and
50/// truncated to the seed length separately).
51pub const MAX_ANALYZED_TOKEN_BYTES: usize = 40;
52
53/// Resolved fields of one index, so callers never look them up by name.
54#[derive(Debug, Clone)]
55pub struct TextSchema {
56    /// The underlying schema handed to Tantivy.
57    pub schema: Schema,
58    /// Encoded term bytes.
59    pub term: Field,
60    /// `(predicate, literal)` document identity.
61    pub key: Field,
62    /// Encoded predicate term.
63    pub predicate: Field,
64    /// Analyzed full lexical.
65    pub text: Field,
66    /// Bounded forward prefix.
67    pub text_begin: Field,
68    /// Bounded reversed suffix.
69    pub text_end: Field,
70    /// Language tag.
71    pub lang: Field,
72}
73
74/// Build the schema for `analyzer` (a menu value of
75/// [`waratah_storage::text_index::ANALYZERS`]).
76pub fn build(analyzer: &str) -> Result<TextSchema, TextIndexError> {
77    let tokenizer = registered_analyzer(analyzer).ok_or_else(|| {
78        let names: Vec<&str> = waratah_storage::text_index::ANALYZERS
79            .iter()
80            .map(|(name, _)| *name)
81            .collect();
82        TextIndexError::Config(format!(
83            "unknown analyzer {analyzer:?}; expected one of {}",
84            names.join(", ")
85        ))
86    })?;
87
88    let mut builder = Schema::builder();
89    let term = builder.add_bytes_field(FIELD_TERM, BytesOptions::default().set_fast());
90    // The identity is indexed so `add_batch` can `delete_term` it before the
91    // add (the upsert that keeps the index at one document per pair across
92    // chunks and restarts). The predicate is indexed for query-side scoping.
93    let key = builder.add_bytes_field(FIELD_KEY, BytesOptions::default().set_indexed());
94    let predicate = builder.add_bytes_field(FIELD_PREDICATE, BytesOptions::default().set_indexed());
95    let text = builder.add_text_field(
96        FIELD_TEXT,
97        TextOptions::default().set_indexing_options(
98            TextFieldIndexing::default()
99                .set_tokenizer(tokenizer)
100                .set_index_option(IndexRecordOption::WithFreqsAndPositions)
101                // No scoring: the collector never asks for a score, so the
102                // per-document fieldnorm column is dead weight.
103                .set_fieldnorms(false),
104        ),
105    );
106    let text_begin = builder.add_text_field(
107        FIELD_TEXT_BEGIN,
108        TextOptions::default().set_indexing_options(
109            TextFieldIndexing::default()
110                .set_tokenizer(RAW_TOKENIZER)
111                .set_index_option(IndexRecordOption::Basic),
112        ),
113    );
114    let text_end = builder.add_text_field(
115        FIELD_TEXT_END,
116        TextOptions::default().set_indexing_options(
117            TextFieldIndexing::default()
118                .set_tokenizer(RAW_TOKENIZER)
119                .set_index_option(IndexRecordOption::Basic),
120        ),
121    );
122    let lang = builder.add_text_field(
123        FIELD_LANG,
124        TextOptions::default().set_indexing_options(
125            TextFieldIndexing::default()
126                .set_tokenizer(RAW_TOKENIZER)
127                .set_index_option(IndexRecordOption::Basic),
128        ),
129    );
130    Ok(TextSchema {
131        schema: builder.build(),
132        term,
133        key,
134        predicate,
135        text,
136        text_begin,
137        text_end,
138        lang,
139    })
140}
141
142/// Resolve the schema of an already-open index.
143///
144/// The directory is authoritative: it carries the schema the documents were
145/// built with, so reopening never has to reconstruct it from configuration.
146pub fn from_index(index: &Index) -> Result<TextSchema, TextIndexError> {
147    let schema = index.schema();
148    let resolve = |name: &str| -> Result<Field, TextIndexError> {
149        schema
150            .get_field(name)
151            .map_err(|_| TextIndexError::SchemaMismatch)
152    };
153    let resolved = TextSchema {
154        term: resolve(FIELD_TERM)?,
155        key: resolve(FIELD_KEY)?,
156        predicate: resolve(FIELD_PREDICATE)?,
157        text: resolve(FIELD_TEXT)?,
158        text_begin: resolve(FIELD_TEXT_BEGIN)?,
159        text_end: resolve(FIELD_TEXT_END)?,
160        lang: resolve(FIELD_LANG)?,
161        schema: schema.clone(),
162    };
163    // Reject a directory that is not ours or was built by an incompatible
164    // layout before it is indexed into or searched.
165    let is_text = |field: Field| {
166        matches!(
167            resolved.schema.get_field_entry(field).field_type(),
168            FieldType::Str(options) if options.get_indexing_options().is_some()
169        )
170    };
171    if !is_text(resolved.text)
172        || !is_text(resolved.text_begin)
173        || !is_text(resolved.text_end)
174        || !is_text(resolved.lang)
175    {
176        return Err(TextIndexError::SchemaMismatch);
177    }
178    let term_ok = matches!(
179        resolved.schema.get_field_entry(resolved.term).field_type(),
180        FieldType::Bytes(options) if options.is_fast()
181    );
182    // Both identity fields must be indexed: `delete_term` silently no-ops on
183    // an unindexed field, which would leave duplicates instead of upserting.
184    let keyed = |field: Field| {
185        matches!(
186            resolved.schema.get_field_entry(field).field_type(),
187            FieldType::Bytes(options) if options.is_indexed()
188        )
189    };
190    if !term_ok || !keyed(resolved.key) || !keyed(resolved.predicate) {
191        return Err(TextIndexError::SchemaMismatch);
192    }
193    Ok(resolved)
194}
195
196/// The tokenizer name of the analyzed text field.
197pub fn text_tokenizer(schema: &TextSchema) -> Option<&str> {
198    match schema.schema.get_field_entry(schema.text).field_type() {
199        FieldType::Str(options) => options
200            .get_indexing_options()
201            .map(TextFieldIndexing::tokenizer),
202        _ => None,
203    }
204}
205
206/// Register the analyzer menu on `index`.
207///
208/// Called on every create and every open: the tokenizer manager is per
209/// [`Index`] in memory, so the names must be present before indexing or
210/// searching. The menu is Waratah-owned so a Tantivy upgrade cannot change the
211/// analysis of an existing index under it.
212pub fn register_analyzers(index: &Index) {
213    let tokenizers = index.tokenizers();
214    tokenizers.register(
215        "waratah_simple",
216        TextAnalyzer::builder(SimpleTokenizer::default())
217            .filter(RemoveLongFilter::limit(MAX_ANALYZED_TOKEN_BYTES))
218            .filter(LowerCaser)
219            .build(),
220    );
221    tokenizers.register(
222        "waratah_en_stem",
223        TextAnalyzer::builder(SimpleTokenizer::default())
224            .filter(RemoveLongFilter::limit(MAX_ANALYZED_TOKEN_BYTES))
225            .filter(LowerCaser)
226            .filter(Stemmer::new(Language::English))
227            .build(),
228    );
229    tokenizers.register(
230        "waratah_whitespace",
231        TextAnalyzer::builder(WhitespaceTokenizer::default())
232            .filter(RemoveLongFilter::limit(MAX_ANALYZED_TOKEN_BYTES))
233            .filter(LowerCaser)
234            .build(),
235    );
236    tokenizers.register(RAW_TOKENIZER, RawTokenizer::default());
237}
238
239/// The sentinel stored in `lang` for a literal without a language tag.
240pub fn language_value(language: Option<&str>) -> &str {
241    language.unwrap_or(LANG_NONE)
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247    use waratah_storage::text_index::DEFAULT_ANALYZER;
248
249    #[test]
250    fn schema_has_the_seven_fields_and_no_others() {
251        let built = build(DEFAULT_ANALYZER).unwrap();
252        assert_eq!(built.schema.fields().count(), 7);
253        for name in [
254            FIELD_TERM,
255            FIELD_KEY,
256            FIELD_PREDICATE,
257            FIELD_TEXT,
258            FIELD_TEXT_BEGIN,
259            FIELD_TEXT_END,
260            FIELD_LANG,
261        ] {
262            assert!(built.schema.get_field(name).is_ok(), "missing {name}");
263        }
264        assert_eq!(built.schema.get_field(FIELD_TERM).unwrap(), built.term);
265        assert_eq!(
266            built.schema.get_field(FIELD_PREDICATE).unwrap(),
267            built.predicate
268        );
269        assert_eq!(built.schema.get_field(FIELD_TEXT).unwrap(), built.text);
270    }
271
272    #[test]
273    fn seed_fields_use_the_raw_tokenizer_and_the_text_field_uses_the_analyzer() {
274        let built = build(DEFAULT_ANALYZER).unwrap();
275        assert_eq!(
276            text_tokenizer(&built),
277            registered_analyzer(DEFAULT_ANALYZER)
278        );
279        for field in [built.text_begin, built.text_end, built.lang] {
280            let indexing = match built.schema.get_field_entry(field).field_type() {
281                FieldType::Str(options) => {
282                    options.get_indexing_options().expect("indexed").tokenizer()
283                }
284                other => panic!("expected text field, got {other:?}"),
285            };
286            assert_eq!(indexing, RAW_TOKENIZER);
287        }
288    }
289
290    #[test]
291    fn unknown_analyzer_is_an_error() {
292        assert!(matches!(build("klingon"), Err(TextIndexError::Config(_))));
293    }
294
295    #[test]
296    fn every_menu_analyzer_builds() {
297        for (name, _) in waratah_storage::text_index::ANALYZERS {
298            let built = build(name).unwrap();
299            assert_eq!(built.schema.fields().count(), 7);
300        }
301    }
302
303    #[test]
304    fn from_index_resolves_the_fields_of_an_opened_index() {
305        let built = build(DEFAULT_ANALYZER).unwrap();
306        let index = Index::create_in_ram(built.schema.clone());
307        let resolved = from_index(&index).unwrap();
308        assert_eq!(resolved.term, built.term);
309        assert_eq!(resolved.text, built.text);
310        assert_eq!(resolved.text_begin, built.text_begin);
311        assert_eq!(resolved.text_end, built.text_end);
312        assert_eq!(resolved.lang, built.lang);
313    }
314
315    /// A schema shaped like ours except for the predicate field, so a refusal
316    /// test fails for the predicate reason and not because another field is
317    /// missing or mistyped.
318    fn schema_with_predicate(predicate: Option<BytesOptions>) -> Schema {
319        let mut builder = Schema::builder();
320        builder.add_bytes_field(FIELD_TERM, BytesOptions::default().set_fast());
321        builder.add_bytes_field(FIELD_KEY, BytesOptions::default().set_indexed());
322        if let Some(options) = predicate {
323            builder.add_bytes_field(FIELD_PREDICATE, options);
324        }
325        for name in [FIELD_TEXT, FIELD_TEXT_BEGIN, FIELD_TEXT_END, FIELD_LANG] {
326            builder.add_text_field(
327                name,
328                TextOptions::default().set_indexing_options(
329                    TextFieldIndexing::default()
330                        .set_tokenizer(RAW_TOKENIZER)
331                        .set_index_option(IndexRecordOption::Basic),
332                ),
333            );
334        }
335        builder.build()
336    }
337
338    #[test]
339    fn from_index_refuses_a_schema_without_the_predicate_field() {
340        let index = Index::create_in_ram(schema_with_predicate(None));
341        assert!(matches!(
342            from_index(&index),
343            Err(TextIndexError::SchemaMismatch)
344        ));
345    }
346
347    #[test]
348    fn from_index_refuses_an_unindexed_predicate_field() {
349        // An unindexed bytes field cannot answer the predicate term query, so
350        // every subject resolve would silently drain nothing.
351        let index = Index::create_in_ram(schema_with_predicate(Some(BytesOptions::default())));
352        assert!(matches!(
353            from_index(&index),
354            Err(TextIndexError::SchemaMismatch)
355        ));
356    }
357}