rlucene 0.1.0-alpha.3

A Rust port of Apache Lucene, a full-text search engine library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
use crate::core::index::index_reader::Identity;
use crate::core::index::index_reader_context::IndexReaderContext;
use crate::core::index::terms::{Terms, TermsPosting};
use crate::core::index::terms_enum::TermsEnum;
use crate::core::search::automaton_query::AutomatonQuery;
use crate::core::search::fuzzy_query::FuzzyQuery;
use crate::core::search::index_searcher::IndexSearcher;
use crate::core::search::multi_term_query_constant_score_blended_wrapper::MultiTermQueryConstantScoreBlendedWrapper;
use crate::core::search::multi_term_query_constant_score_wrapper::MultiTermQueryConstantScoreWrapper;
use crate::core::search::prefix_query::PrefixQuery;
use crate::core::search::query::{IntoQuery, Query, QueryBase, QueryWeight};
use crate::core::search::query_visitor::QueryVisitor;
use crate::core::search::regexp_query::RegexpQuery;
use crate::core::search::score_mode::ScoreMode;
use crate::core::search::similarities_impl::similarities::Similarity;
use crate::core::search::term_in_set_query::TermInSetQuery;
use crate::core::search::term_range_query::TermRangeQuery;
use crate::core::search::wildcard_query::WildcardQuery;
use crate::core::util::HasIdentity;
use crate::core::util::accountable::Accountable;
use crate::core::util::error::lucene_error::Result;
use crate::impl_from_for_enum;
#[cfg(test)]
use crate::test_framework::core::search::multi_term::BoostCheckingQuery;
#[cfg(test)]
use crate::test_framework::core::search::multi_term::DumbPrefixQuery;
#[cfg(test)]
use crate::test_framework::core::search::multi_term::DumbRegexpQuery;
use std::fmt::Debug;
use std::sync::Arc;
/// A [`Query`] trait that matches documents containing a subset of terms provided by a
/// [`FilteredTermsEnum`](crate::core::index::filtered_terms_enum::FilteredTermsEnum) enumeration.
///
/// This query cannot be used directly; implement the trait and define
/// [`MultiTermQuery::get_terms_enum`] to provide a [`FilteredTermsEnum`](crate::core::index::filtered_terms_enum::FilteredTermsEnum) that iterates
/// through the terms to be matched.
///
/// **NOTE**: if [`RewriteMethod`] is either [`CONSTANT_SCORE_BOOLEAN_REWRITE`] or
/// [`SCORING_BOOLEAN_REWRITE`], you may encounter a
/// [`LuceneErrorKind::TooManyClauses`](crate::core::util::error::lucene_error::LuceneErrorKind::TooManyClauses)
/// error during searching, which happens when the number of terms to be searched exceeds
/// [`index_searcher::get_max_clause_count`]. Setting [`RewriteMethod`]
/// to [`ConstantScoreBlendedRewrite`] or [`ConstantScoreRewrite`] prevents this.
///
/// The recommended rewrite method is [`ConstantScoreBlendedRewrite`]: it doesn't
/// spend CPU computing unhelpful scores, and is the most performant rewrite method given the query.
/// If you need scoring (like [`FuzzyQuery`], use [`TopTermsScoringBooleanQueryRewrite`] which uses
/// a priority queue to only collect competitive terms and not hit this limitation.
///
/// Note that org.apache.lucene.queryparser.classic.QueryParser produces MultiTermQueries using
/// [`ConstantScoreRewrite`] by default.
pub trait MultiTermQuery: QueryBase + Clone {
  /// Returns the field name for this query
  fn get_field(&self) -> &str;
  type TermsEnum<T>: TermsEnum<PostingsEnum = TermsPosting<T>>
  where
    T: Terms;
  /// Construct the enumeration to be used, expanding the pattern term. This method should only be
  /// called if the field exists (ie, implementations can assume the field does exist). This method
  /// should not return `None` (should instead return [`EmptyTermsEnum`](crate::core::index::terms_enum::EmptyTermsEnum) if no terms match). The
  /// [`TermsEnum`] must already be positioned to the first matching term. The given
  /// [`AttributeSource`](crate::core::util::attribute_source::AttributeSource) is passed by the
  /// [`RewriteMethod`] to share information
  /// between segments; for example, top-terms rewrite implementations use it to share maximum
  /// competitive boosts.
  fn get_terms_enum<T>(&self, terms: T) -> Result<Self::TermsEnum<T>>
  where
    T: Terms + Clone;
  /// Return the number of unique terms contained in this query, if known up-front. If not known, -1 will be returned.
  fn get_terms_count(&self) -> i64 {
    -1
  }

