use std::collections::{HashMap, HashSet};
use std::ffi::CStr;
use std::ops::Range;
use std::sync::Arc;
use rusqlite::blob::Blob;
use rusqlite::{Connection, MAIN_DB, OptionalExtension};
use super::analyzer::{self, Word};
use super::clusters::{self, Phase, Probe};
use super::correct::Corrector;
use super::execute::{Fetch, List, best, best_of, count, held_by_all};
use super::filter::{self, Docs, Reader};
use super::hybrid::{self, HALF};
use super::index::Total;
use super::kept::{Chunk, Gone, Kept, KeptPiece, Listed, Moment, NORMS};
use super::layouts;
use super::legacy;
use super::matches::{Ask, Sought};
use super::packed::{self, Directory};
use super::postings::Posting;
use super::score::{PREFIXED, Part, average, idf, score};
use super::segments::{self, Segment};
use super::settings::Settings;
use super::vectors::{self, Among, Question, Scan};
use crate::sqlite::sql_error;
use crate::sync::lock;
use crate::{Error, Memory, Result};
const READ_INDEX: &str =
"select documents, normed, gone_version, words_version, lists_version from _tinystore_search_indexes where id = ?1";
const READ_PARTS: &str = "select part, tokens from _tinystore_search_parts where index_id = ?1";
const FIND_KEY: &str =
"select id, documents from _tinystore_search_keys where index_id = ?1 and part = ?2 and term = ?3";
const FIND_PREFIXED: &str = "select id, documents, term from _tinystore_search_keys as k
where index_id = ?1 and part = ?2 and term > ?3 and term < ?4 and (documents > 0 or exists (select 1
from _tinystore_search_segments as s join _tinystore_search_pieces as p on p.segment = s.id and p.key = k.id
where s.index_id = ?1 and s.folded = 0))
order by documents desc, term limit cast(?5 as integer)";
const BEGINS_A_WORD: &str = "select exists (select 1 from _tinystore_search_keys as k
where index_id = ?1 and part = ?2 and term > ?3 and term < ?4 and (documents > 0 or exists (select 1
from _tinystore_search_segments as s join _tinystore_search_pieces as p on p.segment = s.id and p.key = k.id
where s.index_id = ?1 and s.folded = 0)))";
const RUNS: &CStr = c"_tinystore_search_runs";
const BLOCKS: &CStr = c"blocks";
const READ_HIT: &str = "select id, value from _tinystore_search_docs where index_id = ?1 and doc = ?2";
const MOST_PREFIXED: usize = 64;
const LEAST_PREFIX: usize = 2;
const MOST_PREFIXES: usize = 8;
const NARROW_WORDS: u64 = 32;
const NARROW_VECTORS: u64 = 4;
const MOST_COUNTED: usize = 10_000;
#[derive(Clone, Debug)]
pub(crate) struct Query {
pub(crate) normal: String,
pub(crate) words: Vec<Word>,
pub(crate) vector: Option<Question>,
pub(crate) vector_weight: Option<f64>,
pub(crate) rerank: bool,
pub(crate) min_similarity: Option<f64>,
pub(crate) prefix: Prefix,
pub(crate) matches: Option<Ask>,
pub(crate) filter: Option<filter::Asked>,
pub(crate) total: bool,
pub(crate) offset: usize,
pub(crate) limit: usize,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum Prefix {
#[default]
Whole,
Last,
Every,
}
#[derive(Debug)]
pub(crate) struct Asked<'a> {
pub(crate) index: i64,
pub(crate) settings: &'a Settings,
pub(crate) kept: &'a Kept,
pub(crate) memory: &'a Arc<Memory>,
pub(crate) query: Query,
}
#[derive(Debug)]
pub(crate) struct Answer {
pub(crate) hits: Vec<Ranked>,
pub(crate) corrected: Option<String>,
pub(crate) behind: bool,
pub(crate) sought: Option<Sought>,
pub(crate) total: Option<Total>,
}
#[derive(Debug)]
pub(crate) struct Ranked {
pub(crate) id: String,
pub(crate) value: Vec<u8>,
pub(crate) score: f64,
pub(crate) text_score: Option<f64>,
pub(crate) similarity: Option<f64>,
}
#[derive(Default)]
struct Halves {
words: HashMap<u32, f64>,
cosines: HashMap<u32, f64>,
}
impl Halves {
fn words(&mut self, found: Vec<(f64, u32)>) -> Vec<(f64, u32)> {
self.words.extend(found.iter().map(|(score, doc)| (*doc, *score)));
found
}
fn vectors(&mut self, found: Vec<(f64, u32)>) -> Vec<(f64, u32)> {
self.cosines.extend(found.iter().map(|(cosine, doc)| (*doc, *cosine)));
found
}
}
fn floored(found: Vec<(f64, u32)>, asked: &Asked<'_>) -> Vec<(f64, u32)> {
match asked.query.min_similarity {
Some(floor) => found.into_iter().filter(|(cosine, _)| *cosine >= floor).collect(),
None => found,
}
}
#[derive(Clone, Copy, Debug)]
enum Mode {
Words,
Vector,
Sum(f64),
Rerank,
}
pub(crate) fn search(connection: &Connection, mut asked: Asked<'_>) -> Result<Answer> {
let (moment, documents, words_version) = moment(connection, asked.index)?;
let mode = mode(&asked)?;
let mut behind = false;
let swapped = layouts::swap(connection, &mut asked)?;
let corrected = correct(connection, &mut asked, (words_version, &mut behind), swapped)?;
let k = asked.query.offset + asked.query.limit;
let both = k.max(HALF);
let passing = passing(connection, &asked, moment)?;
let held = Held { moment, documents, passing: passing.as_deref() };
let mut halves = Halves::default();
let ranked = match mode {
Mode::Words => halves.words(by_words(connection, &asked, held, k)?),
Mode::Vector => halves.vectors(floored(by_vector(connection, &asked, held, k)?, &asked)),
Mode::Sum(weight) => {
let words = halves.words(by_words(connection, &asked, held, both)?);
let vectors = halves.vectors(floored(by_vector(connection, &asked, held, both)?, &asked));
hybrid::fuse(&words, &vectors, weight)
}
Mode::Rerank => {
let words = halves.words(by_words(connection, &asked, held, both)?);
let docs: Vec<u32> = words.iter().map(|(_, doc)| *doc).collect();
halves.cosines = vectors::cosines(connection, asked.index, question(&asked)?, &docs)?;
hybrid::rerank(&words, &halves.cosines)
}
};
let page: Vec<(f64, u32)> = ranked.into_iter().skip(asked.query.offset).take(asked.query.limit).collect();
if let (Mode::Sum(_) | Mode::Words, Some(question)) = (mode, &asked.query.vector) {
let unread: Vec<u32> =
page.iter().map(|(_, doc)| *doc).filter(|doc| !halves.cosines.contains_key(doc)).collect();
halves.cosines.extend(vectors::cosines(connection, asked.index, question, &unread)?);
}
let hits = page.into_iter().map(|(score, doc)| hit(connection, asked.index, doc, score, &halves));
let hits = hits.collect::<Result<_>>()?;
let sought = match &asked.query.matches {
Some(ask) if !matches!(mode, Mode::Vector) => Some(sought(connection, &asked, ask)?),
_ => None,
};
let total = asked.query.total.then(|| total(connection, &asked, held)).transpose()?;
Ok(Answer { hits, corrected, behind, sought, total })
}
fn sought(connection: &Connection, asked: &Asked<'_>, ask: &Ask) -> Result<Sought> {
let mut sought = Sought::new(ask.clone(), &asked.settings.fields);
for (at, word) in asked.query.words.iter().enumerate() {
for form in forms(std::slice::from_ref(word), asked.settings) {
sought.key(form, at);
}
}
for at in prefixes(&asked.query) {
let word = &asked.query.words[at];
let Some(past) = past(&word.text) else { continue };
let typed = (at, word.text.chars().count());
for field in &asked.settings.fields {
let part = Part::written(field.number);
for term in terms_starting(connection, asked.index, part, (&word.text, &past))? {
sought.begun((part, term), typed);
}
}
}
Ok(sought)
}
fn mode(asked: &Asked<'_>) -> Result<Mode> {
let query = &asked.query;
let Some(question) = &query.vector else { return Ok(Mode::Words) };
let Some(vectors) = asked.settings.vectors else {
return Err(Error::invalid("a search by a vector of an index without vectors"));
};
if question.dimensions() != vectors.dimensions {
return Err(Error::invalid(format!(
"a vector of {} dimensions where the index holds {}",
question.dimensions(),
vectors.dimensions
)));
}
if query.words.is_empty() && !query.rerank {
return Ok(Mode::Vector);
}
let hybrid = asked.settings.hybrid;
let weight = match query.vector_weight {
Some(weight) => weight,
None if query.min_similarity.is_some() && (query.rerank || hybrid.rerank) => {
return Err(Error::invalid(
"a similarity floor keeps what a vector finds, and a rerank finds nothing by it",
));
}
None if query.rerank || hybrid.rerank => return Ok(Mode::Rerank),
None => hybrid.vector_weight,
};
Ok(match weight {
0.0 => Mode::Words,
1.0 => Mode::Vector,
weight => Mode::Sum(weight),
})
}
fn question<'a>(asked: &'a Asked<'_>) -> Result<&'a Question> {
asked.query.vector.as_ref().ok_or_else(|| Error::internal("a search by its vector has none"))
}
#[derive(Clone, Copy)]
struct Held<'a> {
moment: Moment,
documents: u64,
passing: Option<&'a [u32]>,
}
fn passing(connection: &Connection, asked: &Asked<'_>, moment: Moment) -> Result<Option<Vec<u32>>> {
let Some(conditions) = &asked.query.filter else { return Ok(None) };
let gone = asked.kept.gone(connection, moment)?;
let reader = Reader { connection, index: asked.index, settings: asked.settings, gone: &gone.docs };
Ok(match reader.passing(conditions)? {
Docs::All => None,
Docs::Only(docs) => Some(docs),
})
}
fn narrow(passing: usize, documents: u64, share: u64) -> bool {
#[cfg(test)]
if let Some(narrow) = NARROW.get() {
return narrow;
}
(passing as u64).saturating_mul(share) <= documents
}
#[cfg(test)]
thread_local! {
pub(crate) static NARROW: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
}
fn by_words(connection: &Connection, asked: &Asked<'_>, held: Held<'_>, k: usize) -> Result<Vec<(f64, u32)>> {
let stats = stats(connection, asked, held)?;
let mut source = Source::new(connection, asked, held.moment, &stats);
let Lists { mut lists, words } = lists(connection, asked, &stats, &mut source)?;
let found = match asked.query.prefix {
Prefix::Every => holding_every_word_first((&mut lists, &words), &mut source, held, k)?,
Prefix::Whole | Prefix::Last => ranked(&mut lists, &mut source, held, k)?,
};
#[cfg(test)]
check(connection, asked, (&stats, held), (&found, k))?;
Ok(found.into_iter().map(|(points, doc)| (score(points), doc)).collect())
}
fn total(connection: &Connection, asked: &Asked<'_>, held: Held<'_>) -> Result<Total> {
let stats = stats(connection, asked, held)?;
let mut source = Source::new(connection, asked, held.moment, &stats);
let Lists { mut lists, .. } = lists(connection, asked, &stats, &mut source)?;
let counted = count(&mut lists, &mut source, held.passing, MOST_COUNTED)?;
Ok(Total { count: counted.min(MOST_COUNTED) as u64, at_least: counted > MOST_COUNTED })
}
fn stats(connection: &Connection, asked: &Asked<'_>, held: Held<'_>) -> Result<Stats> {
Ok(Stats {
documents: held.documents,
tokens: tokens(connection, asked.index)?,
gone: asked.kept.gone(connection, held.moment)?,
segments: segments::of_index(connection, asked.index)?,
})
}
fn ranked(lists: &mut [List], source: &mut Source<'_>, held: Held<'_>, k: usize) -> Result<Vec<(u64, u32)>> {
match held.passing {
Some(docs) if narrow(docs.len(), held.documents, NARROW_WORDS) => best_of(lists, source, docs, k),
passing => best(lists, source, k, passing),
}
}
fn holding_every_word_first(
(lists, words): (&mut [List], &[Vec<usize>]),
source: &mut Source<'_>,
held: Held<'_>,
k: usize,
) -> Result<Vec<(u64, u32)>> {
let above = lists.iter().fold(0_u64, |sum, list| sum.saturating_add(list.most()));
let raised = |found: Vec<(u64, u32)>| found.into_iter().map(|(points, doc)| (points.saturating_add(above), doc));
if words.len() < 2 {
return Ok(raised(ranked(lists, source, held, k)?).collect());
}
let every = held_by_all(lists, words, source, held.passing)?;
let holding = Held { passing: Some(&every), ..held };
let mut first: Vec<(u64, u32)> = raised(ranked(&mut lists.to_vec(), source, holding, k)?).collect();
if first.len() < k {
let rest = ranked(lists, source, held, k)?.into_iter().filter(|(_, doc)| every.binary_search(doc).is_err());
first.extend(rest.take(k - every.len()));
}
Ok(first)
}
fn by_clusters(
connection: &Connection,
asked: &Asked<'_>,
held: Held<'_>,
k: usize,
) -> Result<Option<Vec<(f64, u32)>>> {
let Some(vectors) = asked.settings.vectors.filter(|vectors| vectors.recall.is_some()) else { return Ok(None) };
let state = clusters::state(connection, asked.index)?;
if state.phase != Phase::Serving || state.probes <= 0 {
return Ok(None);
}
let at = (asked.index, state.version, vectors.dimensions);
let kept = clusters::kept(&asked.kept.clusters, connection, at)?;
let question = question(asked)?;
let probe = Probe {
index: asked.index,
clusters: &kept,
question,
k,
probes: state.probes as usize,
rescored: state.rescored as usize,
passing: held.passing,
};
clusters::best(connection, &probe).map(Some)
}
fn by_vector(connection: &Connection, asked: &Asked<'_>, held: Held<'_>, k: usize) -> Result<Vec<(f64, u32)>> {
let among = match held.passing {
None => Among::Every,
Some(docs) if narrow(docs.len(), held.documents, NARROW_VECTORS) => Among::Only(docs),
Some(docs) => Among::Crossed(docs),
};
if !matches!(among, Among::Only(_))
&& let Some(found) = by_clusters(connection, asked, held, k)?
{
return Ok(found);
}
let scan = Scan { index: asked.index, question: question(asked)?, k, among };
let found = vectors::best(connection, &scan)?;
#[cfg(test)]
if CHECKED.get() {
let every = vectors::every(connection, &scan)?;
if every != found {
return Err(Error::internal(format!("found {found:?} where every vector gives {every:?}")));
}
}
Ok(found)
}
fn moment(connection: &Connection, index: i64) -> Result<(Moment, u64, i64)> {
let mut select = connection.prepare_cached(READ_INDEX).map_err(|error| sql_error("read an index", error))?;
let row = select.query_row([index], |row| {
let moment = Moment { index, normed: row.get(1)?, gone_version: row.get(2)?, lists_version: row.get(4)? };
Ok((moment, row.get::<_, i64>(0)?.max(0) as u64, row.get(3)?))
});
row.map_err(|error| sql_error("read an index", error))
}
struct Stats {
documents: u64,
tokens: HashMap<Part, u64>,
gone: Arc<Gone>,
segments: Vec<Segment>,
}
struct Lists {
lists: Vec<List>,
words: Vec<Vec<usize>>,
}
fn lists(connection: &Connection, asked: &Asked<'_>, stats: &Stats, source: &mut Source<'_>) -> Result<Lists> {
let mut found = keyed_lists(connection, asked, (stats, &mut *source))?;
let mut begun: HashMap<&str, Vec<usize>> = HashMap::new();
for at in prefixes(&asked.query) {
let text = asked.query.words[at].text.as_str();
if !begun.contains_key(text) {
let mut places = Vec::new();
for field in &asked.settings.fields {
let part = Part::written(field.number);
if let Some(list) = prefixed(connection, asked, (stats, &mut *source), (part, text))? {
places.push(found.lists.len());
found.lists.push(list);
}
}
begun.insert(text, places);
}
found.words[at].extend(&begun[text]);
}
Ok(found)
}
fn keyed_lists(
connection: &Connection,
asked: &Asked<'_>,
(stats, source): (&Stats, &mut Source<'_>),
) -> Result<Lists> {
let mut lists = Vec::new();
let mut placed: HashMap<(Part, String), usize> = HashMap::new();
for form in forms(&asked.query.words, asked.settings) {
if let Some(list) = list(connection, asked, (stats, &mut *source), &form)? {
placed.insert(form, lists.len());
lists.push(list);
}
}
let finding = |word: &Word| {
forms(std::slice::from_ref(word), asked.settings).iter().filter_map(|form| placed.get(form).copied()).collect()
};
Ok(Lists { lists, words: asked.query.words.iter().map(finding).collect() })
}
pub(super) fn prefixes(query: &Query) -> Vec<usize> {
let words = &query.words;
match query.prefix {
Prefix::Whole => Vec::new(),
Prefix::Last => {
words.len().checked_sub(1).filter(|last| halfway(&words[*last], &query.normal)).into_iter().collect()
}
Prefix::Every => (0..words.len()).filter(|at| long_enough(&words[*at])).take(MOST_PREFIXES).collect(),
}
}
pub(super) fn halfway(word: &Word, normal: &str) -> bool {
word.at.end == normal.len() && long_enough(word)
}
pub(super) fn long_enough(word: &Word) -> bool {
word.text.chars().count() >= LEAST_PREFIX
}
#[cfg(test)]
thread_local! {
static CHECKED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
#[cfg(test)]
pub(crate) fn checked<T>(run: impl FnOnce() -> T) -> T {
CHECKED.set(true);
let ran = run();
CHECKED.set(false);
ran
}
#[cfg(test)]
fn check(
connection: &Connection,
asked: &Asked<'_>,
(stats, held): (&Stats, Held<'_>),
(found, k): (&[(u64, u32)], usize),
) -> Result<()> {
if !CHECKED.get() {
return Ok(());
}
let mut source = Source::new(connection, asked, held.moment, stats);
let Lists { mut lists, words } = lists(connection, asked, stats, &mut source)?;
let every = match asked.query.prefix {
Prefix::Every => every_by_words(&mut lists, &words, &mut source, (held.passing, k))?,
Prefix::Whole | Prefix::Last => super::execute::every(&mut lists, &mut source, k, held.passing)?,
};
if every != found {
return Err(Error::internal(format!("found {found:?} where every posting gives {every:?}")));
}
Ok(())
}
#[cfg(test)]
fn every_by_words(
lists: &mut [List],
words: &[Vec<usize>],
source: &mut Source<'_>,
(passing, k): (Option<&[u32]>, usize),
) -> Result<Vec<(u64, u32)>> {
let above = lists.iter().fold(0_u64, |sum, list| sum.saturating_add(list.most()));
let mut holding: Option<HashSet<u32>> = None;
for word in words {
let mut docs = HashSet::new();
for &at in word {
docs.extend(lists[at].clone().into_postings(source)?.into_iter().map(|posting| posting.doc));
}
holding = Some(match holding {
Some(held) => held.intersection(&docs).copied().collect(),
None => docs,
});
}
let holding = holding.unwrap_or_default();
let mut every = super::execute::every(lists, source, usize::MAX, passing)?;
for (points, doc) in &mut every {
if holding.contains(doc) {
*points = points.saturating_add(above);
}
}
every.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
every.truncate(k);
Ok(every)
}
fn tokens(connection: &Connection, index: i64) -> Result<HashMap<Part, u64>> {
let failed = |error| sql_error("read an index's lengths", error);
let mut select = connection.prepare_cached(READ_PARTS).map_err(failed)?;
let rows = select.query_map([index], |row| Ok((Part(row.get(0)?), row.get::<_, i64>(1)?.max(0) as u64)));
rows.and_then(Iterator::collect).map_err(failed)
}
pub(super) fn forms(words: &[Word], settings: &Settings) -> Vec<(Part, String)> {
let mut forms: Vec<(Part, String)> = Vec::new();
for word in words {
let stem = word.stem.as_deref().unwrap_or(&word.text);
for field in &settings.fields {
let (written, stems) = (Part::written(field.number), Part::stems(field.number));
forms.push((written, word.text.clone()));
forms.push((stems, stem.to_owned()));
if word.stem.is_some() {
forms.push((written, stem.to_owned()));
}
}
}
let mut seen = HashSet::new();
forms.retain(|form| seen.insert(form.clone()));
forms
}
fn find(connection: &Connection, index: i64, part: Part, term: &str) -> Result<Option<(i64, i64)>> {
let mut select = connection.prepare_cached(FIND_KEY).map_err(|error| sql_error("find a key", error))?;
let found = select.query_row((index, part.0, term), |row| Ok((row.get(0)?, row.get(1)?)));
let found = found.optional();
found.map_err(|error| sql_error("find a key", error))
}
pub(super) fn held(connection: &Connection, asked: &Asked<'_>, word: &Word) -> Result<u64> {
let segments = segments::of_index(connection, asked.index)?;
let mut documents = 0;
for (part, term) in forms(std::slice::from_ref(word), asked.settings) {
if let Some((key, counted)) = find(connection, asked.index, part, &term)? {
documents += segments::holding(connection, &segments, key, counted)?;
}
}
Ok(documents)
}
fn correct(
connection: &Connection,
asked: &mut Asked<'_>,
(version, behind): (i64, &mut bool),
swapped: bool,
) -> Result<Option<String>> {
if !asked.settings.typo_tolerance {
return Ok(swapped.then(|| asked.query.normal.clone()));
}
let mut replaced = Vec::new();
let prefixes = prefixes(&asked.query);
for at in 0..asked.query.words.len() {
let word = &asked.query.words[at];
if word.text.chars().count() < 5 || held(connection, asked, word)? > 0 {
continue;
}
if prefixes.contains(&at) && begins_a_word(connection, asked, &word.text)? {
continue;
}
let corrector = corrector(connection, asked, version, behind)?;
let mut chosen: Option<(u64, Word)> = None;
for candidate in corrector.candidates(&word.text) {
let read = Word { stem: analyzer::stem(&candidate), text: candidate, at: word.at.clone() };
let documents = held(connection, asked, &read)?;
if documents > chosen.as_ref().map_or(0, |(most, _)| *most) {
chosen = Some((documents, read));
}
}
if let Some((_, read)) = chosen {
replaced.push((read.at.clone(), read.text.clone()));
asked.query.words[at] = read;
}
}
if replaced.is_empty() && !swapped {
return Ok(None);
}
Ok(Some(written(&asked.query.normal, replaced)))
}
fn written(normal: &str, replaced: Vec<(Range<usize>, String)>) -> String {
let mut apart: Vec<(Range<usize>, String)> = Vec::with_capacity(replaced.len());
for (at, word) in replaced {
if apart.last().is_none_or(|(last, _)| last.end <= at.start) {
apart.push((at, word));
}
}
let mut text = normal.to_owned();
for (at, word) in apart.into_iter().rev() {
text.replace_range(at, &word);
}
text
}
fn corrector(connection: &Connection, asked: &Asked<'_>, version: i64, behind: &mut bool) -> Result<Arc<Corrector>> {
if let Some(kept) = lock(&asked.kept.corrector).as_ref() {
*behind = kept.version != version;
return Ok(Arc::clone(kept));
}
let parts: Vec<Part> = asked.settings.fields.iter().map(|field| Part::written(field.number)).collect();
let built = Arc::new(Corrector::build(connection, asked.index, version, &parts)?);
*lock(&asked.kept.corrector) = Some(Arc::clone(&built));
Ok(built)
}
fn list(
connection: &Connection,
asked: &Asked<'_>,
(stats, source): (&Stats, &mut Source<'_>),
(part, term): &(Part, String),
) -> Result<Option<List>> {
let Some(found) = find(connection, asked.index, *part, term)? else { return Ok(None) };
keyed(connection, asked, (stats, source), (*part, found))
}
fn keyed(
connection: &Connection,
asked: &Asked<'_>,
(stats, source): (&Stats, &mut Source<'_>),
(part, (key, documents)): (Part, (i64, i64)),
) -> Result<Option<List>> {
let Some(weight) = asked.settings.weight(part.field()) else { return Ok(None) };
let within = |error: Error| error.within(format!("key {key}"));
let (released, listed, holding) =
pieces(connection, asked, (stats, source.moment), (key, documents)).map_err(within)?;
if holding == 0 {
return Ok(None);
}
let tokens = stats.tokens.get(&part).copied().unwrap_or(0);
let scale = part.weight(weight) * idf(stats.documents, holding);
let mut list = List::new(key, part, scale, average(tokens, stats.documents), Vec::new());
let gone = &stats.gone.docs;
onto(&mut list, &released.value.1, source, gone);
push_held(&mut list, legacy::head(connection, asked.index, key)?, gone);
for piece in &listed {
onto(&mut list, &piece.value.1, source, gone);
}
Ok((!list.is_empty()).then_some(list))
}
fn onto(list: &mut List, listed: &Listed, source: &mut Source<'_>, gone: &HashSet<u32>) {
match listed {
Listed::Packed(directory, best) => {
source.place(list.key, list.len(), directory);
list.reserve(directory.blocks.len());
for block in &directory.blocks {
list.push(list.packed(block));
}
list.seed(best.iter().filter(|posting| !gone.contains(&posting.doc)));
}
Listed::Short(postings) => push_held(list, postings.clone(), gone),
Listed::Legacy(legacy) => legacy.onto(list),
Listed::Nothing => {}
}
}
fn pieces(
connection: &Connection,
asked: &Asked<'_>,
(stats, moment): (&Stats, Moment),
(key, documents): (i64, i64),
) -> Result<(KeptPiece, Vec<KeptPiece>, u64)> {
let kept = (asked.memory, moment);
let released = asked.kept.legacy(connection, kept, key)?;
let mut listed = Vec::new();
let mut holding = documents;
for segment in &stats.segments {
if let Some(piece) = asked.kept.piece(connection, kept, segment, key)? {
if !segment.folded {
holding += piece.value.0;
}
listed.push(piece);
}
}
Ok((released, listed, holding.max(0) as u64))
}
fn prefixed(
connection: &Connection,
asked: &Asked<'_>,
(stats, source): (&Stats, &mut Source<'_>),
(part, prefix): (Part, &str),
) -> Result<Option<List>> {
let Some(weight) = asked.settings.weight(part.field()) else { return Ok(None) };
let Some(past) = past(prefix) else { return Ok(None) };
let mut postings = Vec::new();
for found in words_starting(connection, asked.index, part, (prefix, &past))? {
if let Some(list) = keyed(connection, asked, (stats, &mut *source), (part, found))? {
postings.extend(list.into_postings(source)?);
}
}
let joined = joined(postings);
if joined.is_empty() {
return Ok(None);
}
let tokens = stats.tokens.get(&part).copied().unwrap_or(0);
let scale = weight * PREFIXED * idf(stats.documents, joined.len() as u64);
Ok(Some(List::joined(part, scale, average(tokens, stats.documents), joined)))
}
fn joined(mut postings: Vec<Posting>) -> Vec<Posting> {
postings.sort_unstable_by_key(|posting| posting.doc);
let mut joined: Vec<Posting> = Vec::with_capacity(postings.len());
for posting in postings {
match joined.last_mut() {
Some(last) if last.doc == posting.doc => last.tf = last.tf.saturating_add(posting.tf),
_ => joined.push(posting),
}
}
joined
}
fn words_starting(
connection: &Connection,
index: i64,
part: Part,
(prefix, past): (&str, &str),
) -> Result<Vec<(i64, i64)>> {
let failed = |error| sql_error("find the words a prefix begins", error);
let mut select = connection.prepare_cached(FIND_PREFIXED).map_err(failed)?;
let most = MOST_PREFIXED as i64;
let rows = select.query_map((index, part.0, prefix, past, most), |row| Ok((row.get(0)?, row.get(1)?)));
rows.and_then(Iterator::collect).map_err(failed)
}
fn terms_starting(
connection: &Connection,
index: i64,
part: Part,
(prefix, past): (&str, &str),
) -> Result<Vec<String>> {
let failed = |error| sql_error("find the words a prefix begins", error);
let mut select = connection.prepare_cached(FIND_PREFIXED).map_err(failed)?;
let most = MOST_PREFIXED as i64;
let rows = select.query_map((index, part.0, prefix, past, most), |row| row.get(2));
rows.and_then(Iterator::collect).map_err(failed)
}
pub(super) fn begins_a_word(connection: &Connection, asked: &Asked<'_>, prefix: &str) -> Result<bool> {
let Some(past) = past(prefix) else { return Ok(false) };
let failed = |error| sql_error("find a word a prefix begins", error);
let mut select = connection.prepare_cached(BEGINS_A_WORD).map_err(failed)?;
for field in &asked.settings.fields {
let part = Part::written(field.number);
if select.query_row((asked.index, part.0, prefix, &past), |row| row.get(0)).map_err(failed)? {
return Ok(true);
}
}
Ok(false)
}
fn past(prefix: &str) -> Option<String> {
let mut letters: Vec<char> = prefix.chars().collect();
while let Some(last) = letters.pop() {
if let Some(next) = (u32::from(last) + 1..=u32::from(char::MAX)).find_map(char::from_u32) {
letters.push(next);
return Some(letters.into_iter().collect());
}
}
None
}
fn push_held(list: &mut List, mut postings: Vec<Posting>, gone: &HashSet<u32>) {
postings.retain(|posting| !gone.contains(&posting.doc));
if !postings.is_empty() {
let block = list.in_hand(postings);
list.push(block);
}
}
fn hit(connection: &Connection, index: i64, doc: u32, score: f64, halves: &Halves) -> Result<Ranked> {
let failed = |error| sql_error(format!("read document {doc}"), error);
let mut select = connection.prepare_cached(READ_HIT).map_err(failed)?;
let found = select.query_row((index, doc), |row| Ok((row.get(0)?, row.get(1)?))).optional().map_err(failed)?;
let (id, value) = found.ok_or_else(|| Error::corrupt(format!("document {doc} a search found is not kept")))?;
let (text_score, similarity) = (halves.words.get(&doc).copied(), halves.cosines.get(&doc).copied());
Ok(Ranked { id, value, score, text_score, similarity })
}
struct Source<'a> {
connection: &'a Connection,
asked: &'a Asked<'a>,
moment: Moment,
gone: &'a HashSet<u32>,
chunks: HashMap<(Part, u32), Arc<Chunk>>,
last: Option<((Part, u32), Arc<Chunk>)>,
keyed: Vec<Keyed<'a>>,
bytes: Vec<u8>,
}
struct Keyed<'a> {
key: i64,
placed: Vec<(usize, Arc<Directory>)>,
handle: Option<(i64, Blob<'a>)>,
}
impl Fetch for Source<'_> {
fn block(&mut self, list: &List, index: usize, out: &mut Vec<Posting>) -> Result<()> {
let within =
|error: Error| error.within(format!("key {}: block at document {}", list.key, list.first_of(index)));
if let Some(placed) = self.placed_at(list.key, index) {
return self.packed_block(placed, out).map_err(within);
}
let pairs = legacy::block(self.connection, list.key, list.first_of(index)).map_err(within)?;
out.clear();
out.extend(pairs.into_iter().map(|(doc, tf)| Posting { doc, tf, len: 0 }));
self.leave_gone(out);
Ok(())
}
fn lengths(&mut self, part: Part, mut postings: &mut [Posting]) -> Result<()> {
while let Some(first) = postings.first() {
let chunk = first.doc / NORMS;
let lengths = self.chunk(part, chunk)?;
let (these, rest) = postings.split_at_mut(postings.partition_point(|posting| posting.doc / NORMS == chunk));
for posting in these {
posting.len = lengths.length(posting.doc);
}
postings = rest;
}
Ok(())
}
}
type Placed = (usize, usize, usize);
impl<'a> Source<'a> {
fn new(connection: &'a Connection, asked: &'a Asked<'a>, moment: Moment, stats: &'a Stats) -> Source<'a> {
Source {
connection,
asked,
moment,
gone: &stats.gone.docs,
chunks: HashMap::new(),
last: None,
keyed: Vec::new(),
bytes: Vec::new(),
}
}
fn place(&mut self, key: i64, first: usize, directory: &Arc<Directory>) {
let at = match self.keyed.iter().position(|keyed| keyed.key == key) {
Some(at) => at,
None => {
self.keyed.push(Keyed { key, placed: Vec::new(), handle: None });
self.keyed.len() - 1
}
};
self.keyed[at].placed.push((first, Arc::clone(directory)));
}
fn placed_at(&self, key: i64, index: usize) -> Option<Placed> {
let at = self.keyed.iter().position(|keyed| keyed.key == key)?;
let pieces = &self.keyed[at].placed;
let piece = pieces.partition_point(|(first, _)| *first <= index).checked_sub(1)?;
let (first, directory) = &pieces[piece];
(index < first + directory.blocks.len()).then_some((at, piece, index - first))
}
fn packed_block(&mut self, (at, piece, index): Placed, out: &mut Vec<Posting>) -> Result<()> {
let failed = |error| sql_error("read a run", error);
let connection = self.connection;
let keyed = &mut self.keyed[at];
let directory = &keyed.placed[piece].1;
let run = directory.runs[directory.run_of(index)].id;
let handle = match keyed.handle.take() {
Some((on, mut handle)) if on != run => {
handle.reopen(run).map_err(failed)?;
handle
}
Some((_, handle)) => handle,
None => connection.blob_open(MAIN_DB, RUNS, BLOCKS, run, true).map_err(failed)?,
};
let handle = &keyed.handle.insert((run, handle)).1;
let lying = directory.bytes_of(index, handle.len())?;
self.bytes.resize(lying.len(), 0);
handle.read_at_exact(&mut self.bytes, lying.start).map_err(failed)?;
packed::unpack(&self.bytes, directory.blocks[index].first, out)?;
self.leave_gone(out);
Ok(())
}
fn leave_gone(&self, postings: &mut Vec<Posting>) {
if !self.gone.is_empty() {
postings.retain(|posting| !self.gone.contains(&posting.doc));
}
}
fn chunk(&mut self, part: Part, chunk: u32) -> Result<&Chunk> {
let last = match self.last.take() {
Some(last) if last.0 == (part, chunk) => last,
_ => ((part, chunk), self.read_chunk(part, chunk)?),
};
Ok(&self.last.insert(last).1)
}
fn read_chunk(&mut self, part: Part, chunk: u32) -> Result<Arc<Chunk>> {
if let Some(read) = self.chunks.get(&(part, chunk)) {
return Ok(Arc::clone(read));
}
let read = self.asked.kept.chunk(self.connection, self.asked.memory, self.moment, (part, chunk))?;
self.chunks.insert((part, chunk), Arc::clone(&read));
Ok(read)
}
}
#[cfg(test)]
mod tests {
use super::past;
#[test]
fn past_a_prefix_is_the_least_text_no_word_it_begins_reaches() {
assert_eq!(past("crypt").as_deref(), Some("crypu"));
assert_eq!(past("крипто").as_deref(), Some("криптп"));
assert_eq!(past("\u{d7ff}").as_deref(), Some("\u{e000}"));
assert_eq!(past("a\u{10ffff}").as_deref(), Some("b"));
assert_eq!(past("\u{10ffff}"), None);
let begun = ["crypt", "cryptography", "crypt\u{10ffff}"];
assert!(begun.iter().all(|word| *word < past("crypt").unwrap().as_str()));
}
}