Skip to main content

Bm25Index

Struct Bm25Index 

Source
pub struct Bm25Index {
    pub doc_count: usize,
    /* private fields */
}
Expand description

BM25 index for scoring query-document relevance.

Maintains document frequency statistics incrementally. Documents are identified by string IDs and can be added/removed dynamically.

Supports serialization via serialize()/deserialize() for persistence across restarts, avoiding the need to rebuild from all stored memories.

Fields§

§doc_count: usize

Total number of documents

Implementations§

Source§

impl Bm25Index

Source

pub fn new() -> Self

Create a new empty BM25 index with default parameters (k1=1.2, b=0.75).

Source

pub fn add_document(&mut self, id: &str, content: &str)

Add a document to the index, updating term frequencies and statistics. If a document with the same ID already exists, it is replaced. When the index exceeds max_documents, the oldest document is evicted.

Source

pub fn remove_document(&mut self, id: &str)

Remove a document from the index, updating all statistics.

Source

pub fn score(&self, query: &str, doc_id: &str) -> f64

Score a query against a specific document using BM25.

The score is computed as:

score(q, d) = Σ IDF(qi) * (f(qi,d) * (k1+1)) / (f(qi,d) + k1*(1 - b + b*|d|/avgdl))
IDF(qi) = ln((N - n(qi) + 0.5) / (n(qi) + 0.5) + 1)

The returned score is normalized to [0, 1] by dividing by the maximum possible score (perfect self-match with all query terms).

Source

pub fn score_with_tokens_str(&self, query_tokens: &[&str], doc_id: &str) -> f64

Score pre-tokenized query tokens (as &str slices) against a specific indexed document. Use this when scoring multiple documents against the same query to avoid re-tokenizing the query each time. Zero-allocation: passes slices directly to the generic internal helpers.

Source

pub fn score_text_with_tokens( &self, query_tokens: &[String], document: &str, ) -> f64

Score pre-tokenized query tokens against arbitrary text (not necessarily in the index). Use this when scoring multiple documents against the same query to avoid re-tokenizing the query each time.

Source

pub fn score_text_with_tokens_str( &self, query_tokens: &[&str], document: &str, ) -> f64

Score pre-tokenized query tokens (as &str slices) against arbitrary text. Use this when scoring multiple documents against the same query to avoid re-tokenizing the query each time. Zero-allocation: generic helpers accept &[&str].

Source

pub fn score_text(&self, query: &str, document: &str) -> f64

Score a query against arbitrary text (not necessarily in the index). Useful for scoring documents that haven’t been indexed yet.

Source§

impl Bm25Index

Source

pub fn serialize(&self) -> Vec<u8>

Serialize the BM25 index to a byte vector for persistence.

Uses bincode for compact binary representation. The serialized format includes all document frequency statistics, term frequencies, and parameters, enabling fast startup without re-indexing all memories.

Source

pub fn deserialize(data: &[u8]) -> Result<Self, String>

Deserialize a BM25 index from bytes previously produced by serialize().

Returns Err if the data is corrupt or from an incompatible version. Reconstructs total_doc_len and insertion_order if they were missing from older serialized data (via #[serde(default)]).

Source

pub fn needs_save(&self) -> bool

Whether the index contains any documents and may need saving.

Useful for batch operations: call persist_memory_no_save() in a loop, then check needs_save() before writing the vector index to disk once at the end. This avoids O(N) disk writes during bulk inserts.

Trait Implementations§

Source§

impl Debug for Bm25Index

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Bm25Index

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<'de> Deserialize<'de> for Bm25Index

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Serialize for Bm25Index

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> ErasedDestructor for T
where T: 'static,