  fn to_query(&self) -> Query;
}
/// Trait defining how the query is rewritten.
pub trait RewriteMethod {
  fn rewrite<IRC, Q, SIM>(
    &self,
    index_searcher: &IndexSearcher<IRC, SIM>,
    query: &Q,
  ) -> Result<Query>
  where
    SIM: Similarity,
    Q: MultiTermQuery + Into<MultiTermQuerySet>,
    IRC: IndexReaderContext + 'static,
    IndexSearcher<IRC, SIM>: Sync;
  /// Returns the [`MultiTermQuery`]s [`TermsEnum`].
  ///
  /// See [`MultiTermQuery::get_terms_enum`].
  fn get_terms_enum<M, T>(&self, query: &M, terms: T) -> Result<<M as MultiTermQuery>::TermsEnum<T>>
  where
    M: MultiTermQuery,
    T: Terms + Clone,
  {
    query.get_terms_enum(terms)
  }
}
/// A rewrite method where documents are assigned a constant score equal to the query's boost.
/// Maintains a boolean query-like implementation over the most costly terms while pre-processing
/// the less costly terms into a filter bitset. Enforces an upper-limit on the number of terms
/// allowed in the boolean query-like implementation.
///
/// This method aims to balance the benefits of both [`ConstantScoreRewrite`] and
/// [`ConstantScoreRewrite`] by enabling skipping and early termination over costly terms
/// while limiting the overhead of a BooleanQuery with many terms. It also ensures you cannot hit
/// [`LuceneErrorKind::TooManyClauses`](crate::core::util::error::lucene_error::LuceneErrorKind::TooManyClauses).
/// For some use-cases with all low
/// cost terms, [`ConstantScoreRewrite`] may be more performant. While for some use-cases
/// with all high cost terms, `ConstantScoreBooleanRewrite` may be better.
#[derive(Default, Clone, Debug, PartialEq, Eq, Hash)]
pub struct ConstantScoreBlendedRewrite;
impl RewriteMethod for ConstantScoreBlendedRewrite {
  fn rewrite<IRC, Q, SIM>(
    &self,
    _index_searcher: &IndexSearcher<IRC, SIM>,
    query: &Q,
  ) -> Result<Query>
  where
    SIM: Similarity,
    Q: MultiTermQuery + Into<MultiTermQuerySet>,
    IRC: IndexReaderContext + 'static,
    IndexSearcher<IRC, SIM>: Sync,
  {
    Ok(MultiTermQueryConstantScoreBlendedWrapper::new(query.clone()).into())
  }
}
/// A rewrite method that first creates a private Filter, by visiting each term in sequence and
/// marking all docs for that term. Matching documents are assigned a constant score equal to the
/// query's boost.
///
/// This method is faster than the BooleanQuery rewrite methods when the number of matched terms
/// or matched documents is non-trivial. Also, it will never return
/// [`LuceneErrorKind::TooManyClauses`](crate::core::util::error::lucene_error::LuceneErrorKind::TooManyClauses).
#[derive(Default, Clone, Debug, PartialEq, Eq, Hash)]
pub struct ConstantScoreRewrite;
impl RewriteMethod for ConstantScoreRewrite {
  fn rewrite<IRC, Q, SIM>(
    &self,
    _index_searcher: &IndexSearcher<IRC, SIM>,
    query: &Q,
  ) -> Result<Query>
  where
    SIM: Similarity,
    Q: MultiTermQuery + Into<MultiTermQuerySet>,
    IRC: IndexReaderContext + 'static,
    IndexSearcher<IRC, SIM>: Sync,
  {
    Ok(MultiTermQueryConstantScoreWrapper::new(query.clone()).into())
  }
}

