use crate::core::index::BytesRef;
use crate::core::index::index_reader::Identity;
use crate::core::index::index_reader_context::IndexReaderContext;
use crate::core::index::term::Term;
use crate::core::index::terms::Terms;
use crate::core::search::automaton_query::AutomatonQuery;
use crate::core::search::index_searcher::IndexSearcher;
use crate::core::search::multi_term_query::{
ConstantScoreBlendedRewrite, MultiTermQuery, MultiTermQuerySet, RewriteMethod, RewriteMethodEnum,
};
use crate::core::search::query::{Query, QueryBase, QueryWeight};
use crate::core::search::query_visitor::QueryVisitor;
use crate::core::search::score_mode::ScoreMode;
use crate::core::search::similarities_impl::similarities::Similarity;
use crate::core::util::HasIdentity;
use crate::core::util::automation::automaton::Automaton;
use crate::core::util::error::lucene_error::{LuceneError, Result};
use std::fmt::{Debug, Formatter};
use std::hash::{Hash, Hasher};
#[derive(Clone)]
pub struct PrefixQuery {
base: AutomatonQuery,
}
impl PrefixQuery {
pub fn new<TermInput>(prefix: TermInput) -> Result<Self>
where
TermInput: Into<Term>,
{
let prefix = prefix.into();
Self::with_rewrite(prefix, ConstantScoreBlendedRewrite)
}
pub fn with_rewrite<R, TermInput>(prefix: TermInput, rewrite_method: R) -> Result<Self>
where
R: Into<RewriteMethodEnum>,
TermInput: Into<Term>,
{
let prefix = prefix.into();
let automaton = to_automaton(prefix.bytes())?;
let base = AutomatonQuery::new(prefix, automaton, true, rewrite_method)?;
Ok(Self { base })
}
}
impl QueryBase for PrefixQuery {
type Weight<IRC, SIM>
= QueryWeight<IRC, SIM>
where
SIM: Similarity,
IRC: IndexReaderContext + 'static;
fn to_string(&self, field: &str) -> Result<String> {
let mut buffer = String::new();
if self.base.get_field() != field {
buffer.push_str(self.base.get_field());
buffer.push(':');
}
{
let text = self.base.term.text()?;
if buffer.is_empty() {
buffer = text.into_owned();
} else {
buffer.push_str(&text);
}
}
buffer.push('*');
Ok(buffer)
}
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,
Self: Sized,
IndexSearcher<IRC, SIM>: Sync,
{
Err(LuceneError::unsupported_operation(""))
}
fn rewrite<IRC, SIM>(&self, searcher: &IndexSearcher<IRC, SIM>) -> Result<Option<Query>>
where
SIM: Similarity,
IRC: IndexReaderContext + 'static,
Self: Sized,
IndexSearcher<IRC, SIM>: Sync,
{
self.base.rewrite_method.rewrite(searcher, self).map(Some)
}
fn visit<QV>(&self, visitor: &mut QV) -> Result<()>
where
QV: QueryVisitor,
{
self.base.visit_with_query(visitor, self.into())
}
}
impl Debug for PrefixQuery {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self.to_string("") {
Ok(s) => write!(f, "{}", s),
Err(_) => Err(std::fmt::Error),
}
}
}
impl HasIdentity for PrefixQuery {
fn identity(&self) -> &Identity {
self.base.identity()
}
}
impl MultiTermQuery for PrefixQuery {
fn get_field(&self) -> &str {
self.base.get_field()
}
type TermsEnum<T>
= <AutomatonQuery as MultiTermQuery>::TermsEnum<T>
where
T: Terms;
fn get_terms_enum<T>(&self, terms: T) -> Result<Self::TermsEnum<T>>
where
T: Terms + Clone,
{
self.base.compiled.get_terms_enum(terms)
}
fn to_query(&self) -> Query {
MultiTermQuerySet::from(self.clone()).into()
}
}
impl Eq for PrefixQuery {}
impl PartialEq for PrefixQuery {
fn eq(&self, other: &Self) -> bool {
self.base == other.base && self.base.term == other.base.term
}
}
impl Hash for PrefixQuery {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
self.base.term.hash(state);
self.base.hash(state);
}
}
pub fn to_automaton(prefix: &BytesRef<Vec<u8>>) -> Result<Automaton> {
let num_states_and_transitions = prefix.length + 1;
let mut automaton =
Automaton::with_capacity(num_states_and_transitions, num_states_and_transitions);
let mut last_state = automaton.create_state()?;
for i in 0..prefix.length {
let state = automaton.create_state()?;
let b = prefix.bytes[prefix.offset + i];
automaton.add_transition_label(last_state, state, b as i32)?;
last_state = state;
}
automaton.set_accept(last_state, true);
automaton.add_transition(last_state, last_state, 0, 255)?;
automaton.finish_state()?;
debug_assert!(automaton.is_deterministic());
Ok(automaton)
}
impl crate::core::util::accountable::Accountable for PrefixQuery {
fn ram_bytes_used(&self) -> crate::core::util::error::lucene_error::Result<i64> {
Ok(crate::core::util::ram_usage_estimator::QUERY_DEFAULT_RAM_BYTES_USED)
}
}