use std::fmt;
use std::future::Future;
use std::sync::Arc;
use serde::Serialize;
use serde::de::DeserializeOwned;
use super::Store;
use super::oneshot::pending;
use super::run;
use crate::cancel;
use crate::pool::Pool;
use crate::search::Encoded;
use crate::{Key, Result};
#[cfg(feature = "sql")]
pub use crate::search::TxTableIndex;
pub use crate::search::{
Condition, Document, Found, Hit, Listed, Match, Rebuild, Status, and, eq, is_in, missing, or, range,
};
impl Store {
pub fn index<T: Serialize + DeserializeOwned>(&self, name: &str) -> IndexBuilder<'_, T> {
IndexBuilder { builder: self.blocking().index(name), pool: self.pool() }
}
pub fn drop_index(&self, name: &str) -> impl Future<Output = Result<bool>> + Send + 'static {
let (store, what) = (self.blocking().clone(), format!("index {name}: its drop"));
let name = name.to_owned();
run::blocking(self.pool(), None, what, move || store.drop_index(&name))
}
}
pub fn list(store: &Store) -> impl Future<Output = Result<Vec<Listed>>> + Send + 'static {
let blocking = store.blocking().clone();
run::read(store.pool(), format!("{blocking:?}: its indexes"), move || crate::search::list(&blocking))
}
#[must_use = "an index opens at `open`"]
pub struct IndexBuilder<'s, T> {
builder: crate::search::IndexBuilder<'s, T>,
pool: &'s Arc<Pool>,
}
impl<T> fmt::Debug for IndexBuilder<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.builder, f)
}
}
impl<'s, T: Serialize + DeserializeOwned> IndexBuilder<'s, T> {
pub fn field(self, path: &str, weight: f64) -> Self {
self.changed(|builder| builder.field(path, weight))
}
pub fn fields<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Self {
self.changed(|builder| builder.fields(paths))
}
pub fn filters<S: AsRef<str>>(self, paths: impl IntoIterator<Item = S>) -> Self {
self.changed(|builder| builder.filters(paths))
}
pub fn typo_tolerance(self, on: bool) -> Self {
self.changed(|builder| builder.typo_tolerance(on))
}
pub fn layouts<S: AsRef<str>>(self, names: impl IntoIterator<Item = S>) -> Self {
self.changed(|builder| builder.layouts(names))
}
pub fn vectors(self, dimensions: usize) -> Self {
self.changed(|builder| builder.vectors(dimensions))
}
pub fn recall(self, recall: f64) -> Self {
self.changed(|builder| builder.recall(recall))
}
pub fn vector_weight(self, weight: f64) -> Self {
self.changed(|builder| builder.vector_weight(weight))
}
pub fn rerank(self) -> Self {
self.changed(crate::search::IndexBuilder::rerank)
}
pub fn rebuild(self, rebuild: Rebuild) -> Self {
self.changed(|builder| builder.rebuild(rebuild))
}
pub fn open(self) -> Result<Index<T>> {
Ok(Index { index: self.builder.open()?, pool: Arc::clone(self.pool) })
}
pub fn reindex(self) -> Result<Index<T>> {
Ok(Index { index: self.builder.reindex()?, pool: Arc::clone(self.pool) })
}
fn changed(
self,
change: impl FnOnce(crate::search::IndexBuilder<'s, T>) -> crate::search::IndexBuilder<'s, T>,
) -> Self {
IndexBuilder { builder: change(self.builder), pool: self.pool }
}
}
pub struct Index<T> {
index: crate::search::Index<T>,
pool: Arc<Pool>,
}
impl<T> Clone for Index<T> {
fn clone(&self) -> Self {
Index { index: self.index.clone(), pool: Arc::clone(&self.pool) }
}
}
impl<T> fmt::Debug for Index<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.index, f)
}
}
impl<T> From<crate::search::Index<T>> for Index<T> {
fn from(index: crate::search::Index<T>) -> Index<T> {
let pool = pool_of(index.store());
Index { index, pool }
}
}
impl<T> Index<T> {
pub fn blocking(&self) -> &crate::search::Index<T> {
&self.index
}
}
impl<T: DeserializeOwned + Send + 'static> Index<T> {
pub fn name(&self) -> &str {
self.index.name()
}
pub fn status(&self) -> impl Future<Output = Result<Status>> + Send + 'static {
let index = self.index.clone();
run::read(&self.pool, format!("index {}: its status", self.name()), move || index.status())
}
pub fn ready(&self) -> impl Future<Output = Result<()>> + Send + 'static {
ready(self.index.clone(), Arc::clone(&self.pool))
}
pub fn search(&self, text: &str) -> SearchCall<'_, T> {
SearchCall { call: self.index.search(text), pool: &self.pool }
}
pub fn search_vector<'i>(&'i self, vector: &'i [f32]) -> SearchCall<'i, T> {
SearchCall { call: self.index.search_vector(vector), pool: &self.pool }
}
}
impl<T: Serialize + DeserializeOwned + Send + 'static> Index<T> {
pub fn get(&self, id: impl Key) -> impl Future<Output = Result<Option<T>>> + Send + 'static {
let (index, id) = (self.index.clone(), id.text().into_owned());
run::point(&self.pool, format!("index {}: a get", self.name()), move || index.get(&id))
}
pub fn set(&self, id: impl Key, value: &T) -> impl Future<Output = Result<()>> + Send + 'static {
self.set_encoded(Encoded::new(id.text().into_owned(), value, None))
}
pub fn id(&self, id: impl Key) -> DocumentCall<'_, T> {
DocumentCall { index: self, id: id.text().into_owned(), vector: None }
}
pub fn set_many<'v>(
&self,
documents: impl IntoIterator<Item = impl Document<'v, T>>,
) -> impl Future<Output = Result<()>> + Send + 'static
where
T: 'v,
{
let documents: Vec<Encoded> = documents
.into_iter()
.map(|document| {
let (id, value, vector) = document.parts();
Encoded::new(id, value, vector)
})
.collect();
let index = self.index.clone();
run::write(&self.pool, format!("index {}: a set_many", self.name()), move |answer| {
index.set_many_then(documents, move |set| answer.send(set));
})
}
pub fn delete(&self, id: impl Key) -> impl Future<Output = Result<bool>> + Send + 'static {
let (index, id) = (self.index.clone(), id.text().into_owned());
run::write(&self.pool, format!("index {}: a delete", self.name()), move |answer| {
index.delete_then(id, move |deleted| answer.send(deleted));
})
}
fn set_encoded(&self, document: Encoded) -> impl Future<Output = Result<()>> + Send + 'static {
let index = self.index.clone();
run::write(&self.pool, format!("index {}: a set", self.name()), move |answer| {
index.set_then(document, move |set| answer.send(set));
})
}
}
#[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> fmt::Debug for DocumentCall<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("DocumentCall").field("id", &self.id).finish_non_exhaustive()
}
}
impl<'a, T: Serialize + DeserializeOwned + Send + 'static> 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) -> impl Future<Output = Result<()>> + Send + 'static {
self.index.set_encoded(Encoded::new(self.id, value, self.vector))
}
}
#[must_use = "a search runs at `run`"]
pub struct SearchCall<'i, T> {
call: crate::search::SearchCall<'i, T>,
pool: &'i Arc<Pool>,
}
impl<T> fmt::Debug for SearchCall<'_, T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.call, f)
}
}
impl<'i, T: DeserializeOwned + Send + 'static> SearchCall<'i, T> {
pub fn vector(self, vector: &'i [f32]) -> Self {
self.changed(|call| call.vector(vector))
}
pub fn vector_weight(self, weight: f64) -> Self {
self.changed(|call| call.vector_weight(weight))
}
pub fn rerank(self) -> Self {
self.changed(crate::search::SearchCall::rerank)
}
pub fn min_similarity(self, cosine: f64) -> Self {
self.changed(|call| call.min_similarity(cosine))
}
pub fn prefix(self) -> Self {
self.changed(crate::search::SearchCall::prefix)
}
pub fn prefix_every(self) -> Self {
self.changed(crate::search::SearchCall::prefix_every)
}
pub fn matches(self) -> Self {
self.changed(crate::search::SearchCall::matches)
}
pub fn filter(self, condition: Condition) -> Self {
self.changed(|call| call.filter(condition))
}
pub fn limit(self, limit: usize) -> Self {
self.changed(|call| call.limit(limit))
}
pub fn offset(self, offset: usize) -> Self {
self.changed(|call| call.offset(offset))
}
pub fn run(self) -> impl Future<Output = Result<Found<T>>> + Send + 'static {
let pool = self.pool;
let read = self.call.asked().map(|(index, query)| {
let (index, what) = (index.clone(), format!("index {}: a search", index.name()));
run::read(pool, what, move || index.run_query(query))
});
async move { read?.await }
}
fn changed(
self,
change: impl FnOnce(crate::search::SearchCall<'i, T>) -> crate::search::SearchCall<'i, T>,
) -> Self {
SearchCall { call: change(self.call), pool: self.pool }
}
}
#[cfg(feature = "sql")]
#[must_use = "an index opens at `open`"]
pub struct TableIndexBuilder<T> {
builder: crate::search::TableIndexBuilder<T>,
}
#[cfg(feature = "sql")]
impl<T> fmt::Debug for TableIndexBuilder<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.builder, f)
}
}
#[cfg(feature = "sql")]
impl<T> From<crate::search::TableIndexBuilder<T>> for TableIndexBuilder<T> {
fn from(builder: crate::search::TableIndexBuilder<T>) -> TableIndexBuilder<T> {
TableIndexBuilder { builder }
}
}
#[cfg(feature = "sql")]
impl<T: DeserializeOwned + Send + 'static> TableIndexBuilder<T> {
pub fn table(self, table: &str) -> Self {
self.changed(|builder| builder.table(table))
}
pub fn key(self, column: &str) -> Self {
self.changed(|builder| builder.key(column))
}
pub fn field(self, column: &str, weight: f64) -> Self {
self.changed(|builder| builder.field(column, weight))
}
pub fn fields<S: AsRef<str>>(self, columns: impl IntoIterator<Item = S>) -> Self {
self.changed(|builder| builder.fields(columns))
}
pub fn filters<S: AsRef<str>>(self, columns: impl IntoIterator<Item = S>) -> Self {
self.changed(|builder| builder.filters(columns))
}
pub fn typo_tolerance(self, on: bool) -> Self {
self.changed(|builder| builder.typo_tolerance(on))
}
pub fn layouts<S: AsRef<str>>(self, names: impl IntoIterator<Item = S>) -> Self {
self.changed(|builder| builder.layouts(names))
}
pub fn vectors(self, column: &str, dimensions: usize) -> Self {
self.changed(|builder| builder.vectors(column, dimensions))
}
pub fn recall(self, recall: f64) -> Self {
self.changed(|builder| builder.recall(recall))
}
pub fn vector_weight(self, weight: f64) -> Self {
self.changed(|builder| builder.vector_weight(weight))
}
pub fn rerank(self) -> Self {
self.changed(crate::search::TableIndexBuilder::rerank)
}
pub fn rebuild(self, rebuild: Rebuild) -> Self {
self.changed(|builder| builder.rebuild(rebuild))
}
pub fn open(self) -> Result<TableIndex<T>> {
self.builder.open().map(TableIndex::from)
}
pub fn reindex(self) -> Result<TableIndex<T>> {
self.builder.reindex().map(TableIndex::from)
}
fn changed(
self,
change: impl FnOnce(crate::search::TableIndexBuilder<T>) -> crate::search::TableIndexBuilder<T>,
) -> Self {
TableIndexBuilder { builder: change(self.builder) }
}
}
#[cfg(feature = "sql")]
pub struct TableIndex<T> {
index: crate::search::TableIndex<T>,
pool: Arc<Pool>,
}
#[cfg(feature = "sql")]
impl<T> Clone for TableIndex<T> {
fn clone(&self) -> Self {
TableIndex { index: self.index.clone(), pool: Arc::clone(&self.pool) }
}
}
#[cfg(feature = "sql")]
impl<T> fmt::Debug for TableIndex<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.index, f)
}
}
#[cfg(feature = "sql")]
impl<T: DeserializeOwned> From<crate::search::TableIndex<T>> for TableIndex<T> {
fn from(index: crate::search::TableIndex<T>) -> TableIndex<T> {
let pool = pool_of(index.inner().store());
TableIndex { index, pool }
}
}
#[cfg(feature = "sql")]
impl<T> TableIndex<T> {
pub fn blocking(&self) -> &crate::search::TableIndex<T> {
&self.index
}
}
#[cfg(feature = "sql")]
impl<T: DeserializeOwned + Send + 'static> TableIndex<T> {
pub fn name(&self) -> &str {
self.index.name()
}
pub fn search(&self, text: &str) -> SearchCall<'_, T> {
SearchCall { call: self.index.search(text), pool: &self.pool }
}
pub fn search_vector<'i>(&'i self, vector: &'i [f32]) -> SearchCall<'i, T> {
SearchCall { call: self.index.search_vector(vector), pool: &self.pool }
}
pub fn status(&self) -> impl Future<Output = Result<Status>> + Send + 'static {
let index = self.index.clone();
run::read(&self.pool, format!("index {}: its status", self.name()), move || index.status())
}
pub fn ready(&self) -> impl Future<Output = Result<()>> + Send + 'static {
ready(self.index.inner().clone(), Arc::clone(&self.pool))
}
}
#[cfg(feature = "sql")]
impl<T> crate::transaction::sealed::Sealed for TableIndex<T> {}
#[cfg(feature = "sql")]
impl<T: DeserializeOwned> crate::TxHandle for TableIndex<T> {
type InTx<'h>
= TxTableIndex<'h, T>
where
Self: 'h;
fn in_tx<'h>(&'h self, tx: &'h crate::Transaction<'h>) -> TxTableIndex<'h, T> {
crate::TxHandle::in_tx(&self.index, tx)
}
}
fn pool_of(store: Option<crate::Store>) -> Arc<Pool> {
store.map_or_else(Pool::stopped, |store| Pool::of_or_stopped(&store))
}
fn ready<T: DeserializeOwned + Send + 'static>(
index: crate::search::Index<T>,
pool: Arc<Pool>,
) -> impl Future<Output = Result<()>> + Send + 'static {
let tokens = cancel::captured();
let what = format!("index {}: a wait for it to be ready", index.name());
async move {
let maintains_itself = index.maintains_itself();
loop {
let settled = (!maintains_itself).then(|| {
let (answer, settled) = pending(what.clone());
index.settled_then(move |woken| answer.send(woken));
settled
});
let looking = index.clone();
let look = tokens.run(None, || run::read(&pool, what.clone(), move || looking.is_ready()));
if look.await? {
return Ok(());
}
match settled {
Some(settled) => settled.await?,
None => {
let maintaining = index.clone();
let pass = run::blocking(&pool, None, what.clone(), move || maintaining.maintain_once());
pass.await?;
}
}
}
}
}
#[cfg(test)]
#[path = "search_tests.rs"]
mod tests;