use std::marker::PhantomData;
use std::sync::Arc;
use serde::Serialize;
use serde::de::DeserializeOwned;
use serde_json::Value;
use super::analyzer;
use super::engine::Search;
use super::filter::{self, Condition};
#[cfg(feature = "replication")]
use super::forward::Passed;
use super::open::{Data, OpenIndex, Status};
use super::read::Query;
use super::settings::{Settings, Wanted, check_hybrid};
#[cfg(feature = "sql")]
use super::table_index::ReadRows;
use super::vectors::Question;
use super::write::{Incoming, Prepared};
#[cfg(feature = "sql")]
use crate::Transaction;
use crate::{Error, Key, Result, Store};
const MOST_DOCUMENT: usize = 1 << 20;
const MOST_ID: usize = 1 << 10;
const MOST_TEXT: usize = 1 << 10;
const MOST_WORDS: usize = 32;
const LEAST_PREFIX: usize = 2;
const MOST_HITS: usize = 1000;
const LIMIT: usize = 10;
pub(super) const MOST_MANY: usize = 1000;
const MOST_MANY_BYTES: usize = 16 << 20;
#[must_use = "an index opens at `open`"]
pub struct IndexBuilder<'s, T> {
store: &'s Store,
name: String,
wanted: Wanted,
_value: PhantomData<fn() -> T>,
}
impl<T> std::fmt::Debug for IndexBuilder<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("IndexBuilder").field("name", &self.name).field("wanted", &self.wanted).finish()
}
}
impl<'s, T: Serialize + DeserializeOwned> IndexBuilder<'s, T> {
pub(crate) fn new(store: &'s Store, name: &str) -> Self {
IndexBuilder { store, name: name.to_owned(), wanted: Wanted::default(), _value: PhantomData }
}
pub fn field(mut self, path: &str, weight: f64) -> Self {
self.wanted.fields.push((path.to_owned(), weight));
self
}
pub fn fields<S: AsRef<str>>(mut self, paths: impl IntoIterator<Item = S>) -> Self {
self.wanted.fields.extend(paths.into_iter().map(|path| (path.as_ref().to_owned(), 1.0)));
self
}
pub fn filters<S: AsRef<str>>(mut self, paths: impl IntoIterator<Item = S>) -> Self {
self.wanted.filters.extend(paths.into_iter().map(|path| path.as_ref().to_owned()));
self
}
pub fn typo_tolerance(mut self, on: bool) -> Self {
self.wanted.typo_tolerance = on;
self
}
pub fn vectors(mut self, dimensions: usize) -> Self {
self.wanted.dimensions = Some(dimensions);
self
}
pub fn recall(mut self, recall: f64) -> Self {
self.wanted.recall = Some(recall);
self
}
pub fn vector_weight(mut self, weight: f64) -> Self {
self.wanted.vector_weight = Some(weight);
self
}
pub fn rerank(mut self) -> Self {
self.wanted.rerank = true;
self
}
pub fn rebuild(mut self, rebuild: Rebuild) -> Self {
self.wanted.manual = rebuild == Rebuild::Manual;
self
}
pub fn open(self) -> Result<Index<T>> {
self.opened(false)
}
pub fn reindex(self) -> Result<Index<T>> {
self.opened(true)
}
fn opened(self, reindex: bool) -> Result<Index<T>> {
let within = |error: Error| error.within(format!("index {}", self.name));
let search = Search::of(self.store).map_err(within)?;
let open = crate::sqlite::own_work(|| search.open_index(&self.name, &self.wanted, reindex)).map_err(within)?;
Ok(Index::of_documents(search, open))
}
}
#[cfg(any(feature = "wire", feature = "replication"))]
pub(crate) fn open_as_it_is<T: Serialize + DeserializeOwned>(store: &Store, name: &str) -> Result<Index<T>> {
let within = |error: Error| error.within(format!("index {name}"));
let search = Search::of(store).map_err(within)?;
let open = search.open_existing(name).map_err(within)?;
Ok(Index::of_documents(search, open))
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Rebuild {
#[default]
Automatic,
Manual,
}
pub struct Index<T> {
pub(crate) search: Arc<Search>,
pub(crate) open: Arc<OpenIndex>,
#[cfg(feature = "sql")]
pub(crate) read_rows: Option<ReadRows<T>>,
pub(crate) _value: PhantomData<fn() -> T>,
}
impl<T> Clone for Index<T> {
fn clone(&self) -> Self {
Index {
search: Arc::clone(&self.search),
open: Arc::clone(&self.open),
#[cfg(feature = "sql")]
read_rows: self.read_rows.clone(),
_value: PhantomData,
}
}
}
impl<T> Index<T> {
#[cfg(feature = "wire")]
pub(crate) fn follows_table(&self) -> bool {
#[cfg(feature = "sql")]
return self.read_rows.is_some();
#[cfg(not(feature = "sql"))]
false
}
fn of_documents(search: Arc<Search>, open: Arc<OpenIndex>) -> Self {
#[cfg(feature = "sql")]
return Index { search, open, read_rows: None, _value: PhantomData };
#[cfg(not(feature = "sql"))]
Index { search, open, _value: PhantomData }
}
}
impl<T> std::fmt::Debug for Index<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Index").field("name", &self.open.name).finish()
}
}
impl<T: DeserializeOwned> Index<T> {
pub fn name(&self) -> &str {
&self.open.name
}
pub fn status(&self) -> Result<Status> {
self.search.status(&self.open).map_err(|error| error.within(format!("index {}", self.open.name)))
}
pub fn ready(&self) -> Result<()> {
self.search.ready(&self.open).map_err(|error| error.within(format!("index {}", self.open.name)))
}
pub fn search(&self, text: &str) -> SearchCall<'_, T> {
SearchCall {
index: self,
#[cfg(feature = "sql")]
tx: None,
text: text.to_owned(),
vector: None,
vector_weight: None,
rerank: false,
prefix: false,
filter: Vec::new(),
offset: 0,
limit: LIMIT,
}
}
pub fn search_vector<'i>(&'i self, vector: &'i [f32]) -> SearchCall<'i, T> {
self.search("").vector(vector)
}
pub(super) fn found(&self, query: Query) -> Result<Found<T>> {
let answer = self.search.search(&self.open, query)?;
let hits = answer.hits.into_iter().map(|(id, value, score)| {
let value = decode(&value).map_err(|error| error.within(format!("id {id:?}")))?;
Ok(Hit { id, value, score })
});
Ok(Found { hits: hits.collect::<Result<_>>()?, corrected: answer.corrected })
}
}
impl<T: Serialize + DeserializeOwned> Index<T> {
pub fn set(&self, id: impl Key, value: &T) -> Result<()> {
self.set_given(Given { id: id.text().into_owned(), value, vector: None })
}
pub fn id(&self, id: impl Key) -> DocumentCall<'_, T> {
DocumentCall { index: self, id: id.text().into_owned(), vector: None }
}
fn set_given(&self, given: Given<'_, T>) -> Result<()> {
let within = |error: Error| error.within(format!("index {}: id {:?}", self.open.name, given.id));
#[cfg(feature = "replication")]
if self.search.file.is_copy() {
return self.pass_on_set(std::slice::from_ref(&given)).map_err(within);
}
let document = |data: &Data| Ok(vec![prepared(data.id, &given, &data.settings)?]);
self.search.set(&self.open, document).map_err(within)
}
pub fn set_many<'v>(&self, documents: impl IntoIterator<Item = impl Document<'v, T>>) -> Result<()>
where
T: 'v,
{
let documents: Vec<Given<'v, T>> = documents.into_iter().map(Given::of).collect();
self.set_all(documents)
}
pub(super) fn set_all(&self, documents: Vec<Given<'_, T>>) -> Result<()> {
let within = |error: Error| error.within(format!("index {}", self.open.name));
if documents.len() > MOST_MANY {
let said = format!("a set_many of {} documents, past {MOST_MANY}", documents.len());
return Err(within(Error::limit(said)));
}
#[cfg(feature = "replication")]
if self.search.file.is_copy() {
return self.pass_on_set(&documents).map_err(within);
}
let all = |data: &Data| prepared_many(&documents, data);
self.search.set(&self.open, all).map_err(within)
}
pub fn delete(&self, id: impl Key) -> Result<bool> {
let id = id.text();
let within = |error: Error| error.within(format!("index {}: id {id:?}", self.open.name));
let checked = checked(&id).map_err(within)?.to_owned();
#[cfg(feature = "replication")]
if self.search.file.is_copy() {
let store = self.search.store().map_err(within)?;
return super::forward::pass_on_delete(&store, &self.open.name, &checked).map_err(within);
}
self.search.delete(&self.open, checked).map_err(within)
}
#[cfg(feature = "replication")]
fn pass_on_set(&self, documents: &[Given<'_, T>]) -> Result<()> {
pass_on_documents(&self.search, &self.open.name, || documents.iter().map(Passed::of).collect())
}
pub fn get(&self, id: impl Key) -> Result<Option<T>> {
let id = id.text();
let within = |error: Error| error.within(format!("index {}: id {id:?}", self.open.name));
let Some(value) = self.search.get(&self.open, checked(&id).map_err(within)?).map_err(within)? else {
return Ok(None);
};
decode(&value).map(Some).map_err(within)
}
}
#[must_use = "a document is set at `set`"]
pub struct DocumentCall<'a, T> {
index: &'a Index<T>,
id: String,
vector: Option<Option<&'a [f32]>>,
}
impl<T> std::fmt::Debug for DocumentCall<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("DocumentCall").field("id", &self.id).finish_non_exhaustive()
}
}
impl<'a, T: Serialize + DeserializeOwned> DocumentCall<'a, T> {
pub fn vector(mut self, vector: &'a [f32]) -> Self {
self.vector = Some(Some(vector));
self
}
pub fn without_vector(mut self) -> Self {
self.vector = Some(None);
self
}
pub fn set(self, value: &T) -> Result<()> {
self.index.set_given(Given { id: self.id, value, vector: self.vector })
}
}
pub trait Document<'v, T> {
fn parts(self) -> (String, &'v T, Option<Option<&'v [f32]>>);
}
impl<'v, K: Key, T> Document<'v, T> for (K, &'v T) {
fn parts(self) -> (String, &'v T, Option<Option<&'v [f32]>>) {
(self.0.text().into_owned(), self.1, None)
}
}
impl<'v, K: Key, T> Document<'v, T> for (K, &'v T, &'v [f32]) {
fn parts(self) -> (String, &'v T, Option<Option<&'v [f32]>>) {
(self.0.text().into_owned(), self.1, Some(Some(self.2)))
}
}
impl<'v, K: Key, T> Document<'v, T> for (K, &'v T, &'v Vec<f32>) {
fn parts(self) -> (String, &'v T, Option<Option<&'v [f32]>>) {
(self.0.text().into_owned(), self.1, Some(Some(self.2)))
}
}
impl<'v, K: Key, T> Document<'v, T> for (K, &'v T, Option<&'v [f32]>) {
fn parts(self) -> (String, &'v T, Option<Option<&'v [f32]>>) {
(self.0.text().into_owned(), self.1, Some(self.2))
}
}
#[cfg(feature = "replication")]
pub(super) fn pass_on_documents(
search: &Search,
name: &str,
passed: impl FnOnce() -> Result<Vec<Passed>>,
) -> Result<()> {
if search.lent_by.is_some() {
return Err(Error::new(
crate::ErrorKind::Unavailable,
"a copy passes no set of an index in a database's file to its home yet",
));
}
super::forward::pass_on_set(&search.store()?, name, &passed()?)
}
pub(super) struct Given<'v, T> {
pub(super) id: String,
pub(super) value: &'v T,
pub(super) vector: Option<Option<&'v [f32]>>,
}
impl<'v, T> Given<'v, T> {
fn of(document: impl Document<'v, T>) -> Self {
let (id, value, vector) = document.parts();
Given { id, value, vector }
}
}
#[must_use = "a search runs at `run`"]
pub struct SearchCall<'i, T> {
index: &'i Index<T>,
#[cfg(feature = "sql")]
tx: Option<&'i Transaction<'i>>,
text: String,
vector: Option<&'i [f32]>,
vector_weight: Option<f64>,
rerank: bool,
prefix: bool,
filter: Vec<Condition>,
offset: usize,
limit: usize,
}
impl<T> std::fmt::Debug for SearchCall<'_, T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SearchCall").field("text", &self.text).field("offset", &self.offset).finish()
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Found<T> {
pub hits: Vec<Hit<T>>,
pub corrected: Option<String>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct Hit<T> {
pub id: String,
pub value: T,
pub score: f64,
}
impl<'i, T: DeserializeOwned> SearchCall<'i, T> {
pub fn vector(mut self, vector: &'i [f32]) -> Self {
self.vector = Some(vector);
self
}
pub fn vector_weight(mut self, weight: f64) -> Self {
self.vector_weight = Some(weight);
self
}
pub fn rerank(mut self) -> Self {
self.rerank = true;
self
}
pub fn prefix(mut self) -> Self {
self.prefix = true;
self
}
pub fn filter(mut self, condition: Condition) -> Self {
self.filter.push(condition);
self
}
#[cfg(feature = "sql")]
pub(crate) fn in_tx(mut self, tx: &'i Transaction<'i>) -> Self {
self.tx = Some(tx);
self
}
pub fn limit(mut self, limit: usize) -> Self {
self.limit = limit;
self
}
pub fn offset(mut self, offset: usize) -> Self {
self.offset = offset;
self
}
pub fn run(self) -> Result<Found<T>> {
let name = &self.index.open.name;
let within = |error: Error| error.within(format!("index {name}"));
let query = self.query().map_err(within)?;
#[cfg(feature = "sql")]
if let Some(read_rows) = &self.index.read_rows {
return super::table_index::found(self.index, &**read_rows, query, self.tx).map_err(within);
}
self.index.found(query).map_err(within)
}
#[cfg(any(all(feature = "wire", feature = "sql"), feature = "async"))]
pub(crate) fn asked(self) -> Result<(&'i Index<T>, Query)> {
let name = &self.index.open.name;
let query = self.query().map_err(|error| error.within(format!("index {name}")))?;
Ok((self.index, query))
}
fn query(&self) -> Result<Query> {
if self.text.len() > MOST_TEXT {
return Err(Error::limit(format!("a search's text of {} bytes, past {MOST_TEXT}", self.text.len())));
}
if self.limit == 0 {
return Err(Error::invalid("a search asks for at least one hit"));
}
if self.offset.saturating_add(self.limit) > MOST_HITS {
return Err(Error::limit(format!(
"a search reaches its {MOST_HITS}th hit at most, offset and limit together"
)));
}
let normal = analyzer::normalize(&self.text);
let mut words = analyzer::words_of(&normal);
words.truncate(MOST_WORDS);
let prefix = self.prefix
&& words
.last()
.is_some_and(|last| last.at.end == normal.len() && last.text.chars().count() >= LEAST_PREFIX);
Ok(Query {
normal,
words,
vector: self.question()?,
vector_weight: self.vector_weight,
rerank: self.rerank,
prefix,
filter: if self.filter.is_empty() { None } else { Some(filter::asked(&self.filter)?) },
offset: self.offset,
limit: self.limit,
})
}
fn question(&self) -> Result<Option<Question>> {
let Some(vector) = self.vector else {
if self.vector_weight.is_some() || self.rerank {
return Err(Error::invalid("a vector weight or a rerank for a search without a vector"));
}
return Ok(None);
};
check_hybrid(self.vector_weight, self.rerank)?;
if self.rerank && self.text.trim().is_empty() {
return Err(Error::invalid("a rerank orders a search's words' hits, and a search without words has none"));
}
Question::new(vector).map(Some)
}
}
fn prepared<T: Serialize>(index: i64, given: &Given<'_, T>, settings: &Settings) -> Result<Prepared> {
let (tree, bytes) = json(given.value)?;
let incoming = Incoming { id: checked(&given.id)?.to_owned(), tree, bytes, vector: given.vector };
Prepared::new(index, incoming, settings)
}
pub(super) trait ToSet {
fn id(&self) -> &str;
fn prepared(self, data: &Data) -> Result<Prepared>;
}
impl<T: Serialize> ToSet for &Given<'_, T> {
fn id(&self) -> &str {
&self.id
}
fn prepared(self, data: &Data) -> Result<Prepared> {
prepared(data.id, self, &data.settings)
}
}
pub(super) fn prepared_many(documents: impl IntoIterator<Item = impl ToSet>, data: &Data) -> Result<Vec<Prepared>> {
let documents = documents.into_iter();
let mut prepared_all = Vec::with_capacity(documents.size_hint().0);
let mut bytes = 0;
for (at, document) in documents.enumerate() {
let id = document.id().to_owned();
let place = |error: Error| error.within(format!("document {at}, id {id:?}"));
let document = document.prepared(data).map_err(place)?;
bytes += document.value.len();
if bytes > MOST_MANY_BYTES {
return Err(Error::limit(format!("a set_many past {} MiB as JSON", MOST_MANY_BYTES >> 20)));
}
prepared_all.push(document);
}
Ok(prepared_all)
}
pub(super) fn json<T: Serialize>(value: &T) -> Result<(Value, Vec<u8>)> {
let tree = serde_json::to_value(value).map_err(|error| Error::invalid(format!("a document: {error}")))?;
let bytes = serde_json::to_vec(&tree).map_err(|error| Error::invalid(format!("a document: {error}")))?;
if bytes.len() > MOST_DOCUMENT {
return Err(Error::limit(format!("a document of {} bytes as JSON, past 1 MiB", bytes.len())));
}
Ok((tree, bytes))
}
fn decode<T: DeserializeOwned>(value: &[u8]) -> Result<T> {
serde_json::from_slice(value).map_err(|error| Error::invalid(format!("a document of another type: {error}")))
}
pub(super) fn checked(id: &str) -> Result<&str> {
if id.is_empty() {
return Err(Error::invalid("an empty id"));
}
if id.len() > MOST_ID {
return Err(Error::invalid(format!("an id of {} bytes, past {MOST_ID}", id.len())));
}
Ok(id)
}
#[cfg(test)]
#[path = "index_tests.rs"]
mod tests;