pub const DOC_VALUES_REWRITE: DocValuesRewriteMethod = DocValuesRewriteMethod;

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum RewriteMethodEnum {
  Blended(ConstantScoreBlendedRewrite),
  ConstantScoreBoolean(ConstantScoreBooleanRewrite),
  DocValues(DocValuesRewriteMethod),
  ScoringBoolean(ScoringBooleanRewrite),
  Standard(ConstantScoreRewrite),
  TopTermsBlendedFreqScoring(TopTermsBlendedFreqScoringRewrite),
  TopTermsBoostOnlyBoolean(TopTermsBoostOnlyBooleanQueryRewrite),
  TopTermsScoringBoolean(TopTermsScoringBooleanQueryRewrite),
}
impl RewriteMethod for RewriteMethodEnum {
  fn rewrite<IRC, Q, SIM>(
    &self,
    index_searcher: &IndexSearcher<IRC, SIM>,
    query: &Q,
  ) -> Result<Query>
  where
    SIM: Similarity,
    Q: MultiTermQuery + Into<MultiTermQuerySet>,
    IRC: IndexReaderContext + 'static,
    IndexSearcher<IRC, SIM>: Sync,
  {
    match self {
      RewriteMethodEnum::Blended(r) => r.rewrite(index_searcher, query),
      RewriteMethodEnum::ConstantScoreBoolean(r) => r.rewrite(index_searcher, query),
      RewriteMethodEnum::DocValues(r) => r.rewrite(index_searcher, query),
      RewriteMethodEnum::ScoringBoolean(r) => r.rewrite(index_searcher, query),
      RewriteMethodEnum::Standard(r) => r.rewrite(index_searcher, query),
      RewriteMethodEnum::TopTermsBlendedFreqScoring(r) => r.rewrite(index_searcher, query),
      RewriteMethodEnum::TopTermsBoostOnlyBoolean(r) => r.rewrite(index_searcher, query),
      RewriteMethodEnum::TopTermsScoringBoolean(r) => r.rewrite(index_searcher, query),
    }
  }
}
/// A rewrite method that first translates each term into [`Occur::Should`] clause
/// in a [`BooleanQuery`](crate::core::search::boolean_query::BooleanQuery), and keeps the scores as computed by the query. Note that typically such
/// scores are meaningless to the user, and require non-trivial CPU to compute, so it's almost
/// always better to use [`ConstantScoreRewrite`] instead.
///
/// **NOTE**: This rewrite method will return
/// [`LuceneErrorKind::TooManyClauses`](crate::core::util::error::lucene_error::LuceneErrorKind::TooManyClauses)
/// if the number of terms exceeds [`index_searcher::get_max_clause_count`].
pub const SCORING_BOOLEAN_REWRITE: ScoringBooleanRewrite = ScoringBooleanRewrite;
/// Like [`SCORING_BOOLEAN_REWRITE`] except scores are not computed. Instead, each matching
/// document receives a constant score equal to the query's boost.
///
/// **NOTE**: This rewrite method will return
/// [`LuceneErrorKind::TooManyClauses`](crate::core::util::error::lucene_error::LuceneErrorKind::TooManyClauses)
/// if the number of terms exceeds [`index_searcher::get_max_clause_count`].
pub const CONSTANT_SCORE_BOOLEAN_REWRITE: ConstantScoreBooleanRewrite = ConstantScoreBooleanRewrite;
impl_from_for_enum!(
    RewriteMethodEnum,
    ConstantScoreBlendedRewrite => Blended,
    ConstantScoreBooleanRewrite => ConstantScoreBoolean,
    DocValuesRewriteMethod => DocValues,
    ScoringBooleanRewrite => ScoringBoolean,
    ConstantScoreRewrite => Standard,
    TopTermsBlendedFreqScoringRewrite => TopTermsBlendedFreqScoring,
    TopTermsBoostOnlyBooleanQueryRewrite => TopTermsBoostOnlyBoolean,
    TopTermsScoringBooleanQueryRewrite => TopTermsScoringBoolean,
);

