Skip to content

Implement federated multi search #681

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

Merged
merged 18 commits into from
Jul 11, 2025
Merged
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
4 changes: 2 additions & 2 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,8 @@ jobs:
# Generate separate reports for tests and doctests, and combine them.
run: |
set -euo pipefail
cargo llvm-cov --no-report --all-features --workspace
cargo llvm-cov --no-report --doc --all-features --workspace
cargo llvm-cov --no-report --all-features --workspace --exclude 'meilisearch-test-macro'
cargo llvm-cov --no-report --doc --all-features --workspace --exclude 'meilisearch-test-macro'
cargo llvm-cov report --doctests --codecov --output-path codecov.json
- name: Upload coverage reports to Codecov
uses: codecov/codecov-action@v5
Expand Down
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 indexes.

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
52 changes: 10 additions & 42 deletions src/features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,10 @@ impl<'a, Http: HttpClient> ExperimentalFeatures<'a, Http> {
/// # let MEILISEARCH_URL = option_env!("MEILISEARCH_URL").unwrap_or("http://localhost:7700");
/// # let MEILISEARCH_API_KEY = option_env!("MEILISEARCH_API_KEY").unwrap_or("masterKey");
/// # let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap();
/// tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
/// let features = ExperimentalFeatures::new(&client);
/// features.get().await.unwrap();
/// });
/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
/// let features = ExperimentalFeatures::new(&client);
/// features.get().await.unwrap();
/// # });
/// ```
pub async fn get(&self) -> Result<ExperimentalFeaturesResult, Error> {
self.client
Expand Down Expand Up @@ -148,52 +148,20 @@ mod tests {
use meilisearch_test_macro::meilisearch_test;

#[meilisearch_test]
async fn test_experimental_features_set_metrics(client: Client) {
async fn test_experimental_features(client: Client) {
let mut features = ExperimentalFeatures::new(&client);
features.set_metrics(true);
let _ = features.update().await.unwrap();

let res = features.get().await.unwrap();
assert!(res.metrics)
}

#[meilisearch_test]
async fn test_experimental_features_set_logs_route(client: Client) {
let mut features = ExperimentalFeatures::new(&client);
features.set_logs_route(true);
let _ = features.update().await.unwrap();

let res = features.get().await.unwrap();
assert!(res.logs_route)
}

#[meilisearch_test]
async fn test_experimental_features_set_contains_filter(client: Client) {
let mut features = ExperimentalFeatures::new(&client);
features.set_contains_filter(true);
let _ = features.update().await.unwrap();

let res = features.get().await.unwrap();
assert!(res.contains_filter)
}

#[meilisearch_test]
async fn test_experimental_features_set_network(client: Client) {
let mut features = ExperimentalFeatures::new(&client);
features.set_network(true);
let _ = features.update().await.unwrap();

let res = features.get().await.unwrap();
assert!(res.network)
}

#[meilisearch_test]
async fn test_experimental_features_set_edit_documents_by_function(client: Client) {
let mut features = ExperimentalFeatures::new(&client);
features.set_edit_documents_by_function(true);
let _ = features.update().await.unwrap();

let res = features.get().await.unwrap();
assert!(res.edit_documents_by_function)
assert!(res.metrics);
assert!(res.logs_route);
assert!(res.contains_filter);
assert!(res.network);
assert!(res.edit_documents_by_function);
}
}
Loading