Skip to main content

waratah_text_index/
query.rs

1//! Candidate queries for the three search modes.
2//!
3//! - `FTS` parses a Jena/Lucene-style query string over the analyzed `text`
4//!   field.
5//! - `PREFIX` asks "the stored prefix starts with this seed" through a
6//!   literal-prefix [`RegexQuery`] over `text_begin`. A literal prefix is a
7//!   contiguous range of the sorted term dictionary, so the FST walk only
8//!   visits terms under the seed.
9//! - `SUFFIX` is the same query over the reversed `text_end` field, with the
10//!   reversed seed. Without the reversal a suffix would have no automaton
11//!   prefix and the walk would cover the whole dictionary.
12//!
13//! Seeds are truncated to the configured character count. For patterns within
14//! that length the candidate set is exact; longer patterns are seeded with the
15//! leading (or trailing) characters and the residual FILTER decides.
16
17use tantivy::Index;
18use tantivy::query::{BooleanQuery, Occur, Query, QueryParser, RegexQuery, TermQuery};
19use tantivy::schema::IndexRecordOption;
20use tantivy::schema::Term;
21use waratah_storage::text_index::{TextCandidateMode, TextSearchRequest};
22
23use crate::doc::{prefix_seed, suffix_pattern_seed_reversed};
24use crate::error::TextIndexError;
25use crate::schema::{TextSchema, language_value};
26
27/// Build the query for `request`.
28///
29/// Empty patterns are an error rather than a match-everything query: an empty
30/// `STRSTARTS` pattern is true for every string, so rewriting it would produce
31/// a useless full drain.
32pub fn build_query(
33    index: &Index,
34    schema: &TextSchema,
35    seed_chars: usize,
36    request: &TextSearchRequest,
37) -> Result<Box<dyn Query>, TextIndexError> {
38    build_query_scoped(index, schema, seed_chars, request, &[])
39}
40
41/// [`build_query`] conjoined with a predicate-set filter on the stored
42/// predicate.
43///
44/// `predicates` are the encoded predicate bytes a document carries (the write
45/// path stores `encode_term_bytes` of the predicate term). The drain returns
46/// only literals that appear under at least one of them:
47///
48/// ```text
49/// Must( mode query ) ∧ Must( Should( term(p₁), …, term(pₙ) ) )
50/// ```
51///
52/// The inner `BooleanQuery` holds only `Should` clauses, and Tantivy defaults
53/// a should-only boolean to `minimum_number_should_match = 1` (the
54/// Elasticsearch convention), so a document must carry one of the named
55/// predicates. An empty `predicates` means no predicate restriction: the mode
56/// query alone decides.
57///
58/// The subject resolve passes the request's whole predicate set in one call.
59/// A literal has one text/lang/seed analysis regardless of which predicate it
60/// appears under, so the union of per-predicate drains is exactly this one
61/// query, and the same set then scopes the OPSG walk.
62pub fn build_query_scoped(
63    index: &Index,
64    schema: &TextSchema,
65    seed_chars: usize,
66    request: &TextSearchRequest,
67    predicates: &[Vec<u8>],
68) -> Result<Box<dyn Query>, TextIndexError> {
69    let query: Box<dyn Query> = match request.mode {
70        TextCandidateMode::Fts => {
71            if request.query.trim().is_empty() {
72                return Err(TextIndexError::EmptyPattern);
73            }
74            let parser = QueryParser::for_index(index, vec![schema.text]);
75            let parsed = parser.parse_query(&request.query)?;
76            match request.language.as_deref() {
77                None => parsed,
78                Some(language) => {
79                    let term = Term::from_field_text(schema.lang, language_value(Some(language)));
80                    let language_query: Box<dyn Query> =
81                        Box::new(TermQuery::new(term, IndexRecordOption::Basic));
82                    Box::new(BooleanQuery::new(vec![
83                        (Occur::Must, parsed),
84                        (Occur::Must, language_query),
85                    ]))
86                }
87            }
88        }
89        TextCandidateMode::Prefix => {
90            let seed =
91                prefix_seed(&request.query, seed_chars).ok_or(TextIndexError::EmptyPattern)?;
92            Box::new(RegexQuery::from_pattern(&anchor(seed), schema.text_begin)?)
93        }
94        TextCandidateMode::Suffix => {
95            let seed = suffix_pattern_seed_reversed(&request.query, seed_chars)
96                .ok_or(TextIndexError::EmptyPattern)?;
97            Box::new(RegexQuery::from_pattern(&anchor(&seed), schema.text_end)?)
98        }
99    };
100    if predicates.is_empty() {
101        return Ok(query);
102    }
103    let predicate_queries: Vec<(Occur, Box<dyn Query>)> = predicates
104        .iter()
105        .map(|predicate| {
106            let term = Term::from_field_bytes(schema.predicate, predicate);
107            let predicate_query: Box<dyn Query> =
108                Box::new(TermQuery::new(term, IndexRecordOption::Basic));
109            (Occur::Should, predicate_query)
110        })
111        .collect();
112    let predicate_query: Box<dyn Query> = Box::new(BooleanQuery::new(predicate_queries));
113    Ok(Box::new(BooleanQuery::new(vec![
114        (Occur::Must, query),
115        (Occur::Must, predicate_query),
116    ])))
117}
118
119/// A literal-prefix pattern.
120///
121/// `tantivy-fst`'s regex parser rejects zero-width assertions (`^`, `$`) — the
122/// automaton matches the whole term, so the pattern is implicitly anchored at
123/// the start and needs no `^`. The trailing `.*` makes it a prefix rather than
124/// an exact-term match. A literal prefix leaves the automaton with a definite
125/// prefix, which is what lets the FST walk seek instead of scanning.
126fn anchor(seed: &str) -> String {
127    format!("{}.*", regex::escape(seed))
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133    use crate::index::{TextIndex, TextIndexOptions};
134    use waratah_storage::text_index::{DEFAULT_ANALYZER, TextIndexDoc};
135
136    /// Literals chosen so every regex metacharacter we care about appears in a
137    /// seed. This is the escaping probe: Tantivy's regex parser is not the
138    /// `regex` crate's, so an escaped seed must be accepted and must match the
139    /// document term literally.
140    const TRICKY: &[&str] = &[
141        "a.b", "a-b", "a+b", "a*b", "a?b", "(x)", "[y]", "{z}", "a|b", "a\\b", "a#b", "a&b", "a~b",
142        "a$b", "a^b", "a b", "héllo", "🌳tree", "plain",
143    ];
144
145    fn index_with(literals: &[&str], seed_chars: usize) -> TextIndex {
146        let options = TextIndexOptions::new(DEFAULT_ANALYZER, seed_chars, "text-index-v1;test");
147        let index = TextIndex::create_in_ram(&options).unwrap();
148        let docs: Vec<TextIndexDoc> = literals
149            .iter()
150            .enumerate()
151            .map(|(i, literal)| TextIndexDoc::new(vec![i as u8], *literal, None))
152            .collect();
153        index.add_batch(&docs).unwrap();
154        index
155    }
156
157    fn terms_sorted(index: &TextIndex, request: TextSearchRequest) -> Vec<Vec<u8>> {
158        let mut terms = index.search(&request).unwrap();
159        terms.sort();
160        terms
161    }
162
163    #[test]
164    fn every_tricky_seed_is_accepted_and_matches_literally() {
165        // seed_chars large enough to hold the whole literal, so the candidate
166        // set is exact.
167        let index = index_with(TRICKY, 16);
168        for (i, literal) in TRICKY.iter().enumerate() {
169            let expected = vec![vec![i as u8]];
170            assert_eq!(
171                terms_sorted(&index, TextSearchRequest::prefix(*literal)),
172                expected,
173                "prefix seed {literal:?} must match its own document literally"
174            );
175            // A prefix of the literal must match it too.
176            let chars: Vec<char> = literal.chars().collect();
177            if let Some(first) = chars.first() {
178                let seed: String = first.to_string();
179                let got = terms_sorted(&index, TextSearchRequest::prefix(seed.clone()));
180                assert!(
181                    got.contains(&vec![i as u8]),
182                    "prefix seed {seed:?} must match literal {literal:?}"
183                );
184            }
185        }
186    }
187
188    #[test]
189    fn suffix_seed_matches_the_reversed_stored_suffix() {
190        let index = index_with(TRICKY, 16);
191        for (i, literal) in TRICKY.iter().enumerate() {
192            let chars: Vec<char> = literal.chars().collect();
193            let tail: String = chars[chars.len().saturating_sub(2)..].iter().collect();
194            let got = terms_sorted(&index, TextSearchRequest::suffix(tail.clone()));
195            assert!(
196                got.contains(&vec![i as u8]),
197                "suffix seed {tail:?} must match literal {literal:?}"
198            );
199        }
200    }
201
202    #[test]
203    fn prefix_candidates_are_exact_within_the_seed_length() {
204        let literals = ["abcdef", "abcxyz", "ab", "zzz"];
205        let index = index_with(&literals, 4);
206        // |p| <= N: the candidate set is exactly the matching literals.
207        for (pattern, expected) in [
208            ("abc", vec![0u8, 1]),
209            ("abcd", vec![0u8]),
210            ("ab", vec![0u8, 1, 2]),
211            ("zz", vec![3u8]),
212            ("zzz", vec![3u8]),
213        ] {
214            let mut expected: Vec<Vec<u8>> = expected.into_iter().map(|t| vec![t]).collect();
215            expected.sort();
216            assert_eq!(
217                terms_sorted(&index, TextSearchRequest::prefix(pattern)),
218                expected,
219                "pattern {pattern:?}"
220            );
221        }
222    }
223
224    #[test]
225    fn long_patterns_are_a_sound_superset() {
226        // N = 2, pattern 4 chars: seeded with the first 2 chars, so the
227        // candidate set is a superset. Every exact match must be present.
228        let literals = ["abcdef", "abzzz", "xy"];
229        let index = index_with(&literals, 2);
230        let got = terms_sorted(&index, TextSearchRequest::prefix("abcd"));
231        assert!(
232            got.contains(&vec![0u8]),
233            "exact match must be in the superset: {got:?}"
234        );
235        // The superset may also contain the other "ab" literal.
236        assert!(!got.contains(&vec![2u8]));
237    }
238
239    #[test]
240    fn empty_patterns_and_queries_are_rejected() {
241        let index = index_with(&["a"], 4);
242        assert!(matches!(
243            index.search(&TextSearchRequest::prefix("")),
244            Err(TextIndexError::EmptyPattern)
245        ));
246        assert!(matches!(
247            index.search(&TextSearchRequest::suffix("")),
248            Err(TextIndexError::EmptyPattern)
249        ));
250        assert!(matches!(
251            index.search(&TextSearchRequest::fts("   ")),
252            Err(TextIndexError::EmptyPattern)
253        ));
254    }
255
256    #[test]
257    fn fts_matches_tokens_and_phrases_and_respects_language() {
258        let index = index_with(&[], 16);
259        let docs = vec![
260            TextIndexDoc::new(vec![1], "laser printer", None),
261            TextIndexDoc::new(vec![2], "ink printer", Some("en".to_owned())),
262            TextIndexDoc::new(vec![3], "imprimante laser", Some("fr".to_owned())),
263        ];
264        index.add_batch(&docs).unwrap();
265        assert_eq!(
266            terms_sorted(&index, TextSearchRequest::fts("printer")),
267            vec![vec![1u8], vec![2u8]]
268        );
269        assert_eq!(
270            terms_sorted(&index, TextSearchRequest::fts("\"laser printer\"")),
271            vec![vec![1u8]]
272        );
273        let mut french = TextSearchRequest::fts("laser");
274        french.language = Some("fr".to_owned());
275        assert_eq!(terms_sorted(&index, french), vec![vec![3u8]]);
276        let mut none_lang = TextSearchRequest::fts("printer");
277        none_lang.language = Some(waratah_storage::text_index::LANG_NONE.to_owned());
278        assert_eq!(terms_sorted(&index, none_lang), vec![vec![1u8]]);
279    }
280
281    #[test]
282    fn candidate_limit_is_an_error_not_a_truncation() {
283        let index = index_with(&["aa", "ab", "ac", "ad"], 4);
284        let mut request = TextSearchRequest::prefix("a");
285        request.limit = 2;
286        assert!(matches!(
287            index.search(&request),
288            Err(TextIndexError::CandidateLimitExceeded { limit: 2 })
289        ));
290    }
291
292    #[test]
293    fn the_candidate_limit_is_a_global_distinct_count_across_segments() {
294        // Tantivy commits one segment per batch: two disjoint batches give
295        // two segments, each holding at most `limit` distinct terms. The old
296        // per-segment accounting ORed the per-segment flags and returned
297        // `2 × limit` terms silently; the limit is over the MERGED union.
298        let options = TextIndexOptions::new(DEFAULT_ANALYZER, 8, "text-index-v1;test");
299        let index = TextIndex::create_in_ram(&options).unwrap();
300        index
301            .add_batch(&[
302                TextIndexDoc::new(vec![1], "aa".to_owned(), None),
303                TextIndexDoc::new(vec![2], "ab".to_owned(), None),
304            ])
305            .unwrap();
306        index
307            .add_batch(&[
308                TextIndexDoc::new(vec![3], "ac".to_owned(), None),
309                TextIndexDoc::new(vec![4], "ad".to_owned(), None),
310            ])
311            .unwrap();
312        let mut request = TextSearchRequest::prefix("a");
313        request.limit = 3;
314        // Each segment holds 2 ≤ 3 distinct terms; the union holds 4 > 3.
315        assert!(matches!(
316            index.search(&request),
317            Err(TextIndexError::CandidateLimitExceeded { limit: 3 })
318        ));
319        // Exactly at the limit: no error, all four terms.
320        request.limit = 4;
321        assert_eq!(
322            terms_sorted(&index, request),
323            vec![vec![1], vec![2], vec![3], vec![4]]
324        );
325        // Unlimited (the planner's request): never an error.
326        let mut unlimited = TextSearchRequest::prefix("a");
327        unlimited.limit = 0;
328        assert_eq!(terms_sorted(&index, unlimited).len(), 4);
329    }
330}