Skip to content

Implement federated multi search #625

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions meilisearch-test-macro/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ There are a few rules, though:
- `String`: It returns the name of the test.
- `Client`: It creates a client like that: `Client::new("http://localhost:7700", "masterKey")`.
- `Index`: It creates and deletes an index, as we've seen before.
You can include multiple `Index` parameter to automatically create multiple indices.

2. You only get what you asked for. That means if you don't ask for an index, no index will be created in meilisearch.
So, if you are testing the creation of indexes, you can ask for a `Client` and a `String` and then create it yourself.
Expand Down
89 changes: 53 additions & 36 deletions meilisearch-test-macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ pub fn meilisearch_test(params: TokenStream, input: TokenStream) -> TokenStream
let use_name = params
.iter()
.any(|param| matches!(param, Param::String | Param::Index));
let use_index = params.contains(&Param::Index);

// Now we are going to build the body of the outer function
let mut outer_block: Vec<Stmt> = Vec::new();
Expand Down Expand Up @@ -106,59 +105,77 @@ pub fn meilisearch_test(params: TokenStream, input: TokenStream) -> TokenStream
));
}

let index_var = |idx: usize| Ident::new(&format!("index_{idx}"), Span::call_site());

// And finally if an index was asked, we delete it, and we (re)create it and wait until meilisearch confirm its creation.
if use_index {
outer_block.push(parse_quote!({
let res = client
.delete_index(&name)
.await
.expect("Network issue while sending the delete index task")
.wait_for_completion(&client, None, None)
.await
.expect("Network issue while waiting for the index deletion");
if res.is_failure() {
let error = res.unwrap_failure();
assert_eq!(
error.error_code,
crate::errors::ErrorCode::IndexNotFound,
"{:?}",
error
);
}
}));
for (i, param) in params.iter().enumerate() {
if !matches!(param, Param::Index) {
continue;
}

let var_name = index_var(i);
outer_block.push(parse_quote!(
let index = client
.create_index(&name, None)
.await
.expect("Network issue while sending the create index task")
.wait_for_completion(&client, None, None)
.await
.expect("Network issue while waiting for the index creation")
.try_make_index(&client)
.expect("Could not create the index out of the create index task");
let #var_name = {
let index_uid = format!("{name}_{}", #i);
let res = client
.delete_index(&index_uid)
.await
.expect("Network issue while sending the delete index task")
.wait_for_completion(&client, None, None)
.await
.expect("Network issue while waiting for the index deletion");

if res.is_failure() {
let error = res.unwrap_failure();
assert_eq!(
error.error_code,
crate::errors::ErrorCode::IndexNotFound,
"{:?}",
error
);
}

client
.create_index(&index_uid, None)
.await
.expect("Network issue while sending the create index task")
.wait_for_completion(&client, None, None)
.await
.expect("Network issue while waiting for the index creation")
.try_make_index(&client)
.expect("Could not create the index out of the create index task")
};
));
}

// Create a list of params separated by comma with the name we defined previously.
let params: Vec<Expr> = params
.into_iter()
.map(|param| match param {
let args: Vec<Expr> = params
.iter()
.enumerate()
.map(|(i, param)| match param {
Param::Client => parse_quote!(client),
Param::Index => parse_quote!(index),
Param::Index => {
let var = index_var(i);
parse_quote!(#var)
}
Param::String => parse_quote!(name),
})
.collect();

// Now we can call the user code with our parameters :tada:
outer_block.push(parse_quote!(
let result = #inner_ident(#(#params.clone()),*).await;
let result = #inner_ident(#(#args.clone()),*).await;
));

// And right before the end, if an index was created and the tests successfully executed we delete it.
if use_index {
for (i, param) in params.iter().enumerate() {
if !matches!(param, Param::Index) {
continue;
}

let var_name = index_var(i);
outer_block.push(parse_quote!(
index
#var_name
.delete()
.await
.expect("Network issue while sending the last delete index task");
Expand Down
31 changes: 31 additions & 0 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,21 @@ impl<Http: HttpClient> Client<Http> {
.await
}

pub async fn execute_federated_multi_search_query<
T: 'static + DeserializeOwned + Send + Sync,
>(
&self,
body: &FederatedMultiSearchQuery<'_, '_, Http>,
) -> Result<FederatedMultiSearchResponse<T>, Error> {
self.http_client
.request::<(), &FederatedMultiSearchQuery<Http>, FederatedMultiSearchResponse<T>>(
&format!("{}/multi-search", &self.host),
Method::Post { body, query: () },
200,
)
.await
}

/// Make multiple search requests.
///
/// # Example
Expand Down Expand Up @@ -170,6 +185,22 @@ impl<Http: HttpClient> Client<Http> {
/// # movies.delete().await.unwrap().wait_for_completion(&client, None, None).await.unwrap();
/// # });
/// ```
///
/// # Federated Search
///
/// You can use [`MultiSearchQuery::with_federation`] to perform a [federated
/// search][1] where results from different indexes are merged and returned as
/// one list.
///
/// When executing a federated query, the type parameter `T` is less clear,
/// as the documents in the different indexes potentially have different
/// fields and you might have one Rust type per index. In most cases, you
/// either want to create an enum with one variant per index and `#[serde
/// (untagged)]` attribute, or if you need more control, just pass
/// `serde_json::Map<String, serde_json::Value>` and then deserialize that
/// into the appropriate target types later.
///
/// [1]: https://www.meilisearch.com/docs/learn/multi_search/multi_search_vs_federated_search#what-is-federated-search
#[must_use]
pub fn multi_search(&self) -> MultiSearchQuery<Http> {
MultiSearchQuery::new(self)
Expand Down
Loading
Loading