rlucene 0.1.0-alpha.3

A Rust port of Apache Lucene, a full-text search engine library
Documentation
/*
 * 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::util::error::lucene_error::{LuceneError, Result};

/// Allows access to the score of a query.
pub trait Scorable: FixedScore {
  type Child<'a>: Scorable
  where
    Self: 'a;
  /// Returns the score of the current document matching the query.
  ///
  /// # Errors
  /// Returns an error if an I/O error occurs.
  fn score(&mut self) -> Result<f32>;

  /// Returns the smoothing score of the current document matching the query.
  ///
  /// This score is used when the query/term does not appear in the document,
  /// and behaves like an IDF (inverse document frequency). The smoothing
  /// score is particularly important when the scorer returns a product of
  /// probabilities, so that the document score does not go to zero when
  /// one probability is zero. This can return `0` or a smoothing score.
  ///
  /// # Note
  /// Smoothing scores are described in many papers, including:
  /// - Metzler, D. and Croft, W. B., "Combining the Language Model and
  ///   Inference Network Approaches to Retrieval," *Information Processing
  ///   and Management Special Issue on Bayesian Networks and Information
  ///   Retrieval*, 40(5), pp. 735-750.
  fn smoothing_score(&mut self, _doc_id: i32) -> Result<f32> {
    Ok(0.0)
  }

  /// Optional method: Tells the scorer that its iterator may safely ignore
  /// all documents whose score is lower than the given `min_score`. This
  /// is a no-op by default.
  ///
  /// # Note
  /// This method may only be called from collectors that use
  /// [`ScoreMode::TopScores`](crate::core::search::score_mode::ScoreMode::TopScores),
  /// and successive calls may only set increasing values of `min_score`.
  fn set_min_competitive_score(&mut self, _min_score: f32) -> Result<()> {
    Ok(())
  }

  /// Returns child sub-scorers positioned on the current document.
  ///
  /// Children borrow their existing scorers. This may advance child iterators
  /// to resolve all matches before returning them.
  fn get_children(&mut self) -> Result<Vec<ChildScorable<Self::Child<'_>>>> {
    Ok(vec![])
  }

  /// Implementations that also implement [`Scorer`](crate::core::search::scorer::Scorer) should delegate this method
  /// to [`Scorer::default_cost`](crate::core::search::scorer::Scorer::default_cost) for consistent cost reporting.
  fn cost(&self) -> Result<i64> {
    Err(LuceneError::unsupported_operation(""))
  }
  #[cfg(test)]
  fn as_any(&mut self) -> &mut dyn std::any::Any {
    unreachable!("")
  }

  #[cfg(test)]
  fn scorable_test_type_name(&self) -> &'static str {
    std::any::type_name::<Self>()
  }
}

pub trait FixedScore {
  fn set_score(&mut self, _score: f32) -> Result<()> {
    Err(LuceneError::need_implemented(""))
  }
}

impl<T> FixedScore for &mut T
where
  T: FixedScore + ?Sized,
{
  fn set_score(&mut self, score: f32) -> Result<()> {
    (**self).set_score(score)
  }
}

/// A child Scorer and its relationship to its parent.
///
/// The relationship can be any string that makes sense to the parent scorer.
///
/// # Fields
/// - `child`: The child [`Scorable`]. (This is typically a direct child and may
///   itself also have children.)
/// - `relationship`: An arbitrary string relating this scorer to the parent.
#[derive(Debug, Clone)]
pub struct ChildScorable<T> {
  pub child: T,
  pub relationship: String,
}

impl<T> ChildScorable<T> {
  pub fn new<FName>(child: T, relationship: FName) -> Self
  where
    FName: Into<String>,
  {
    let relationship = relationship.into();
    Self {
      child,
      relationship,
    }
  }
}

impl<T> Scorable for &mut T
where
  T: Scorable + ?Sized,
{
  type Child<'a>
    = T::Child<'a>
  where
    Self: 'a;

  fn score(&mut self) -> Result<f32> {
    (**self).score()
  }

  fn smoothing_score(&mut self, doc_id: i32) -> Result<f32> {
    (**self).smoothing_score(doc_id)
  }

  fn set_min_competitive_score(&mut self, min_score: f32) -> Result<()> {
    (**self).set_min_competitive_score(min_score)
  }

  fn get_children(&mut self) -> Result<Vec<ChildScorable<Self::Child<'_>>>> {
    (**self).get_children()
  }

  fn cost(&self) -> Result<i64> {
    (**self).cost()
  }
  #[cfg(test)]
  fn as_any(&mut self) -> &mut dyn std::any::Any {
    (**self).as_any()
  }

  #[cfg(test)]
  fn scorable_test_type_name(&self) -> &'static str {
    (**self).scorable_test_type_name()
  }
}
macro_rules! either_scorable {
    (
        $vis:vis $name:ident {
            $( $Variant:ident : $T:ident ),+ $(,)?
        }
    ) => {
        $vis enum $name<$( $T ),+> {
            $( $Variant($T), )+
        }

        impl<$( $T ),+> Scorable for $name<$( $T ),+>
        where
            $( $T: Scorable ),+
        {
  type Child<'a> = $name<$( $T::Child<'a> ),+> where Self: 'a;

            fn score(&mut self) -> Result<f32> {
                match self { $( Self::$Variant(inner) => inner.score(), )+ }
            }

            fn smoothing_score(&mut self, doc_id: i32) -> Result<f32> {
                match self { $( Self::$Variant(inner) => inner.smoothing_score(doc_id), )+ }
            }

            fn set_min_competitive_score(&mut self, min_score: f32) -> Result<()> {
                match self { $( Self::$Variant(inner) => inner.set_min_competitive_score(min_score), )+ }
            }

            fn get_children(&mut self) -> Result<Vec<ChildScorable<Self::Child<'_>>>> {
                match self {
                    $( Self::$Variant(inner) => inner.get_children().map(|children| children.into_iter().map(|child| ChildScorable { child: $name::$Variant(child.child), relationship: child.relationship }).collect()), )+
                }
            }

            fn cost(&self) -> Result<i64> {
                match self { $( Self::$Variant(inner) => inner.cost(), )+ }
            }
            #[cfg(test)]
            fn as_any(&mut self) -> &mut dyn std::any::Any {
                match self { $( Self::$Variant(inner) => inner.as_any(), )+ }
            }
        }

        impl<$( $T ),+> FixedScore for $name<$( $T ),+>
        where
            $( $T: FixedScore ),+
        {
            fn set_score(&mut self, score: f32) -> Result<()> {
                match self { $( Self::$Variant(inner) => inner.set_score(score), )+ }
            }
        }
    };
}
either_scorable!(
    pub ScorableEnum2 { A: A, B: B }
);

either_scorable!(pub ScorableEnum3 { A: A, B: B, C: C });
either_scorable!(pub ScorableEnum4 { A: A, B: B, C: C, D: D });