macro_rules! dispatch_multi_term_query {
  ($self:expr, |$inner:ident| $body:expr) => {{
    match $self {
      MultiTermQuerySet::Prefix($inner) => $body,
      MultiTermQuerySet::TermRange($inner) => $body,
      MultiTermQuerySet::Automaton($inner) => $body,
      MultiTermQuerySet::Fuzzy($inner) => $body,
      MultiTermQuerySet::TermInSet($inner) => $body,
      MultiTermQuerySet::Wildcard($inner) => $body,
      MultiTermQuerySet::Regexp($inner) => $body,
      #[cfg(test)]
      MultiTermQuerySet::BoostChecking($inner) => $body,
      #[cfg(test)]
      MultiTermQuerySet::DumbPrefix($inner) => $body,
      #[cfg(test)]
      MultiTermQuerySet::DumbRegexp($inner) => $body,
    }
  }};
}

/// A rewrite method that first translates each term into [`Occur::Should`] clause
/// in a [`BooleanQuery`](crate::core::search::boolean_query::BooleanQuery), and keeps the scores as computed by the query.
///
/// This rewrite method only uses the top scoring terms so it will not overflow the boolean max
/// clause count.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TopTermsScoringBooleanQueryRewrite {
  size: usize,
}

impl TopTermsScoringBooleanQueryRewrite {
  /// Create a [`TopTermsScoringBooleanQueryRewrite`] for at most `size` terms.
  ///
  /// NOTE: if [`index_searcher::get_max_clause_count`] is smaller than `size`, then
  /// it will be used instead.
  pub fn new(size: usize) -> Self {
    Self { size }
  }
}

impl TermCollectingRewrite for TopTermsScoringBooleanQueryRewrite {
  type B = boolean_query::Builder;

  fn get_top_level_builder(&self) -> Result<Self::B> {
    Ok(boolean_query::Builder::new())
  }

  fn build(&self, builder: Self::B) -> Result<Query> {
    Ok(builder.build().into())
  }

  fn add_clause_with_states(
    &self,
    top_level: &mut Self::B,
    term: Term,
    _doc_count: i32,
    boost: f32,
    states: Option<TermStates>,
  ) -> Result<()> {
    let tq = TermQuery::with_term_state(term, states.map(Arc::new));
    top_level.add(BoostQuery::new(tq, boost)?, Occur::Should)?;
    Ok(())
  }
}

impl RewriteMethod for TopTermsScoringBooleanQueryRewrite {
  fn rewrite<IRC, Q, SIM>(
    &self,
    index_searcher: &IndexSearcher<IRC, SIM>,
    query: &Q,
  ) -> Result<Query>
  where
    SIM: Similarity,
    Q: MultiTermQuery + Into<MultiTermQuerySet>,
    IRC: IndexReaderContext + 'static,
    IndexSearcher<IRC, SIM>: Sync,
  {
    self.default_rewrite(index_searcher, query)
  }
}

impl TopTermsRewrite for TopTermsScoringBooleanQueryRewrite {
  fn get_size(&self) -> usize {
    self.size
  }

  fn get_max_size(&self) -> usize {
    index_searcher::get_max_clause_count()
  }
}
/// A rewrite method that first translates each term into [`Occur::Should`] clause
/// in a [`BooleanQuery`](crate::core::search::boolean_query::BooleanQuery), but adjusts the frequencies used for scoring to be blended across the
/// terms, otherwise the rarest term typically ranks highest (often not useful eg in the set of
/// expanded terms in a [`FuzzyQuery`]).
///
/// This rewrite method only uses the top scoring terms so it will not overflow the boolean max
/// clause count.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TopTermsBlendedFreqScoringRewrite {
  size: usize,
}

impl TopTermsBlendedFreqScoringRewrite {
  /// Create a [`TopTermsBlendedFreqScoringRewrite`] for at most `size` terms.
  ///
  /// NOTE: if [`index_searcher::get_max_clause_count`] is smaller than `size`, then
  /// it will be used instead.
  pub fn new(size: usize) -> Self {
    Self { size }
  }
}

impl TermCollectingRewrite for TopTermsBlendedFreqScoringRewrite {
  type B = blended_term_query::Builder;

