MeiliSearch/meilisearch-http/src/routes/indexes/search.rs

183 lines
5.8 KiB
Rust
Raw Normal View History

2021-06-23 18:54:33 +02:00
use actix_web::{web, HttpResponse};
use log::debug;
2021-09-27 15:41:14 +02:00
use meilisearch_lib::index::{default_crop_length, SearchQuery, DEFAULT_SEARCH_LIMIT};
use meilisearch_lib::MeiliSearch;
2021-02-16 15:54:07 +01:00
use serde::Deserialize;
use serde_json::Value;
2020-12-12 13:32:06 +01:00
2021-06-23 18:54:33 +02:00
use crate::error::ResponseError;
2021-06-24 16:25:52 +02:00
use crate::extractors::authentication::{policies::*, GuardedData};
2020-12-12 13:32:06 +01:00
use crate::routes::IndexParam;
2021-06-22 23:49:34 +02:00
2021-07-05 14:29:20 +02:00
pub fn configure(cfg: &mut web::ServiceConfig) {
2021-06-22 23:49:34 +02:00
cfg.service(
2021-07-05 14:29:20 +02:00
web::resource("")
2021-06-22 23:49:34 +02:00
.route(web::get().to(search_with_url_query))
.route(web::post().to(search_with_post)),
);
2020-12-12 13:32:06 +01:00
}
2021-02-16 15:54:07 +01:00
#[derive(Deserialize, Debug)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct SearchQueryGet {
q: Option<String>,
offset: Option<usize>,
limit: Option<usize>,
attributes_to_retrieve: Option<String>,
attributes_to_crop: Option<String>,
2021-06-22 14:22:36 +02:00
#[serde(default = "default_crop_length")]
crop_length: usize,
2021-02-16 15:54:07 +01:00
attributes_to_highlight: Option<String>,
filter: Option<String>,
2021-08-24 12:31:35 +02:00
sort: Option<String>,
2021-06-22 14:22:36 +02:00
#[serde(default = "Default::default")]
matches: bool,
2021-06-22 20:07:23 +02:00
facets_distribution: Option<String>,
2021-02-16 15:54:07 +01:00
}
impl From<SearchQueryGet> for SearchQuery {
fn from(other: SearchQueryGet) -> Self {
2021-02-16 15:54:07 +01:00
let attributes_to_retrieve = other
.attributes_to_retrieve
2021-08-24 12:31:35 +02:00
.map(|attrs| attrs.split(',').map(String::from).collect());
2021-02-16 15:54:07 +01:00
let attributes_to_crop = other
.attributes_to_crop
2021-08-24 12:31:35 +02:00
.map(|attrs| attrs.split(',').map(String::from).collect());
2021-02-16 15:54:07 +01:00
let attributes_to_highlight = other
.attributes_to_highlight
2021-08-24 12:31:35 +02:00
.map(|attrs| attrs.split(',').map(String::from).collect());
2021-02-16 15:54:07 +01:00
2021-06-22 20:07:23 +02:00
let facets_distribution = other
.facets_distribution
2021-08-24 12:31:35 +02:00
.map(|attrs| attrs.split(',').map(String::from).collect());
2021-02-16 15:54:07 +01:00
let filter = match other.filter {
Some(f) => match serde_json::from_str(&f) {
Ok(v) => Some(v),
_ => Some(Value::String(f)),
2021-05-04 18:22:48 +02:00
},
2021-02-16 15:54:07 +01:00
None => None,
};
2021-09-27 15:41:14 +02:00
let sort = other.sort.map(|attr| fix_sort_query_parameters(&attr));
2021-08-24 12:31:35 +02:00
Self {
2021-02-16 15:54:07 +01:00
q: other.q,
offset: other.offset,
limit: other.limit.unwrap_or(DEFAULT_SEARCH_LIMIT),
attributes_to_retrieve,
attributes_to_crop,
crop_length: other.crop_length,
attributes_to_highlight,
filter,
2021-08-24 12:31:35 +02:00
sort,
matches: other.matches,
2021-06-22 20:07:23 +02:00
facets_distribution,
}
2021-02-16 15:54:07 +01:00
}
}
2020-12-12 13:32:06 +01:00
// TODO: TAMO: split on :asc, and :desc, instead of doing some weird things
2021-09-27 15:41:14 +02:00
/// Transform the sort query parameter into something that matches the post expected format.
fn fix_sort_query_parameters(sort_query: &str) -> Vec<String> {
let mut sort_parameters = Vec::new();
let mut merge = false;
for current_sort in sort_query.trim_matches('"').split(',').map(|s| s.trim()) {
if current_sort.starts_with("_geoPoint(") {
sort_parameters.push(current_sort.to_string());
merge = true;
} else if merge && !sort_parameters.is_empty() {
sort_parameters
.last_mut()
.unwrap()
.push_str(&format!(",{}", current_sort));
if current_sort.ends_with("):desc") || current_sort.ends_with("):asc") {
merge = false;
}
} else {
sort_parameters.push(current_sort.to_string());
merge = false;
}
}
sort_parameters
}
2021-07-07 16:20:22 +02:00
pub async fn search_with_url_query(
2021-09-24 12:03:16 +02:00
meilisearch: GuardedData<Public, MeiliSearch>,
2021-02-16 15:54:07 +01:00
path: web::Path<IndexParam>,
params: web::Query<SearchQueryGet>,
2020-12-12 13:32:06 +01:00
) -> Result<HttpResponse, ResponseError> {
2021-06-23 12:18:34 +02:00
debug!("called with params: {:?}", params);
let query = params.into_inner().into();
2021-09-27 15:41:14 +02:00
let search_result = meilisearch
.search(path.into_inner().index_uid, query)
.await?;
2021-07-06 11:54:37 +02:00
// Tests that the nb_hits is always set to false
#[cfg(test)]
assert!(!search_result.exhaustive_nb_hits);
2021-06-23 12:18:34 +02:00
debug!("returns: {:?}", search_result);
Ok(HttpResponse::Ok().json(search_result))
2020-12-12 13:32:06 +01:00
}
2021-07-07 16:20:22 +02:00
pub async fn search_with_post(
2021-09-24 12:03:16 +02:00
meilisearch: GuardedData<Public, MeiliSearch>,
2020-12-24 12:58:34 +01:00
path: web::Path<IndexParam>,
params: web::Json<SearchQuery>,
2020-12-12 13:32:06 +01:00
) -> Result<HttpResponse, ResponseError> {
2021-06-23 12:18:34 +02:00
debug!("search called with params: {:?}", params);
2021-09-24 12:03:16 +02:00
let search_result = meilisearch
2021-03-15 18:11:10 +01:00
.search(path.into_inner().index_uid, params.into_inner())
.await?;
2021-07-06 11:54:37 +02:00
// Tests that the nb_hits is always set to false
#[cfg(test)]
assert!(!search_result.exhaustive_nb_hits);
2021-06-23 12:18:34 +02:00
debug!("returns: {:?}", search_result);
Ok(HttpResponse::Ok().json(search_result))
2020-12-12 13:32:06 +01:00
}
2021-09-27 15:41:14 +02:00
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_fix_sort_query_parameters() {
let sort = fix_sort_query_parameters("_geoPoint(12, 13):asc");
assert_eq!(sort, vec!["_geoPoint(12,13):asc".to_string()]);
let sort = fix_sort_query_parameters("doggo:asc,_geoPoint(12.45,13.56):desc");
assert_eq!(
sort,
vec![
"doggo:asc".to_string(),
"_geoPoint(12.45,13.56):desc".to_string(),
]
);
let sort = fix_sort_query_parameters(
"doggo:asc , _geoPoint(12.45, 13.56, 2590352):desc , catto:desc",
);
assert_eq!(
sort,
vec![
"doggo:asc".to_string(),
"_geoPoint(12.45,13.56,2590352):desc".to_string(),
"catto:desc".to_string(),
]
);
let sort = fix_sort_query_parameters("doggo:asc , _geoPoint(1, 2), catto:desc");
// This is ugly but eh, I don't want to write a full parser just for this unused route
assert_eq!(
sort,
vec![
"doggo:asc".to_string(),
"_geoPoint(1,2),catto:desc".to_string(),
]
);
}
}