1use 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
31pub const FIELD_TERM: &str = "term";
33pub const FIELD_KEY: &str = "key";
36pub const FIELD_PREDICATE: &str = "predicate";
38pub const FIELD_TEXT: &str = "text";
40pub const FIELD_TEXT_BEGIN: &str = "text_begin";
42pub const FIELD_TEXT_END: &str = "text_end";
44pub const FIELD_LANG: &str = "lang";
46
47pub const MAX_ANALYZED_TOKEN_BYTES: usize = 40;
52
53#[derive(Debug, Clone)]
55pub struct TextSchema {
56 pub schema: Schema,
58 pub term: Field,
60 pub key: Field,
62 pub predicate: Field,
64 pub text: Field,
66 pub text_begin: Field,
68 pub text_end: Field,
70 pub lang: Field,
72}
73
74pub 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 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 .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
142pub 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 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 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
196pub 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
206pub 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
239pub 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 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 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}