  fn get_top_level_builder(&self) -> Result<Self::B> {
    let mut builder = blended_term_query::Builder::new();
    builder.set_rewrite_method(BooleanRewrite);
    Ok(builder)
  }

  fn build(&self, builder: Self::B) -> Result<Query> {
    Ok(builder.build()?.into())
  }

  fn add_clause_with_states(
    &self,
    top_level: &mut Self::B,
    term: Term,
    _doc_count: i32,
    boost: f32,
    states: Option<TermStates>,
  ) -> Result<()> {
    top_level.add_with_term_states(term, boost, states.map(Arc::new))?;
    Ok(())
  }
}

impl RewriteMethod for TopTermsBlendedFreqScoringRewrite {
  fn rewrite<IRC, Q, SIM>(
    &self,
    index_searcher: &IndexSearcher<IRC, SIM>,
    query: &Q,
  ) -> Result<Query>
  where
    SIM: Similarity,
    Q: MultiTermQuery + Into<MultiTermQuerySet>,
    IRC: IndexReaderContext + 'static,
    IndexSearcher<IRC, SIM>: Sync,
  {
    self.default_rewrite(index_searcher, query)
  }
}

impl TopTermsRewrite for TopTermsBlendedFreqScoringRewrite {
  fn get_size(&self) -> usize {
    self.size
  }

  fn get_max_size(&self) -> usize {
    index_searcher::get_max_clause_count()
  }
}

/// A rewrite method that first translates each term into [`Occur::Should`] clause
/// in a [`BooleanQuery`](crate::core::search::boolean_query::BooleanQuery), and keeps the scores as computed by the query.
///
/// This rewrite method only uses the top scoring terms so it will not overflow the boolean max
/// clause count.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TopTermsBoostOnlyBooleanQueryRewrite {
  size: usize,
}
impl TopTermsBoostOnlyBooleanQueryRewrite {
  /// Create a [`TopTermsScoringBooleanQueryRewrite`] for at most `size` terms.
  ///
  /// NOTE: if [`index_searcher::get_max_clause_count`] is smaller than `size`, then
  /// it will be used instead.
  pub fn new(size: usize) -> Self {
    Self { size }
  }
}

impl TermCollectingRewrite for TopTermsBoostOnlyBooleanQueryRewrite {
  type B = boolean_query::Builder;

  fn get_top_level_builder(&self) -> Result<Self::B> {
    Ok(boolean_query::Builder::new())
  }

  fn build(&self, builder: Self::B) -> Result<Query> {
    Ok(builder.build().into())
  }

  fn add_clause_with_states(
    &self,
    top_level: &mut Self::B,
    term: Term,
    _doc_count: i32,
    boost: f32,
    states: Option<TermStates>,
  ) -> Result<()> {
    let tq = TermQuery::with_term_state(term, states.map(Arc::new));
    let q = ConstantScoreQuery::new(tq);
    top_level.add(BoostQuery::new(q, boost)?, Occur::Should)?;
    Ok(())
  }
}

impl RewriteMethod for TopTermsBoostOnlyBooleanQueryRewrite {
  fn rewrite<IRC, Q, SIM>(
    &self,
    index_searcher: &IndexSearcher<IRC, SIM>,
    query: &Q,
  ) -> Result<Query>
  where
    SIM: Similarity,
    Q: MultiTermQuery + Into<MultiTermQuerySet>,
    IRC: IndexReaderContext + 'static,
    IndexSearcher<IRC, SIM>: Sync,
  {
    self.default_rewrite(index_searcher, query)
  }
}

impl TopTermsRewrite for TopTermsBoostOnlyBooleanQueryRewrite {
  fn get_size(&self) -> usize {
    self.size
  }

  fn get_max_size(&self) -> usize {
    index_searcher::get_max_clause_count()
  }
}

