meilisearch/src/data/search.rs

356 lines
12 KiB
Rust
Raw Normal View History

2021-02-17 21:52:30 +08:00
use std::collections::{HashSet, BTreeMap};
2020-12-24 19:58:34 +08:00
use std::mem;
use std::time::Instant;
2020-12-12 20:32:06 +08:00
2021-02-26 16:10:04 +08:00
use anyhow::bail;
2021-02-17 01:21:16 +08:00
use either::Either;
use heed::RoTxn;
2021-02-02 02:51:47 +08:00
use meilisearch_tokenizer::{Analyzer, AnalyzerConfig};
2021-02-17 21:52:30 +08:00
use milli::{obkv_to_json, FacetCondition, Index, facet::FacetValue};
2021-02-02 02:51:47 +08:00
use serde::{Deserialize, Serialize};
2021-02-17 01:21:16 +08:00
use serde_json::{Map, Value};
2020-12-12 20:32:06 +08:00
2020-12-29 18:11:06 +08:00
use super::Data;
2020-12-12 20:32:06 +08:00
2021-02-16 22:54:07 +08:00
pub const DEFAULT_SEARCH_LIMIT: usize = 20;
2020-12-24 19:58:34 +08:00
2021-02-17 01:21:16 +08:00
const fn default_search_limit() -> usize {
DEFAULT_SEARCH_LIMIT
}
2021-01-14 00:50:36 +08:00
2020-12-24 19:58:34 +08:00
#[derive(Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
2020-12-29 18:11:06 +08:00
#[allow(dead_code)]
2020-12-24 19:58:34 +08:00
pub struct SearchQuery {
2021-01-14 18:27:07 +08:00
pub q: Option<String>,
pub offset: Option<usize>,
2021-01-14 00:50:36 +08:00
#[serde(default = "default_search_limit")]
2021-01-14 18:27:07 +08:00
pub limit: usize,
pub attributes_to_retrieve: Option<Vec<String>>,
pub attributes_to_crop: Option<Vec<String>>,
pub crop_length: Option<usize>,
2021-01-28 21:12:34 +08:00
pub attributes_to_highlight: Option<HashSet<String>>,
2021-01-14 18:27:07 +08:00
pub filters: Option<String>,
pub matches: Option<bool>,
pub facet_filters: Option<Value>,
2021-02-17 21:52:30 +08:00
pub facet_distributions: Option<Vec<String>>,
2021-01-28 21:12:34 +08:00
}
impl SearchQuery {
2021-02-17 01:21:16 +08:00
pub fn perform(&self, index: impl AsRef<Index>) -> anyhow::Result<SearchResult> {
2021-01-28 21:12:34 +08:00
let index = index.as_ref();
let before_search = Instant::now();
2021-02-16 23:17:28 +08:00
let rtxn = index.read_txn()?;
2021-01-28 21:12:34 +08:00
let mut search = index.search(&rtxn);
if let Some(ref query) = self.q {
search.query(query);
}
2021-02-02 02:51:47 +08:00
search.limit(self.limit);
search.offset(self.offset.unwrap_or_default());
2021-02-17 01:21:16 +08:00
if let Some(ref facets) = self.facet_filters {
if let Some(facets) = parse_facets(facets, index, &rtxn)? {
search.facet_condition(facets);
2021-01-28 21:12:34 +08:00
}
}
2021-02-17 01:21:16 +08:00
let milli::SearchResult {
documents_ids,
found_words,
candidates,
} = search.execute()?;
2021-01-28 21:12:34 +08:00
let mut documents = Vec::new();
2021-02-16 23:17:28 +08:00
let fields_ids_map = index.fields_ids_map(&rtxn)?;
let displayed_fields_ids = index.displayed_fields_ids(&rtxn)?;
let attributes_to_retrieve_ids = match self.attributes_to_retrieve {
Some(ref attrs) if attrs.iter().any(|f| f == "*") => None,
Some(ref attrs) => attrs
2021-02-17 01:21:16 +08:00
.iter()
.filter_map(|f| fields_ids_map.id(f))
.collect::<Vec<_>>()
.into(),
2021-02-16 23:17:28 +08:00
None => None,
};
2021-01-28 21:12:34 +08:00
2021-02-17 01:21:16 +08:00
let displayed_fields_ids = match (displayed_fields_ids, attributes_to_retrieve_ids) {
2021-02-16 23:17:28 +08:00
(_, Some(ids)) => ids,
(Some(ids), None) => ids,
(None, None) => fields_ids_map.iter().map(|(id, _)| id).collect(),
2021-01-28 21:12:34 +08:00
};
let stop_words = fst::Set::default();
let highlighter = Highlighter::new(&stop_words);
2021-02-16 23:17:28 +08:00
for (_id, obkv) in index.documents(&rtxn, documents_ids)? {
let mut object = obkv_to_json(&displayed_fields_ids, &fields_ids_map, obkv)?;
2021-01-28 21:12:34 +08:00
if let Some(ref attributes_to_highlight) = self.attributes_to_highlight {
highlighter.highlight_record(&mut object, &found_words, attributes_to_highlight);
}
documents.push(object);
}
2021-02-17 21:52:30 +08:00
let nb_hits = candidates.len();
let facet_distributions = match self.facet_distributions {
Some(ref fields) => {
let mut facet_distribution = index.facets_distribution(&rtxn);
if fields.iter().all(|f| f != "*") {
facet_distribution.facets(fields);
}
Some(facet_distribution.candidates(candidates).execute()?)
}
None => None,
};
2021-01-28 21:12:34 +08:00
Ok(SearchResult {
hits: documents,
2021-02-17 21:52:30 +08:00
nb_hits,
2021-01-28 21:12:34 +08:00
query: self.q.clone().unwrap_or_default(),
2021-02-02 02:51:47 +08:00
limit: self.limit,
2021-01-28 21:12:34 +08:00
offset: self.offset.unwrap_or_default(),
processing_time_ms: before_search.elapsed().as_millis(),
2021-02-17 21:52:30 +08:00
facet_distributions,
2021-01-28 21:12:34 +08:00
})
}
2020-12-24 19:58:34 +08:00
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SearchResult {
hits: Vec<Map<String, Value>>,
2021-02-02 02:51:47 +08:00
nb_hits: u64,
2020-12-24 19:58:34 +08:00
query: String,
limit: usize,
offset: usize,
processing_time_ms: u128,
2021-02-17 21:52:30 +08:00
#[serde(skip_serializing_if = "Option::is_none")]
facet_distributions: Option<BTreeMap<String, BTreeMap<FacetValue, u64>>>,
2020-12-24 19:58:34 +08:00
}
2020-12-29 18:11:06 +08:00
struct Highlighter<'a, A> {
analyzer: Analyzer<'a, A>,
2020-12-12 20:32:06 +08:00
}
2020-12-29 18:11:06 +08:00
impl<'a, A: AsRef<[u8]>> Highlighter<'a, A> {
fn new(stop_words: &'a fst::Set<A>) -> Self {
let analyzer = Analyzer::new(AnalyzerConfig::default_with_stopwords(stop_words));
Self { analyzer }
2020-12-12 20:32:06 +08:00
}
2020-12-29 18:11:06 +08:00
fn highlight_value(&self, value: Value, words_to_highlight: &HashSet<String>) -> Value {
match value {
Value::Null => Value::Null,
Value::Bool(boolean) => Value::Bool(boolean),
Value::Number(number) => Value::Number(number),
Value::String(old_string) => {
let mut string = String::new();
let analyzed = self.analyzer.analyze(&old_string);
for (word, token) in analyzed.reconstruct() {
if token.is_word() {
let to_highlight = words_to_highlight.contains(token.text());
2021-02-17 01:21:16 +08:00
if to_highlight {
string.push_str("<mark>")
}
2020-12-29 18:11:06 +08:00
string.push_str(word);
2021-02-17 01:21:16 +08:00
if to_highlight {
string.push_str("</mark>")
}
2020-12-29 18:11:06 +08:00
} else {
string.push_str(word);
}
}
Value::String(string)
2021-02-17 01:21:16 +08:00
}
Value::Array(values) => Value::Array(
values
.into_iter()
2020-12-29 18:11:06 +08:00
.map(|v| self.highlight_value(v, words_to_highlight))
2021-02-17 01:21:16 +08:00
.collect(),
),
Value::Object(object) => Value::Object(
object
.into_iter()
2020-12-29 18:11:06 +08:00
.map(|(k, v)| (k, self.highlight_value(v, words_to_highlight)))
2021-02-17 01:21:16 +08:00
.collect(),
),
2020-12-12 20:32:06 +08:00
}
}
2020-12-23 00:53:13 +08:00
2020-12-29 18:11:06 +08:00
fn highlight_record(
2020-12-23 20:52:28 +08:00
&self,
2020-12-29 18:11:06 +08:00
object: &mut Map<String, Value>,
words_to_highlight: &HashSet<String>,
attributes_to_highlight: &HashSet<String>,
) {
// TODO do we need to create a string for element that are not and needs to be highlight?
for (key, value) in object.iter_mut() {
if attributes_to_highlight.contains(key) {
let old_value = mem::take(value);
*value = self.highlight_value(old_value, words_to_highlight);
}
2020-12-23 20:52:28 +08:00
}
}
2020-12-29 18:11:06 +08:00
}
2020-12-23 20:52:28 +08:00
2020-12-29 18:11:06 +08:00
impl Data {
2021-02-17 01:21:16 +08:00
pub fn search<S: AsRef<str>>(
&self,
2021-02-26 16:10:04 +08:00
_index: S,
_search_query: SearchQuery,
2021-02-17 01:21:16 +08:00
) -> anyhow::Result<SearchResult> {
2021-02-26 16:10:04 +08:00
todo!()
//match self.index_controller.index(&index)? {
//Some(index) => Ok(search_query.perform(index)?),
//None => bail!("index {:?} doesn't exists", index.as_ref()),
//}
2020-12-24 19:58:34 +08:00
}
2021-02-11 00:08:37 +08:00
2021-02-16 06:02:20 +08:00
pub async fn retrieve_documents<S>(
2021-02-11 00:08:37 +08:00
&self,
2021-02-26 16:10:04 +08:00
_index: String,
_offset: usize,
_limit: usize,
_attributes_to_retrieve: Option<Vec<S>>,
2021-02-16 06:02:20 +08:00
) -> anyhow::Result<Vec<Map<String, Value>>>
where
2021-02-17 01:21:16 +08:00
S: AsRef<str> + Send + Sync + 'static,
2021-02-16 06:02:20 +08:00
{
2021-02-26 16:10:04 +08:00
todo!()
//let index_controller = self.index_controller.clone();
//let documents: anyhow::Result<_> = tokio::task::spawn_blocking(move || {
//let index = index_controller
//.index(index.clone())?
//.with_context(|| format!("Index {:?} doesn't exist", index))?;
//let txn = index.read_txn()?;
//let fields_ids_map = index.fields_ids_map(&txn)?;
//let attributes_to_retrieve_ids = match attributes_to_retrieve {
//Some(attrs) => attrs
//.iter()
//.filter_map(|f| fields_ids_map.id(f.as_ref()))
//.collect::<Vec<_>>(),
//None => fields_ids_map.iter().map(|(id, _)| id).collect(),
//};
//let iter = index.documents.range(&txn, &(..))?.skip(offset).take(limit);
//let mut documents = Vec::new();
//for entry in iter {
//let (_id, obkv) = entry?;
//let object = obkv_to_json(&attributes_to_retrieve_ids, &fields_ids_map, obkv)?;
//documents.push(object);
//}
//Ok(documents)
//})
//.await?;
//documents
2021-02-11 00:08:37 +08:00
}
2021-02-11 17:59:23 +08:00
2021-02-16 06:02:20 +08:00
pub async fn retrieve_document<S>(
2021-02-11 17:59:23 +08:00
&self,
2021-02-26 16:10:04 +08:00
_index: impl AsRef<str> + Sync + Send + 'static,
_document_id: impl AsRef<str> + Sync + Send + 'static,
_attributes_to_retrieve: Option<Vec<S>>,
2021-02-16 06:02:20 +08:00
) -> anyhow::Result<Map<String, Value>>
where
S: AsRef<str> + Sync + Send + 'static,
{
2021-02-26 16:10:04 +08:00
todo!()
//let index_controller = self.index_controller.clone();
//let document: anyhow::Result<_> = tokio::task::spawn_blocking(move || {
//let index = index_controller
//.index(&index)?
//.with_context(|| format!("Index {:?} doesn't exist", index.as_ref()))?;
//let txn = index.read_txn()?;
//let fields_ids_map = index.fields_ids_map(&txn)?;
//let attributes_to_retrieve_ids = match attributes_to_retrieve {
//Some(attrs) => attrs
//.iter()
//.filter_map(|f| fields_ids_map.id(f.as_ref()))
//.collect::<Vec<_>>(),
//None => fields_ids_map.iter().map(|(id, _)| id).collect(),
//};
//let internal_id = index
//.external_documents_ids(&txn)?
//.get(document_id.as_ref().as_bytes())
//.with_context(|| format!("Document with id {} not found", document_id.as_ref()))?;
//let document = index
//.documents(&txn, std::iter::once(internal_id))?
//.into_iter()
//.next()
//.map(|(_, d)| d);
//match document {
//Some(document) => Ok(obkv_to_json(
//&attributes_to_retrieve_ids,
//&fields_ids_map,
//document,
//)?),
//None => bail!("Document with id {} not found", document_id.as_ref()),
//}
//})
//.await?;
//document
2021-02-11 17:59:23 +08:00
}
2020-12-24 19:58:34 +08:00
}
2021-02-17 01:21:16 +08:00
fn parse_facets_array(
txn: &RoTxn,
index: &Index,
arr: &Vec<Value>,
) -> anyhow::Result<Option<FacetCondition>> {
let mut ands = Vec::new();
for value in arr {
match value {
Value::String(s) => ands.push(Either::Right(s.clone())),
Value::Array(arr) => {
let mut ors = Vec::new();
for value in arr {
match value {
Value::String(s) => ors.push(s.clone()),
v => bail!("Invalid facet expression, expected String, found: {:?}", v),
}
}
ands.push(Either::Left(ors));
}
v => bail!(
"Invalid facet expression, expected String or [String], found: {:?}",
v
),
}
}
FacetCondition::from_array(txn, index, ands)
}
fn parse_facets(
facets: &Value,
index: &Index,
txn: &RoTxn,
) -> anyhow::Result<Option<FacetCondition>> {
match facets {
// Disabled for now
//Value::String(expr) => Ok(Some(FacetCondition::from_str(txn, index, expr)?)),
Value::Array(arr) => parse_facets_array(txn, index, arr),
v => bail!(
"Invalid facet expression, expected Array, found: {:?}",
v
),
}
}