Files
telefind-rs/crates/telefind-core/src/search/retrieve.rs
T

123 lines
3.7 KiB
Rust

use super::{analysis, rank, scope::Scope};
use crate::{index::IndexReader, DocumentId, Kind, Query, SearchPage};
use std::{
cmp::{Ordering, Reverse},
collections::BinaryHeap,
};
#[derive(Debug)]
struct Hit {
exact: bool,
score: f64,
id: DocumentId,
}
impl Ord for Hit {
fn cmp(&self, other: &Self) -> Ordering {
self.exact
.cmp(&other.exact)
.then_with(|| self.score.total_cmp(&other.score))
.then_with(|| other.id.cmp(&self.id))
}
}
impl PartialOrd for Hit {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Hit {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl Eq for Hit {}
pub(crate) fn retrieve<R: IndexReader>(reader: &R, query: &Query) -> Result<SearchPage, R::Error> {
let empty = || SearchPage {
total: 0,
hits: Vec::new(),
};
let normalized = analysis::normalize(query.text);
let Some((scope, text)) = Scope::parse(&normalized) else {
return Ok(empty());
};
// Only closed quote pairs are operators; an unmatched trailing quote is punctuation.
let parts: Vec<_> = text.split('"').skip(1).collect();
let phrases: Vec<_> = parts
.chunks_exact(2)
.map(|pair| pair[0].trim())
.filter(|phrase| !phrase.is_empty())
.collect();
let mut lists = Vec::new();
for term in analysis::query_terms(text) {
let Some(postings) = reader.postings(&term)? else {
return Ok(empty());
};
lists.push(postings);
}
lists.sort_unstable_by_key(|list| list.len());
let Some(first) = lists.first() else {
return Ok(empty());
};
let (n, lengths) = reader.statistics()?;
let avg = lengths.map(|length| length as f64 / n.max(1) as f64);
let mut best = BinaryHeap::new();
let mut total = 0;
let window = query.offset.saturating_add(query.limit);
for id in first.keys() {
if !lists[1..].iter().all(|list| list.contains_key(id)) {
continue;
}
let entry = reader.document(*id)?;
if !scope.accepts(&entry)
|| query.kind.is_some_and(|kind| kind != entry.document.kind())
|| query
.media
.is_some_and(|media| Some(media) != entry.document.media)
{
continue;
}
if !phrases
.iter()
.all(|phrase| entry.title.contains(phrase) || entry.body.contains(phrase))
{
continue;
}
total += 1;
if query.limit == 0 || query.offset >= first.len() {
continue;
}
let mut score: f64 = lists
.iter()
.map(|list| rank::term_score(list[id], entry.lengths, avg, n, list.len()))
.sum();
if entry.title.contains(text) {
score += 2.0;
} else if entry.body.contains(text) {
score += 0.5;
}
let exact = entry.document.kind() != Kind::Post
&& (entry.title == text
|| entry.document.username.as_str() == text.trim_start_matches('@'));
let hit = Hit {
exact,
score,
id: *id,
};
if best.len() < window {
best.push(Reverse(hit));
} else if let Some(mut worst) = best.peek_mut() {
if hit > worst.0 {
*worst = Reverse(hit);
}
}
}
let hits = best
.into_sorted_vec()
.into_iter()
.skip(query.offset)
.map(|Reverse(hit)| reader.document(hit.id).map(|entry| entry.document.clone()))
.collect::<Result<Vec<_>, _>>()?;
Ok(SearchPage { total, hits })
}