use crate::core::index::term::Term;
use crate::core::index::term_states::TermStates;
use crate::core::search::blended_term_query::BooleanRewrite;
use crate::core::search::boolean_clause::Occur;
use crate::core::search::boost_query::BoostQuery;
use crate::core::search::constant_score_query::ConstantScoreQuery;
use crate::core::search::doc_values_rewrite_method::DocValuesRewriteMethod;
use crate::core::search::scoring_rewrite::{ConstantScoreBooleanRewrite, ScoringBooleanRewrite};
use crate::core::search::term_collecting_rewrite::TermCollectingRewrite;
use crate::core::search::term_query::TermQuery;
use crate::core::search::top_terms_rewrite::TopTermsRewrite;
use crate::core::search::{blended_term_query, boolean_query, index_searcher};
pub(crate) use dispatch_multi_term_query;

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum MultiTermQuerySet {
  Automaton(AutomatonQuery),
  Fuzzy(FuzzyQuery),
  Prefix(PrefixQuery),
  Regexp(RegexpQuery),
  TermInSet(TermInSetQuery),
  TermRange(TermRangeQuery),
  Wildcard(WildcardQuery),

  #[cfg(test)]
  BoostChecking(BoostCheckingQuery),
  #[cfg(test)]
  DumbPrefix(DumbPrefixQuery),
  #[cfg(test)]
  DumbRegexp(DumbRegexpQuery),
}

impl QueryBase for MultiTermQuerySet {
  type Weight<IRC, SIM>
    = QueryWeight<IRC, SIM>
  where
    SIM: Similarity,
    IRC: IndexReaderContext + 'static;

  fn to_string(&self, field: &str) -> Result<String> {
    dispatch_multi_term_query!(self, |q| q.to_string(field))
  }

  fn create_weight<IRC, SIM>(
    self,
    searcher: &IndexSearcher<IRC, SIM>,
    score_mode: &ScoreMode,
    boost: f32,
  ) -> Result<Self::Weight<IRC, SIM>>
  where
    SIM: Similarity,
    IRC: IndexReaderContext + 'static,
    IndexSearcher<IRC, SIM>: Sync,
    Self: Sized,
  {
    dispatch_multi_term_query!(self, |q| q.create_weight(searcher, score_mode, boost))
  }

  fn rewrite<IRC, SIM>(&self, searcher: &IndexSearcher<IRC, SIM>) -> Result<Option<Query>>
  where
    SIM: Similarity,
    IRC: IndexReaderContext + 'static,
    IndexSearcher<IRC, SIM>: Sync,
    Self: Sized,
  {
    dispatch_multi_term_query!(self, |q| q.rewrite(searcher))
  }

  fn visit<QV>(&self, visitor: &mut QV) -> Result<()>
  where
    QV: QueryVisitor,
  {
    dispatch_multi_term_query!(self, |q| q.visit(visitor))
  }
}

impl Accountable for MultiTermQuerySet {
  fn ram_bytes_used(&self) -> Result<i64> {
    dispatch_multi_term_query!(self, |q| q.ram_bytes_used())
  }
}

impl HasIdentity for MultiTermQuerySet {
  fn identity(&self) -> &Identity {
    dispatch_multi_term_query!(self, |q| q.identity())
  }
}

impl_from_for_enum!(
    MultiTermQuerySet,
    AutomatonQuery => Automaton,
    FuzzyQuery => Fuzzy,
    PrefixQuery => Prefix,
    RegexpQuery => Regexp,
    TermInSetQuery => TermInSet,
    TermRangeQuery => TermRange,
    WildcardQuery => Wildcard,
);

#[cfg(test)]
impl_from_for_enum!(
    MultiTermQuerySet,
    BoostCheckingQuery => BoostChecking,
    DumbPrefixQuery => DumbPrefix,
    DumbRegexpQuery => DumbRegexp,
);

macro_rules! impl_into_query_for_multi_term_query {
    ($($ty:ty),* $(,)?) => {
        $(
            impl IntoQuery for $ty {
                fn into_query(self) -> Query {
                    MultiTermQuerySet::from(self).into()
                }
            }
        )*
    };
}

impl_into_query_for_multi_term_query!(
  AutomatonQuery,
  FuzzyQuery,
  PrefixQuery,
  RegexpQuery,
  TermInSetQuery,
  TermRangeQuery,
  WildcardQuery,
);

#[cfg(test)]
impl_into_query_for_multi_term_query!(BoostCheckingQuery, DumbPrefixQuery, DumbRegexpQuery,);