use crate::core::index::index_reader_context::{IRCLeafReader, IndexReaderContext};
use crate::core::index::leaf_reader_context::LeafReaderContext;
use crate::core::search::approximation_disi::ApproximationBitSetAccess;
use crate::core::search::approximation_disi::ApproximationDISI;
use crate::core::search::block_max_conjunction_bulk_scorer::BlockMaxConjunctionBulkScorer;
use crate::core::search::block_max_conjunction_scorer::BlockMaxConjunctionScorer;
use crate::core::search::boolean_clause::Occur;
use crate::core::search::boolean_scorer::BooleanScorer;
use crate::core::search::bulk_scorer::BulkScorer;
use crate::core::search::conjunction_bulk_scorer::ConjunctionBulkScorer;
use crate::core::search::conjunction_scorer::{ConjunctionScorer, ConjunctionScorerDisi};
use crate::core::search::constant_score_scorer::ConstantScoreScorer;
use crate::core::search::disjunction_scorer::DisjunctionScorer;
use crate::core::search::disjunction_sum_scorer::DisjunctionSumScorer;
use crate::core::search::doc_id_set_iterator::{DocIdSetIterator, DocIdSetIteratorEnum2};
use crate::core::search::index_searcher::IndexSearcher;
use crate::core::search::leaf_collector::LeafCollector;
use crate::core::search::max_score_bulk_scorer::MaxScoreBulkScorer;
use crate::core::search::query::{QueryWeightSs, QueryWeightSsBulkScorer, QueryWeightSsScorer};
use crate::core::search::req_excl_bulk_scorer::ReqExclBulkScorer;
use crate::core::search::req_excl_scorer::ReqExclScorer;
use crate::core::search::req_opt_sum_scorer::{self, ReqOptSumScorer};
use crate::core::search::scorable::Scorable;
use crate::core::search::score::Score;
use crate::core::search::score_mode::ScoreMode;
use crate::core::search::score_mode::ScoreMode::CompleteNoScores;
use crate::core::search::scorer::{Scorer, ScorerEnum2, ScorerEnum3, TwoPhaseState};
use crate::core::search::scorer_supplier::ScorerSupplier;
use crate::core::search::scorer_util::ScorerUtil;
use crate::core::search::similarities_impl::similarities::Similarity;
use crate::core::search::two_phase_iterator::TwoPhaseIterator;
use crate::core::search::wand_scorer::WANDScorer;
use crate::core::search::weight::DefaultBulkScorer;
use crate::core::util::bits::Bits;
use crate::core::util::error::lucene_error::{LuceneError, Result};
use smallvec::SmallVec;
#[cfg(test)]
use std::any::Any;
use std::collections::HashMap;
use std::fmt::{Display, Formatter};
pub struct BooleanScorerSupplier<
IRC: IndexReaderContext + 'static,
SIM = crate::core::search::similarities_impl::bm25_similarity::BM25Similarity,
> where
SIM: Similarity,
{
pub(crate) subs: HashMap<Occur, Vec<QueryWeightSs<IRC, SIM>>>,
score_mode: ScoreMode,
min_should_match: i32,
max_doc: i32,
cost: i64,
top_level_scoring_clause: bool,
}
impl<IRC, SIM> BooleanScorerSupplier<IRC, SIM>
where
SIM: Similarity,
IRC: IndexReaderContext + 'static,
{
pub(crate) fn new(
subs: HashMap<Occur, Vec<QueryWeightSs<IRC, SIM>>>,
score_mode: ScoreMode,
min_should_match: i32,
max_doc: i32,
) -> Result<Self> {
if subs.len() != 4
|| !subs.contains_key(&Occur::Should)
|| !subs.contains_key(&Occur::Must)
|| !subs.contains_key(&Occur::Filter)
|| !subs.contains_key(&Occur::MustNot)
{
return Err(LuceneError::illegal_argument(
"subs must contain exactly 4 keys: SHOULD, MUST, FILTER, MUST_NOT",
));
}
if min_should_match < 0 {
return Err(LuceneError::illegal_argument(format!(
"minShouldMatch must be positive, but got: {}",
min_should_match
)));
}
let should_len = subs.get(&Occur::Should).map(|v| v.len()).unwrap_or(0);
let must_len = subs.get(&Occur::Must).map(|v| v.len()).unwrap_or(0);
let filter_len = subs.get(&Occur::Filter).map(|v| v.len()).unwrap_or(0);
if min_should_match != 0 && min_should_match as usize >= should_len {
return Err(LuceneError::illegal_argument(
"minShouldMatch must be strictly less than the number of SHOULD clauses",
));
}
if !score_mode.needs_scores()
&& min_should_match == 0
&& should_len > 0
&& (must_len + filter_len) > 0
{
return Err(LuceneError::illegal_argument(
"Cannot pass purely optional clauses if scores are not needed",
));
}
if should_len + must_len + filter_len == 0 {
return Err(LuceneError::illegal_argument(
"There should be at least one positive clause",
));
}
Ok(Self {
subs,
score_mode,
min_should_match,
max_doc,
cost: -1,
top_level_scoring_clause: false,
})
}
fn compute_cost(
&mut self,
context: &LeafReaderContext<IRCLeafReader<IRC>>,
searcher: &IndexSearcher<IRC, SIM>,
) -> Result<i64>
where
IndexSearcher<IRC, SIM>: Sync,
{
let mut min_required_cost: Option<i64> = None;
if let Some(v) = self.subs.get_mut(&Occur::Must) {
for ss in v.iter_mut() {
let c = ss.cost(context, searcher)?;
min_required_cost = Some(match min_required_cost {
Some(prev) => prev.min(c),
None => c,
});
}
}
if let Some(v) = self.subs.get_mut(&Occur::Filter) {
for ss in v.iter_mut() {
let c = ss.cost(context, searcher)?;
min_required_cost = Some(match min_required_cost {
Some(prev) => prev.min(c),
None => c,
});
}
}
if self.min_should_match == 0
&& let Some(c) = min_required_cost
{
return Ok(c);
}
let should_cost = match self.subs.get_mut(&Occur::Should) {
Some(v) => {
let mut costs: SmallVec<[i64; 8]> = SmallVec::with_capacity(v.len());
for ss in v.iter_mut() {
costs.push(ss.cost(context, searcher)?);
}
ScorerUtil::cost_with_min_should_match(costs, v.len(), self.min_should_match as usize)?
},
None => i64::MAX,
};
Ok(std::cmp::min(
min_required_cost.unwrap_or(i64::MAX),
should_cost,
))
}
fn get_internal(
&mut self,
mut lead_cost: i64,
context: &LeafReaderContext<IRCLeafReader<IRC>>,
searcher: &IndexSearcher<IRC, SIM>,
) -> Result<QueryWeightSsScorer<IRC, SIM>>
where
IndexSearcher<IRC, SIM>: Sync,
{
lead_cost = std::cmp::min(lead_cost, self.cost(context, searcher)?);
let should_empty = self
.subs
.get(&Occur::Should)
.map(|v| v.is_empty())
.unwrap_or(true);
let filter_empty = self
.subs
.get(&Occur::Filter)
.map(|v| v.is_empty())
.unwrap_or(true);
let must_empty = self
.subs
.get(&Occur::Must)
.map(|v| v.is_empty())
.unwrap_or(true);
if should_empty {
let [filter_v, must_v] = self.subs.get_disjoint_mut([&Occur::Filter, &Occur::Must]);
let filter_slice = filter_v
.ok_or_else(|| LuceneError::illegal_state("FILTER clause is missing"))?
.as_mut_slice();
let must_slice = must_v
.ok_or_else(|| LuceneError::illegal_state("MUST clause is missing"))?
.as_mut_slice();
let req = Self::req(
filter_slice,
must_slice,
lead_cost,
self.top_level_scoring_clause,
context,
searcher,
&self.score_mode,
)?;
let v = Self::excl(
req,
self
.subs
.get_mut(&Occur::MustNot)
.map(|v| v.as_mut_slice())
.unwrap_or(&mut []),
lead_cost,
context,
searcher,
)?;
return Ok(v);
}
if filter_empty && must_empty {
let opt = Self::opt(
self
.subs
.get_mut(&Occur::Should)
.map(|v| v.as_mut_slice())
.unwrap_or(&mut []),
self.min_should_match,
self.score_mode,
lead_cost,
self.top_level_scoring_clause,
context,
searcher,
)?;
let v = Self::excl(
opt,
self
.subs
.get_mut(&Occur::MustNot)
.map(|v| v.as_mut_slice())
.unwrap_or(&mut []),
lead_cost,
context,
searcher,
)?;
return Ok(v);
}
let [should_v, must_v, filter_v, must_not_v] = self.subs.get_disjoint_mut([
&Occur::Should,
&Occur::Must,
&Occur::Filter,
&Occur::MustNot,
]);
let should_slice = should_v
.ok_or_else(|| LuceneError::illegal_state("SHOULD clause is missing"))?
.as_mut_slice();
let must_slice = must_v
.ok_or_else(|| LuceneError::illegal_state("MUST clause is missing"))?
.as_mut_slice();
let filter_slice = filter_v
.ok_or_else(|| LuceneError::illegal_state("FILTER clause is missing"))?
.as_mut_slice();
let must_not_slice = must_not_v
.ok_or_else(|| LuceneError::illegal_state("MUST_NOT clause is missing"))?
.as_mut_slice();
if self.min_should_match > 0 {
let req = Self::excl(
Self::req(
filter_slice,
must_slice,
lead_cost,
false,
context,
searcher,
&self.score_mode,
)?,
must_not_slice,
lead_cost,
context,
searcher,
)?;
let opt = Self::opt(
should_slice,
self.min_should_match,
self.score_mode,
lead_cost,
false,
context,
searcher,
)?;
let scoring_idx = vec![0, 1];
Ok(
match ConjunctionScorer::prepare(vec![req, opt], &scoring_idx)? {
ConjunctionScorerDisi::A(disi) => {
QueryWeightSsScorer::<IRC, SIM>::new(ConjunctionScorer::from_disi(disi, scoring_idx))
},
ConjunctionScorerDisi::B(disi) => {
QueryWeightSsScorer::<IRC, SIM>::new(ConjunctionScorer::from_disi(disi, scoring_idx))
},
ConjunctionScorerDisi::C(disi) => {
QueryWeightSsScorer::<IRC, SIM>::new(ConjunctionScorer::from_tpi(disi, scoring_idx))
},
ConjunctionScorerDisi::D(disi) => {
QueryWeightSsScorer::<IRC, SIM>::new(ConjunctionScorer::from_tpi(disi, scoring_idx))
},
},
)
} else {
debug_assert!(self.score_mode.needs_scores());
let req = Self::excl(
Self::req(
filter_slice,
must_slice,
lead_cost,
false,
context,
searcher,
&self.score_mode,
)?,
must_not_slice,
lead_cost,
context,
searcher,
)?;
let opt = Self::opt(
should_slice,
self.min_should_match,
self.score_mode,
lead_cost,
false,
context,
searcher,
)?;
let (disi, has_tpi) =
req_opt_sum_scorer::DocIdSetIteratorImpl::new(req, opt, self.score_mode)?;
if has_tpi {
Ok(QueryWeightSsScorer::<IRC, SIM>::new(
ReqOptSumScorer::from_tpi(req_opt_sum_scorer::TwoPhaseIteratorImpl::new(disi)),
))
} else {
Ok(QueryWeightSsScorer::<IRC, SIM>::new(
ReqOptSumScorer::from_disi(disi),
))
}
}
}
#[allow(clippy::type_complexity)]
pub(crate) fn boolean_scorer(
&mut self,
context: &LeafReaderContext<IRCLeafReader<IRC>>,
searcher: &IndexSearcher<IRC, SIM>,
) -> Result<Option<QueryWeightSsBulkScorer<IRC, SIM>>>
where
IndexSearcher<IRC, SIM>: Sync,
{
let num_optional = self.subs.get(&Occur::Should).map(|v| v.len()).unwrap_or(0);
let num_must = self.subs.get(&Occur::Must).map(|v| v.len()).unwrap_or(0);
let num_required = num_must + self.subs.get(&Occur::Filter).map(|v| v.len()).unwrap_or(0);
let mut positive = if num_required == 0 {
let cost_threshold: i64 = if self.min_should_match <= 1 {
-1
} else {
(self.max_doc as i64) / 3
};
if self.cost(context, searcher)? < cost_threshold {
return Ok(None);
}
match self.optional_bulk_scorer(context, searcher)? {
Some(v) => v,
None => return Ok(None),
}
} else if num_must == 0 && num_optional > 1 && self.min_should_match >= 1 {
match self.filtered_optional_bulk_scorer(context, searcher)? {
Some(v) => v,
None => return Ok(None),
}
} else if num_required > 0 && num_optional == 0 && self.min_should_match == 0 {
match self.required_bulk_scorer(context, searcher)? {
Some(v) => v,
None => return Ok(None),
}
} else {
return Ok(None);
};
let positive_cost = positive.cost()?;
let prohibited_suppliers = self
.subs
.get_mut(&Occur::MustNot)
.map(|v| v.as_mut_slice())
.unwrap_or(&mut []);
if prohibited_suppliers.is_empty() {
return Ok(Some(positive));
}
let mut prohibited = Vec::with_capacity(prohibited_suppliers.len());
for ss in prohibited_suppliers.iter_mut() {
prohibited.push(ss.get(positive_cost, context, searcher)?);
}
let prohibited_scorer = if prohibited.len() == 1 {
ScorerEnum3::A(prohibited.remove(0))
} else {
match DisjunctionScorer::<_, DisjunctionSumScorer>::prepare(
prohibited,
ScoreMode::CompleteNoScores,
)? {
crate::core::search::doc_id_set_iterator::DocIdSetIteratorEnum2::A(disi) => {
ScorerEnum3::B(DisjunctionScorer::from_disi(disi, DisjunctionSumScorer))
},
crate::core::search::doc_id_set_iterator::DocIdSetIteratorEnum2::B(disi) => {
ScorerEnum3::C(DisjunctionScorer::from_tpi(disi, DisjunctionSumScorer))
},
}
};
let v = ReqExclBulkScorer::new(positive, prohibited_scorer);
Ok(Some(QueryWeightSsBulkScorer::<IRC, SIM>::new(v)))
}
#[allow(clippy::type_complexity)]
fn optional_bulk_scorer(
&mut self,
context: &LeafReaderContext<IRCLeafReader<IRC>>,
searcher: &IndexSearcher<IRC, SIM>,
) -> Result<Option<QueryWeightSsBulkScorer<IRC, SIM>>>
where
IndexSearcher<IRC, SIM>: Sync,
{
let should_len = self.subs.get(&Occur::Should).map(|v| v.len()).unwrap_or(0);
if should_len == 0 {
return Ok(None);
} else if should_len == 1 && self.min_should_match <= 1 {
let should = self
.subs
.get_mut(&Occur::Should)
.ok_or_else(|| LuceneError::illegal_state("SHOULD clauses are missing"))?;
return match should[0].bulk_scorer(context, searcher)? {
None => Ok(None),
Some(bs) => return Ok(Some(bs)),
};
}
if self.score_mode == ScoreMode::TopScores && self.min_should_match <= 1 {
let mut optional_scorers = Vec::with_capacity(should_len);
let should = self
.subs
.get_mut(&Occur::Should)
.ok_or_else(|| LuceneError::illegal_state("SHOULD clauses are missing"))?;
for ss in should.iter_mut() {
optional_scorers.push(ss.get(i64::MAX, context, searcher)?);
}
let v = QueryWeightSsBulkScorer::<IRC, SIM>::new(MaxScoreBulkScorer::with_no_filter(
self.max_doc,
optional_scorers,
)?);
return Ok(Some(v));
}
let should = self
.subs
.get_mut(&Occur::Should)
.ok_or_else(|| LuceneError::illegal_state("SHOULD clauses are missing"))?;
if should.iter().all(|supplier| match &supplier.inner {
crate::core::search::query_scorer_supplier::SupplierNode::Term(term) => {
term.score_mode != ScoreMode::TopScores
},
_ => false,
}) {
let mut optional = Vec::with_capacity(should_len);
for supplier in should.iter_mut() {
let crate::core::search::query_scorer_supplier::SupplierNode::Term(term) =
&mut supplier.inner
else {
return Err(LuceneError::illegal_state(
"all optional suppliers were checked to be terms",
));
};
let scorer = match term.get(i64::MAX, context, searcher)? {
crate::core::search::scorer::ScorerEnum4::A(scorer) => {
crate::core::search::scorer::ScorerEnum2::A(scorer)
},
crate::core::search::scorer::ScorerEnum4::D(scorer) => {
crate::core::search::scorer::ScorerEnum2::B(scorer)
},
_ => {
return Err(LuceneError::illegal_state(
"non-TopScores term supplier returned impacts scorer",
));
},
};
optional.push(Box::new(scorer));
}
return Ok(Some(QueryWeightSsBulkScorer::<IRC, SIM>::new(
BooleanScorer::new(
optional,
std::cmp::max(1, self.min_should_match) as usize,
self.score_mode.needs_scores(),
self.max_doc,
)?,
)));
}
let mut optional = Vec::with_capacity(should_len);
for ss in should.iter_mut() {
optional.push(ss.get(i64::MAX, context, searcher)?);
}
let msm = std::cmp::max(1, self.min_should_match);
let v = QueryWeightSsBulkScorer::<IRC, SIM>::new(BooleanScorer::new(
optional,
msm as usize,
self.score_mode.needs_scores(),
self.max_doc,
)?);
Ok(Some(v))
}
fn filtered_optional_bulk_scorer(
&mut self,
context: &LeafReaderContext<IRCLeafReader<IRC>>,
searcher: &IndexSearcher<IRC, SIM>,
) -> Result<Option<QueryWeightSsBulkScorer<IRC, SIM>>>
where
IndexSearcher<IRC, SIM>: Sync,
{
let must_len = self.subs.get(&Occur::Must).map(|v| v.len()).unwrap_or(0);
let filter_len = self.subs.get(&Occur::Filter).map(|v| v.len()).unwrap_or(0);
let should_len = self.subs.get(&Occur::Should).map(|v| v.len()).unwrap_or(0);
if must_len != 0
|| filter_len == 0
|| self.score_mode != ScoreMode::TopScores
|| should_len <= 1
|| self.min_should_match > 1
{
return Ok(None);
}
let cost = self.cost(context, searcher)?;
let mut optional_scorers = Vec::with_capacity(should_len);
if let Some(v) = self.subs.get_mut(&Occur::Should) {
for ss in v.iter_mut() {
optional_scorers.push(ss.get(cost, context, searcher)?);
}
}
let mut filters = Vec::with_capacity(filter_len);
if let Some(v) = self.subs.get_mut(&Occur::Filter) {
for ss in v.iter_mut() {
filters.push(ss.get(cost, context, searcher)?);
}
}
let filter_scorer = if filters.len() == 1 {
filters.remove(0)
} else {
match ConjunctionScorer::prepare(filters, &[])? {
ConjunctionScorerDisi::A(disi) => {
QueryWeightSsScorer::<IRC, SIM>::new(ConjunctionScorer::from_disi(disi, vec![]))
},
ConjunctionScorerDisi::B(disi) => {
QueryWeightSsScorer::<IRC, SIM>::new(ConjunctionScorer::from_disi(disi, vec![]))
},
ConjunctionScorerDisi::C(disi) => {
QueryWeightSsScorer::<IRC, SIM>::new(ConjunctionScorer::from_tpi(disi, vec![]))
},
ConjunctionScorerDisi::D(disi) => {
QueryWeightSsScorer::<IRC, SIM>::new(ConjunctionScorer::from_tpi(disi, vec![]))
},
}
};
let v = QueryWeightSsBulkScorer::<IRC, SIM>::new(MaxScoreBulkScorer::new(
self.max_doc,
optional_scorers,
Some(filter_scorer),
)?);
Ok(Some(v))
}
#[allow(clippy::type_complexity)]
fn required_bulk_scorer(
&mut self,
context: &LeafReaderContext<IRCLeafReader<IRC>>,
searcher: &IndexSearcher<IRC, SIM>,
) -> Result<Option<QueryWeightSsBulkScorer<IRC, SIM>>>
where
IndexSearcher<IRC, SIM>: Sync,
{
let must_len = {
self
.subs
.get_mut(&Occur::Must)
.map(|v| v.len())
.unwrap_or(0)
};
let filter_len = self
.subs
.get_mut(&Occur::Filter)
.map(|v| v.len())
.unwrap_or(0);
let required_cnt = must_len + filter_len;
if required_cnt == 0 {
return Ok(None);
}
if required_cnt == 1 {
return if must_len != 0 {
let must = self
.subs
.get_mut(&Occur::Must)
.ok_or_else(|| LuceneError::illegal_state("MUST clauses are missing"))?;
must[0].bulk_scorer(context, searcher)
} else {
let filter = self
.subs
.get_mut(&Occur::Filter)
.ok_or_else(|| LuceneError::illegal_state("FILTER clauses are missing"))?;
if self.score_mode.needs_scores() {
match filter[0].bulk_scorer(context, searcher)? {
None => Err(LuceneError::illegal_state("bulk_scorer is None"))?,
Some(s) => {
let v = disable_scoring(s);
Ok(Some(QueryWeightSsBulkScorer::<IRC, SIM>::new(v)))
},
}
} else {
filter[0].bulk_scorer(context, searcher)
}
};
}
let mut lead_cost = i64::MAX;
match self.subs.get_mut(&Occur::Must) {
Some(v) if !v.is_empty() => {
for ss in v.iter_mut() {
lead_cost = lead_cost.min(ss.cost(context, searcher)?);
}
},
_ => {},
}
match self.subs.get_mut(&Occur::Filter) {
Some(v) if !v.is_empty() => {
lead_cost = i64::MAX;
for ss in v.iter_mut() {
lead_cost = lead_cost.min(ss.cost(context, searcher)?);
}
},
_ => {},
}
let mut required_no_scoring = Vec::with_capacity(filter_len);
if let Some(v) = self.subs.get_mut(&Occur::Filter) {
for ss in v.iter_mut() {
required_no_scoring.push(ss.get(lead_cost, context, searcher)?);
}
}
let mut required_scoring = Vec::with_capacity(must_len);
if let Some(v) = self.subs.get_mut(&Occur::Must) {
for ss in v.iter_mut() {
if must_len == 1 {
ss.set_top_level_scoring_clause()?;
}
required_scoring.push(ss.get(lead_cost, context, searcher)?);
}
}
if self.score_mode == ScoreMode::TopScores && required_scoring.len() > 1 {
let mut all_no_scoring_no_two_phase = true;
for s in required_no_scoring.iter_mut() {
if s.has_two_phase_iterator() == crate::core::search::scorer::TwoPhaseState::Yes {
all_no_scoring_no_two_phase = false;
break;
}
}
let mut all_scoring_no_two_phase = true;
for s in required_scoring.iter_mut() {
if s.has_two_phase_iterator() == crate::core::search::scorer::TwoPhaseState::Yes {
all_scoring_no_two_phase = false;
break;
}
}
if all_no_scoring_no_two_phase && all_scoring_no_two_phase {
for filter_scorer in required_no_scoring {
required_scoring.push(QueryWeightSsScorer::<IRC, SIM>::new(
ConstantScoreScorer::from_disi(0.0, ScoreMode::Complete, filter_scorer),
));
}
return Ok(Some(QueryWeightSsBulkScorer::<IRC, SIM>::new(
BlockMaxConjunctionBulkScorer::new(self.max_doc, required_scoring)?,
)));
}
}
if self.score_mode != ScoreMode::TopScores
&& required_scoring.len() + required_no_scoring.len() >= 2
{
let mut all_scoring_no_two_phase = true;
for s in required_scoring.iter_mut() {
if s.has_two_phase_iterator() == crate::core::search::scorer::TwoPhaseState::Yes {
all_scoring_no_two_phase = false;
break;
}
}
let mut all_no_scoring_no_two_phase = true;
for s in required_no_scoring.iter_mut() {
if s.has_two_phase_iterator() == crate::core::search::scorer::TwoPhaseState::Yes {
all_no_scoring_no_two_phase = false;
break;
}
}
if all_scoring_no_two_phase && all_no_scoring_no_two_phase {
return Ok(Some(QueryWeightSsBulkScorer::<IRC, SIM>::new(
ConjunctionBulkScorer::new(required_scoring, required_no_scoring)?,
)));
}
}
let mut required_scoring =
if self.score_mode == ScoreMode::TopScores && required_scoring.len() > 1 {
let v = match BlockMaxConjunctionScorer::prepare(required_scoring)? {
DocIdSetIteratorEnum2::A(disi) => {
QueryWeightSsScorer::<IRC, SIM>::new(BlockMaxConjunctionScorer::from_disi(disi))
},
DocIdSetIteratorEnum2::B(disi) => {
QueryWeightSsScorer::<IRC, SIM>::new(BlockMaxConjunctionScorer::from_tpi(disi))
},
};
vec![v]
} else {
required_scoring
};
let mut required_no_scoring = required_no_scoring;
let conjunction_scorer = if required_scoring.len() + required_no_scoring.len() == 1 {
if required_scoring.len() == 1 {
let v = match required_scoring.pop() {
Some(v) => v,
None => {
return Err(LuceneError::illegal_state(
"required_scoring should not be empty",
));
},
};
ScorerEnum2::A(v)
} else {
let inner = match required_no_scoring.pop() {
Some(v) => v,
None => {
return Err(LuceneError::illegal_state(
"required_no_scoring should not be empty",
));
},
};
if self.score_mode.needs_scores() {
ScorerEnum2::B(FilterScorerImpl::new(inner))
} else {
ScorerEnum2::A(inner)
}
}
} else {
let mut required = required_scoring;
let scoring_scorers_idx: Vec<usize> = (0..required.len()).collect();
required.extend(required_no_scoring);
return Ok(Some(
match ConjunctionScorer::prepare(required, &scoring_scorers_idx)? {
ConjunctionScorerDisi::A(disi) => QueryWeightSsBulkScorer::<IRC, SIM>::new(
DefaultBulkScorer::new(ConjunctionScorer::from_disi(disi, scoring_scorers_idx)),
),
ConjunctionScorerDisi::B(disi) => QueryWeightSsBulkScorer::<IRC, SIM>::new(
DefaultBulkScorer::new(ConjunctionScorer::from_disi(disi, scoring_scorers_idx)),
),
ConjunctionScorerDisi::C(disi) => QueryWeightSsBulkScorer::<IRC, SIM>::new(
DefaultBulkScorer::new(ConjunctionScorer::from_tpi(disi, scoring_scorers_idx)),
),
ConjunctionScorerDisi::D(disi) => QueryWeightSsBulkScorer::<IRC, SIM>::new(
DefaultBulkScorer::new(ConjunctionScorer::from_tpi(disi, scoring_scorers_idx)),
),
},
));
};
Ok(Some(QueryWeightSsBulkScorer::<IRC, SIM>::new(
DefaultBulkScorer::new(conjunction_scorer),
)))
}
fn req(
required_no_scoring: &mut [QueryWeightSs<IRC, SIM>],
required_scoring: &mut [QueryWeightSs<IRC, SIM>],
lead_cost: i64,
top_level_scoring_clause: bool,
context: &LeafReaderContext<IRCLeafReader<IRC>>,
searcher: &IndexSearcher<IRC, SIM>,
score_mode: &ScoreMode,
) -> Result<QueryWeightSsScorer<IRC, SIM>>
where
IndexSearcher<IRC, SIM>: Sync,
{
if required_no_scoring.len() + required_scoring.len() == 1 {
let req = if required_no_scoring.is_empty() {
required_scoring[0].get(lead_cost, context, searcher)?
} else {
required_no_scoring[0].get(lead_cost, context, searcher)?
};
if !score_mode.needs_scores() {
return Ok(req);
}
if required_scoring.is_empty() {
return Ok(QueryWeightSsScorer::<IRC, SIM>::new(FilterScorerImpl::new(
req,
)));
}
return Ok(req);
}
let mut required_scorers =
Vec::with_capacity(required_no_scoring.len() + required_scoring.len());
let mut scoring_scorers = Vec::with_capacity(required_scoring.len());
for s in required_no_scoring.iter_mut() {
required_scorers.push(s.get(lead_cost, context, searcher)?);
}
for s in required_scoring.iter_mut() {
let scorer = s.get(lead_cost, context, searcher)?;
scoring_scorers.push(scorer);
}
let scoring_scorers_idx = if *score_mode == ScoreMode::TopScores
&& scoring_scorers.len() > 1
&& top_level_scoring_clause
{
let block_max_scorer = match BlockMaxConjunctionScorer::prepare(scoring_scorers)? {
DocIdSetIteratorEnum2::A(disi) => {
QueryWeightSsScorer::<IRC, SIM>::new(BlockMaxConjunctionScorer::from_disi(disi))
},
DocIdSetIteratorEnum2::B(disi) => {
QueryWeightSsScorer::<IRC, SIM>::new(BlockMaxConjunctionScorer::from_tpi(disi))
},
};
if required_scorers.is_empty() {
return Ok(block_max_scorer);
} else {
required_scorers.push(block_max_scorer);
}
vec![required_scorers.len() - 1]
} else {
let base = required_scorers.len();
let scoring_scorers_idx = (0..scoring_scorers.len()).map(|i| base + i).collect();
required_scorers.extend(scoring_scorers);
scoring_scorers_idx
};
Ok(
match ConjunctionScorer::prepare(required_scorers, &scoring_scorers_idx)? {
ConjunctionScorerDisi::A(disi) => QueryWeightSsScorer::<IRC, SIM>::new(
ConjunctionScorer::from_disi(disi, scoring_scorers_idx),
),
ConjunctionScorerDisi::B(disi) => QueryWeightSsScorer::<IRC, SIM>::new(
ConjunctionScorer::from_disi(disi, scoring_scorers_idx),
),
ConjunctionScorerDisi::C(disi) => QueryWeightSsScorer::<IRC, SIM>::new(
ConjunctionScorer::from_tpi(disi, scoring_scorers_idx),
),
ConjunctionScorerDisi::D(disi) => QueryWeightSsScorer::<IRC, SIM>::new(
ConjunctionScorer::from_tpi(disi, scoring_scorers_idx),
),
},
)
}
fn excl(
main: QueryWeightSsScorer<IRC, SIM>,
prohibited: &mut [QueryWeightSs<IRC, SIM>],
lead_cost: i64,
context: &LeafReaderContext<IRCLeafReader<IRC>>,
searcher: &IndexSearcher<IRC, SIM>,
) -> Result<QueryWeightSsScorer<IRC, SIM>>
where
IndexSearcher<IRC, SIM>: Sync,
{
if prohibited.is_empty() {
Ok(main)
} else {
let opt = Self::opt(
prohibited,
1,
CompleteNoScores,
lead_cost,
false,
context,
searcher,
)?;
match ReqExclScorer::prepare(main, opt)? {
crate::core::search::two_phase_iterator::TwoPhaseIteratorEnum2::A(tpi) => Ok(
QueryWeightSsScorer::<IRC, SIM>::new(ReqExclScorer::new(tpi)),
),
crate::core::search::two_phase_iterator::TwoPhaseIteratorEnum2::B(tpi) => Ok(
QueryWeightSsScorer::<IRC, SIM>::new(ReqExclScorer::new(tpi)),
),
}
}
}
fn opt(
optional: &mut [QueryWeightSs<IRC, SIM>],
min_should_match: i32,
score_mode: ScoreMode,
lead_cost: i64,
top_level_scoring_clause: bool,
context: &LeafReaderContext<IRCLeafReader<IRC>>,
searcher: &IndexSearcher<IRC, SIM>,
) -> Result<QueryWeightSsScorer<IRC, SIM>>
where
IndexSearcher<IRC, SIM>: Sync,
{
if optional.len() == 1 {
return optional[0].get(lead_cost, context, searcher);
}
let mut optional_scorers = Vec::with_capacity(optional.len());
for supplier in optional.iter_mut() {
optional_scorers.push(supplier.get(lead_cost, context, searcher)?);
}
if (score_mode == ScoreMode::TopScores && top_level_scoring_clause) || min_should_match > 1 {
if score_mode == ScoreMode::TopScores {
Ok(QueryWeightSsScorer::<IRC, SIM>::new(
WANDScorer::<_, true>::new(optional_scorers, min_should_match, score_mode, lead_cost)?,
))
} else {
Ok(QueryWeightSsScorer::<IRC, SIM>::new(
WANDScorer::<_, false>::new(optional_scorers, min_should_match, score_mode, lead_cost)?,
))
}
} else {
match DisjunctionScorer::<_, DisjunctionSumScorer>::prepare(optional_scorers, score_mode)? {
crate::core::search::doc_id_set_iterator::DocIdSetIteratorEnum2::A(disi) => {
Ok(QueryWeightSsScorer::<IRC, SIM>::new(
DisjunctionScorer::from_disi(disi, DisjunctionSumScorer),
))
},
crate::core::search::doc_id_set_iterator::DocIdSetIteratorEnum2::B(disi) => {
Ok(QueryWeightSsScorer::<IRC, SIM>::new(
DisjunctionScorer::from_tpi(disi, DisjunctionSumScorer),
))
},
}
}
}
}
impl<IRC, SIM> ScorerSupplier<IRC, SIM> for BooleanScorerSupplier<IRC, SIM>
where
SIM: Similarity,
IRC: IndexReaderContext + 'static,
{
type Scorer = QueryWeightSsScorer<IRC, SIM>;
type BulkScorer = QueryWeightSsBulkScorer<IRC, SIM>;
fn get(
&mut self,
lead_cost: i64,
context: &LeafReaderContext<IRCLeafReader<IRC>>,
searcher: &IndexSearcher<IRC, SIM>,
) -> Result<Self::Scorer>
where
IndexSearcher<IRC, SIM>: Sync,
{
let scorer = self.get_internal(lead_cost, context, searcher)?;
if self.score_mode == ScoreMode::TopScores {
let should_empty = self
.subs
.get(&Occur::Should)
.map(|v| v.is_empty())
.unwrap_or(true);
let must_empty = self
.subs
.get(&Occur::Must)
.map(|v| v.is_empty())
.unwrap_or(true);
if should_empty && must_empty {
if scorer.has_two_phase_iterator() == crate::core::search::scorer::TwoPhaseState::Yes {
let tpi = scorer;
return Ok(QueryWeightSsScorer::<IRC, SIM>::new(
ConstantScoreScorer::from_tpi(0.0, self.score_mode, tpi),
));
} else {
let disi = scorer;
return Ok(QueryWeightSsScorer::<IRC, SIM>::new(
ConstantScoreScorer::from_disi(0.0, self.score_mode, disi),
));
};
}
}
Ok(scorer)
}
fn bulk_scorer(
&mut self,
context: &LeafReaderContext<IRCLeafReader<IRC>>,
searcher: &IndexSearcher<IRC, SIM>,
) -> Result<Option<Self::BulkScorer>>
where
IndexSearcher<IRC, SIM>: Sync,
{
if let Some(bs) = self.boolean_scorer(context, searcher)? {
return Ok(Some(bs));
}
match self.default_bulk_scorer(context, searcher).map(Some)? {
Some(v) => Ok(Some(QueryWeightSsBulkScorer::<IRC, SIM>::new(v))),
None => Ok(None),
}
}
fn cost(
&mut self,
context: &LeafReaderContext<IRCLeafReader<IRC>>,
searcher: &IndexSearcher<IRC, SIM>,
) -> Result<i64>
where
IndexSearcher<IRC, SIM>: Sync,
{
if self.cost == -1 {
self.cost = self.compute_cost(context, searcher)?;
}
Ok(self.cost)
}
fn set_top_level_scoring_clause(&mut self) -> Result<()> {
self.top_level_scoring_clause = true;
let should_len = self.subs.get(&Occur::Should).map(|v| v.len()).unwrap_or(0);
let must_len = self.subs.get(&Occur::Must).map(|v| v.len()).unwrap_or(0);
if should_len + must_len == 1 {
if let Some(v) = self.subs.get_mut(&Occur::Should) {
for ss in v.iter_mut() {
ss.set_top_level_scoring_clause()?;
}
}
if let Some(v) = self.subs.get_mut(&Occur::Must) {
for ss in v.iter_mut() {
ss.set_top_level_scoring_clause()?;
}
}
}
Ok(())
}
#[cfg(test)]
fn as_any(&mut self) -> &mut dyn Any {
self
}
}
pub struct FilterScorerImpl<S> {
inner: S,
}
impl<S> FilterScorerImpl<S> {
fn new(inner: S) -> Self {
Self { inner }
}
}
impl<S> Scorable for FilterScorerImpl<S>
where
S: Scorer,
{
type Child<'a>
= crate::core::search::dummy::dummy_scorable::DummyScorable
where
Self: 'a;
fn score(&mut self) -> Result<f32> {
Ok(0f32)
}
fn cost(&self) -> Result<i64> {
DocIdSetIterator::cost(&self)
}
}
impl<S> crate::core::search::scorable::FixedScore for FilterScorerImpl<S> {}
impl<S> DocIdSetIterator for FilterScorerImpl<S>
where
S: Scorer,
{
fn doc_id(&self) -> i32 {
DocIdSetIterator::doc_id(&self.inner)
}
fn next_doc(&mut self) -> Result<i32> {
DocIdSetIterator::next_doc(&mut self.inner)
}
fn advance(&mut self, target: i32) -> Result<i32> {
DocIdSetIterator::advance(&mut self.inner, target)
}
fn slow_advance(&mut self, target: i32) -> Result<i32> {
DocIdSetIterator::slow_advance(&mut self.inner, target)
}
fn cost(&self) -> Result<i64> {
DocIdSetIterator::cost(&self.inner)
}
}
impl<S> crate::core::search::doc_id_set_iterator::DocIdSetIteratorExtensions for FilterScorerImpl<S>
where
S: Scorer,
{
fn get_fixed_bit_set(&self) -> Option<&crate::core::util::fixed_bit_set::FixedBitSet> {
let iterator = { &self.inner };
crate::core::search::doc_id_set_iterator::DocIdSetIteratorExtensions::get_fixed_bit_set(
iterator,
)
}
fn get_sparse_fixed_bit_set(
&self,
) -> Option<&crate::core::util::sparse_fixed_bit_set::SparseFixedBitSet> {
let iterator = { &self.inner };
crate::core::search::doc_id_set_iterator::DocIdSetIteratorExtensions::get_sparse_fixed_bit_set(
iterator,
)
}
fn get_doc_base_fixed_bit_set(
&self,
) -> Option<(usize, &crate::core::util::fixed_bit_set::FixedBitSet)> {
let iterator = { &self.inner };
crate::core::search::doc_id_set_iterator::DocIdSetIteratorExtensions::get_doc_base_fixed_bit_set(
iterator,
)
}
}
impl<S> crate::core::search::doc_id_set_iterator::BitSetIteratorAccess for FilterScorerImpl<S>
where
S: Scorer,
{
fn is_bit_iter(&self) -> bool {
crate::core::search::doc_id_set_iterator::BitSetIteratorAccess::is_bit_iter(&self.inner)
}
fn get(&self, index: usize) -> Result<bool> {
crate::core::search::doc_id_set_iterator::BitSetIteratorAccess::get(&self.inner, index)
}
fn set_doc_id(&mut self, doc: i32) -> Result<()> {
crate::core::search::doc_id_set_iterator::BitSetIteratorAccess::set_doc_id(&mut self.inner, doc)
}
fn bit_set_length(&self) -> Result<usize> {
crate::core::search::doc_id_set_iterator::BitSetIteratorAccess::bit_set_length(&self.inner)
}
}
impl<S> ApproximationDISI for FilterScorerImpl<S>
where
S: Scorer,
{
fn approx_doc_id(&self) -> i32 {
self.inner.approx_doc_id()
}
fn approx_next_doc(&mut self) -> Result<i32> {
self.inner.approx_next_doc()
}
fn approx_advance(&mut self, target: i32) -> Result<i32> {
self.inner.approx_advance(target)
}
fn approx_slow_advance(&mut self, target: i32) -> Result<i32> {
self.inner.approx_slow_advance(target)
}
fn approx_cost(&self) -> Result<i64> {
self.inner.approx_cost()
}
}
impl<S> ApproximationBitSetAccess for FilterScorerImpl<S>
where
S: Scorer,
{
fn approx_is_bit_iter(&self) -> bool {
self.inner.approx_is_bit_iter()
}
fn approx_get(&self, index: usize) -> Result<bool> {
self.inner.approx_get(index)
}
fn approx_set_doc_id(&mut self, doc: i32) -> Result<()> {
self.inner.approx_set_doc_id(doc)
}
fn approx_bit_set_length(&self) -> Result<usize> {
self.inner.approx_bit_set_length()
}
}
impl<S> TwoPhaseIterator for FilterScorerImpl<S>
where
S: Scorer,
{
fn matches(&mut self) -> Result<bool> {
self.inner.matches()
}
fn match_cost(&self) -> f32 {
self.inner.match_cost()
}
}
impl<S> Scorer for FilterScorerImpl<S>
where
S: Scorer,
{
fn scoring_doc_id(&mut self) -> Result<i32> {
(self.inner).scoring_doc_id()
}
fn advance_shallow(&mut self, target: i32) -> Result<i32> {
self.inner.advance_shallow(target)
}
fn default_advance_shallow(&mut self, target: i32) -> Result<i32> {
self.inner.default_advance_shallow(target)
}
fn get_max_score(&mut self, _up_to: i32) -> Result<f32> {
Ok(0f32)
}
fn default_cost(&mut self) -> Result<i64> {
self.inner.default_cost()
}
fn has_two_phase_iterator(&self) -> TwoPhaseState {
self.inner.has_two_phase_iterator()
}
}
pub(crate) fn disable_scoring<BS>(scorer: BS) -> BulkScorerImpl<BS> {
BulkScorerImpl::new(scorer)
}
pub struct BulkScorerImpl<BS> {
pub(crate) scorer: BS,
}
impl<BS> BulkScorerImpl<BS> {
fn new(scorer: BS) -> Self {
Self { scorer }
}
}
impl<BS> BulkScorer for BulkScorerImpl<BS>
where
BS: BulkScorer,
{
fn score<CLC: crate::core::search::leaf_collector::LeafCollector, AB: Bits + ?Sized>(
&mut self,
collector: &mut CLC,
accept_docs: Option<&AB>,
min: i32,
max: i32,
) -> Result<i32> {
let mut no_score_collector = LeafCollectorImpl::new(collector);
self
.scorer
.score(&mut no_score_collector, accept_docs, min, max)
}
fn cost(&mut self) -> Result<i64> {
self.scorer.cost()
}
}
pub struct LeafCollectorImpl<LC> {
collector: LC,
fake: Score,
}
impl<LC> LeafCollectorImpl<LC> {
fn new(collector: LC) -> Self {
Self {
collector,
fake: Score::new(0.0),
}
}
}
impl<LC> Display for LeafCollectorImpl<LC>
where
LC: Display,
{
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "LeafCollectorImpl({})", self.collector)
}
}
impl<LC> LeafCollector for LeafCollectorImpl<LC>
where
LC: LeafCollector,
{
type CompetitiveIterator<'a>
= crate::core::search::doc_id_set_iterator::EmptyDISI
where
Self: 'a;
fn set_scorer<SC: Scorable + ?Sized>(&mut self, _scorer: &mut SC) -> Result<()> {
self.collector.set_scorer(&mut self.fake)
}
fn collect<SC: Scorable + ?Sized>(&mut self, doc: i32, _scorer: &mut SC) -> Result<()> {
self.collector.collect(doc, &mut self.fake)
}
}