### Run the Rust Application Source: https://github.com/meilisearch/meilisearch-rust/blob/main/examples/web_app_graphql/README.md Compile and run the example application. This will provide a link to the GraphQL playground. ```bash cargo run --release ``` -------------------------------- ### Run Meilisearch Server Source: https://github.com/meilisearch/meilisearch-rust/blob/main/examples/web_app_graphql/README.md Start the Meilisearch server with a master key. Ensure this is done before running the application. ```bash meilisearch --master-key ``` -------------------------------- ### Install wasm-pack Source: https://github.com/meilisearch/meilisearch-rust/blob/main/examples/web_app/README.md Install the wasm-pack tool, which is required for building Rust projects for WebAssembly. ```console curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh ``` -------------------------------- ### Example YAML Version Update Source: https://github.com/meilisearch/meilisearch-rust/blob/main/CONTRIBUTING.md This YAML snippet demonstrates updating the meilisearch-sdk version in the `.code-samples.meilisearch.yaml` file. ```yaml meilisearch-sdk = "X.X.X" ``` -------------------------------- ### Example Rustdoc Version Update Source: https://github.com/meilisearch/meilisearch-rust/blob/main/CONTRIBUTING.md This Rustdoc snippet illustrates updating the meilisearch-sdk version in `src/lib.rs` for a release. ```rust //! meilisearch-sdk = "X.X.X" ``` -------------------------------- ### Create Backups (Dump and Snapshot) with Meilisearch Rust Client Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Provides examples for creating both a portable `.dump` file (compatible across versions) and a version-specific binary snapshot for fast disaster recovery using the Meilisearch Rust client. ```rust use meilisearch_sdk::client::Client; use meilisearch_sdk::tasks::Task; #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); // Export all indexes + documents + settings as a .dump file let dump_task = client .create_dump() .await .unwrap() .wait_for_completion(&client, None, None) .await .unwrap(); assert!(matches!(dump_task, Task::Succeeded { .. })); // Create a binary snapshot for this Meilisearch version let snap_task = client .create_snapshot() .await .unwrap() .wait_for_completion(&client, None, None) .await .unwrap(); assert!(matches!(snap_task, Task::Succeeded { .. })); } ``` -------------------------------- ### Install and Update Clippy Source: https://github.com/meilisearch/meilisearch-rust/blob/main/CONTRIBUTING.md Instructions for installing or updating the Clippy linter component for the Rust toolchain. Ensure you have the latest version for effective code analysis. ```bash rustup update rustup component add clippy ``` -------------------------------- ### Example TOML Version Update Source: https://github.com/meilisearch/meilisearch-rust/blob/main/CONTRIBUTING.md This TOML snippet shows how to update the version number in `Cargo.toml` as part of the release process. ```toml version = "X.X.X" ``` -------------------------------- ### Perform Full-Text Search with Index::search Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Utilize `Index::search()` to initiate a full-text search. Chain `.with_*` methods to configure the query and then call `.execute::()` to get results. ```rust use meilisearch_sdk::{client::Client, search::{SearchQuery, Selectors, MatchingStrategies}}; use serde::Deserialize; #[derive(Deserialize, Debug)] struct Movie { id: u32, title: String, genres: Vec } #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); let movies = client.index("movies"); let results = movies .search() .with_query("sci-fi adventure") .with_limit(5) .with_offset(0) .with_filter("genres = sci-fi") .with_sort(&["id:asc"]) .with_attributes_to_highlight(Selectors::All) .with_highlight_pre_tag("") .with_highlight_post_tag("") .with_show_ranking_score(true) .with_matching_strategy(MatchingStrategies::LAST) .execute::() .await .unwrap(); println!("hits: {}", results.hits.len()); println!("estimated total: {:?}", results.estimated_total_hits); for hit in &results.hits { println!("{} (score: {:?})", hit.result.title, hit.ranking_score); if let Some(fmt) = &hit.formatted_result { println!(" formatted: {:?}", fmt.get("title")); } } } ``` -------------------------------- ### Fix PostgreSQL Development Library Error Source: https://github.com/meilisearch/meilisearch-rust/blob/main/examples/web_app_graphql/README.md If you encounter a linker error related to '-lpq', install the PostgreSQL development library using apt. ```bash sudo apt install libpq-dev ``` -------------------------------- ### SearchQuery — numbered pagination Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Demonstrates how to implement page-number-based pagination using `with_page` and `with_hits_per_page` to retrieve specific pages of search results and get total hit and page counts. ```APIDOC ## SearchQuery — numbered pagination Use `with_page` and `with_hits_per_page` for page-number–based pagination (returns `total_hits` and `total_pages`). ```rust use meilisearch_sdk::client::Client; use serde::Deserialize; #[derive(Deserialize, Debug)] struct Movie { id: u32, title: String } #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); let movies = client.index("movies"); let results = movies .search() .with_page(2) .with_hits_per_page(10) .execute::() .await .unwrap(); println!("page: {:?}, total_pages: {:?}", results.page, results.total_pages); } ``` ``` -------------------------------- ### Basic Search in Meilisearch Source: https://github.com/meilisearch/meilisearch-rust/blob/main/README.md Performs a basic search query on a Meilisearch index. Meilisearch is typo-tolerant, so this example searches for 'caorl' and returns matching documents. ```rust println!("{:?}", client.index("movies_2").search().with_query("caorl").execute::().await.unwrap().hits); ``` -------------------------------- ### GraphQL Search Query Example Source: https://github.com/meilisearch/meilisearch-rust/blob/main/examples/web_app_graphql/README.md Use this query in the GraphQL playground to search for users by their last name. It retrieves the first name, last name, and email of matching users. ```graphql query { users{ search(queryString: "Eugene"){ lastName firstName email } } } ``` -------------------------------- ### Update Clippy Source: https://github.com/meilisearch/meilisearch-rust/blob/main/CONTRIBUTING.md Update an existing Clippy installation to the latest version. This is recommended if Clippy was installed a long time ago to ensure compatibility and access to new lints. ```bash rustup update ``` -------------------------------- ### Meilisearch Test Before Macro Source: https://github.com/meilisearch/meilisearch-rust/blob/main/meilisearch-test-macro/README.md Example of a Meilisearch test written without the meilisearch_test macro, highlighting the boilerplate code for client creation, index management, and cleanup. ```rust #[async_test] async fn test_get_tasks() -> Result<(), Error> { let client = Client::new(MEILISEARCH_URL, MEILISEARCH_API_KEY); let index = client .create_index("test_get_tasks", None) .await? .wait_for_completion(&client, None, None) .await? .try_make_index(&client) .unwrap(); let tasks = index.get_tasks().await?; // The only task is the creation of the index assert_eq!(status.results.len(), 1); index.delete() .await? .wait_for_completion(&client, None, None) .await?; Ok(()) } ``` -------------------------------- ### Run Tests and Meilisearch Source: https://github.com/meilisearch/meilisearch-rust/blob/main/CONTRIBUTING.md This snippet demonstrates the steps to download Meilisearch, run it with a master key and disabled analytics, and then execute the project's tests. ```bash # Tests curl -L https://install.meilisearch.com | sh # download Meilisearch ./meilisearch --master-key=masterKey --no-analytics # run Meilisearch cargo test ``` -------------------------------- ### Create an Index Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Schedules index creation and returns a `TaskInfo`. Call `.wait_for_completion` to block until the index is ready, then `.try_make_index` to obtain an `Index` handle. ```rust use meilisearch_sdk::client::Client; #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); let index = client .create_index("movies", Some("id")) // uid, optional primary key .await .unwrap() .wait_for_completion(&client, None, None) // default interval 50 ms, timeout 5 s .await .unwrap() .try_make_index(&client) .unwrap(); assert_eq!(index.uid, "movies"); } ``` -------------------------------- ### Initialize Web App Source: https://github.com/meilisearch/meilisearch-rust/blob/main/examples/web_app/pkg/index.html Imports and initializes the web application. This is typically the entry point for the client-side application logic. ```javascript import init from "./web_app.js" init() ``` -------------------------------- ### Initialize Amplitude Analytics SDK Source: https://github.com/meilisearch/meilisearch-rust/blob/main/examples/web_app/pkg/index.html This script initializes the Amplitude analytics SDK. It should be included in your HTML to track user events. Ensure the correct API key is used. ```javascript (function (e, t) { var n = e.amplitude || { _q: [], _iq: {} }; var r = t.createElement("script"); r.type = "text/javascript"; r.integrity = "sha384-d/yhnowERvm+7eCU79T/bYjOiMmq4F11ElWYLmt0ktvYEVgqLDazh4+gW9CKMpYW"; r.crossOrigin = "anonymous"; r.async = true; r.src = "https://cdn.amplitude.com/libs/amplitude-5.2.2-min.gz.js"; r.onload = function () { if (!e.amplitude.runQueuedFunctions) { console.log("[Amplitude] Error: could not load SDK") } } ; var i = t.getElementsByTagName("script")[0]; i.parentNode.insertBefore(r, i); function s(e, t) { e.prototype[t] = function () { this._q.push([t].concat(Array.prototype.slice.call(arguments, 0))); return this } } var o = function () { this._q = []; return this }; var a = ["add", "append", "clearAll", "prepend", "set", "setOnce", "unset"]; for (var u = 0; u < a.length; u++) { s(o, a[u]) } n.Identify = o; var c = function () { this._q = []; return this }; var l = ["setProductId", "setQuantity", "setPrice", "setRevenueType", "setEventProperties"]; for (var p = 0; p < l.length; p++) { s(c, l[p]) } n.Revenue = c; var d = ["init", "logEvent", "logRevenue", "setUserId", "setUserProperties", "setOptOut", "setVersionName", "setDomain", "setDeviceId", "setGlobalUserProperties", "identify", "clearUserProperties", "setGroup", "logRevenueV2", "regenerateDeviceId", "groupIdentify", "onInit", "logEventWithTimestamp", "logEventWithGroups", "setSessionId", "resetSessionId"]; function v(e) { function t(t) { e[t] = function () { e._q.push([t].concat(Array.prototype.slice.call(arguments, 0))) } } for (var n = 0; n < d.length; n++) { t(d[n]) } } v(n); n.getInstance = function (e) { e = (!e || e.length === 0 ? "$default_instance" : e).toLowerCase(); if (!n._iq.hasOwnProperty(e)) { n._iq[e] = { _q: [] }; v(n._iq[e]) } return n._iq[e] } ; e.amplitude = n })(window, document); amplitude.getInstance().init("6696ad48de06bdb7c8e964ccd7c5b14b"); ``` -------------------------------- ### Create a Meilisearch Client Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Construct a `Client` pointing at a Meilisearch instance. The second argument is the API key (use `None` for public instances). Without a key, endpoints that require authentication will return an error. ```rust use meilisearch_sdk::client::Client; #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); let health = client.health().await.unwrap(); println!("{}", health.status); // "available" } ``` -------------------------------- ### Client::new Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Constructs a new Client instance for connecting to a Meilisearch instance. It takes the Meilisearch URL and an optional API key. ```APIDOC ## Client::new — create a client Construct a `Client` pointing at a Meilisearch instance. The second argument is the API key (use `None` for public instances). Without a key, endpoints that require authentication will return an error. ```rust use meilisearch_sdk::client::Client; #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); let health = client.health().await.unwrap(); println!("{}", health.status); // "available" } ``` ``` -------------------------------- ### Create and Update API Keys with Meilisearch Rust Client Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Demonstrates creating scoped API keys with specific actions, index restrictions, and expiry times. Also shows how to update an existing key's description. ```rust use meilisearch_sdk::{client::Client, key::{Action, KeyBuilder}}; use time::{OffsetDateTime, Duration}; #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); let key = KeyBuilder::new() .with_name("search-only") .with_description("Read-only key for the movies index") .with_action(Action::Search) .with_index("movies") .with_expires_at(OffsetDateTime::now_utc() + Duration::days(365)) .execute(&client) .await .unwrap(); println!("key value: {}", key.key); println!("uid: {}", key.uid); // Later: update description let mut updater = key.into_key_updater(); updater.with_description("Updated description"); updater.execute(&client).await.unwrap(); } ``` -------------------------------- ### Serve Web App Locally Source: https://github.com/meilisearch/meilisearch-rust/blob/main/examples/web_app/README.md Use a simple Python HTTP server to serve the compiled web application locally. This is necessary because browsers have security restrictions that prevent opening local HTML files directly. ```console python3 -m http.server 8080 ``` -------------------------------- ### Update README from Template Source: https://github.com/meilisearch/meilisearch-rust/blob/main/CONTRIBUTING.md Execute this script to regenerate the `README.md` file from its template. Ensure the README is up-to-date before pushing changes. ```bash sh scripts/update-readme.sh ``` -------------------------------- ### Build Release Version Source: https://github.com/meilisearch/meilisearch-rust/blob/main/CONTRIBUTING.md Compile the project in release mode to optimize performance. This command is used for building the final executable. ```bash cargo build --release ``` -------------------------------- ### Check Rust Project Compilation Source: https://github.com/meilisearch/meilisearch-rust/blob/main/examples/web_app/README.md Run this command to verify if the Rust project compiles without issues. ```console cargo build ``` -------------------------------- ### Run All Checks with Docker Source: https://github.com/meilisearch/meilisearch-rust/blob/main/CONTRIBUTING.md Execute all project checks, including tests, using Docker Compose. This ensures a consistent environment for development. ```bash docker-compose run --rm package bash -c "cargo test" ``` -------------------------------- ### Register and Manage Webhooks Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Create, update, list, and delete server-side webhooks that Meilisearch calls when tasks complete. ```rust use meilisearch_sdk::{client::Client, webhooks::{WebhookCreate, WebhookUpdate}}; use std::collections::BTreeMap; #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); // Register a webhook let webhook = client .create_webhook( WebhookCreate::new("https://my-app.example.com/hooks/meilisearch") .with_header("Authorization", "Bearer my-secret"), ) .await .unwrap(); println!("webhook uuid: {}", webhook.uuid); // List all webhooks let list = client.get_webhooks().await.unwrap(); println!("{} webhook(s) registered", list.results.len()); // Update a webhook's URL let mut update = WebhookUpdate::new(); update.set_url("https://my-app.example.com/hooks/v2"); client.update_webhook(webhook.uuid, update).await.unwrap(); // Delete client.delete_webhook(webhook.uuid).await.unwrap(); } ``` -------------------------------- ### Client::create_dump / Client::create_snapshot — backup Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt `create_dump` produces a portable `.dump` file compatible across Meilisearch versions. `create_snapshot` creates a version-specific binary snapshot for fast disaster recovery. ```APIDOC ## Client::create_dump / Client::create_snapshot — backup ### Description `create_dump` produces a portable `.dump` file compatible across Meilisearch versions. `create_snapshot` creates a version-specific binary snapshot for fast disaster recovery. ### Method - `client.create_dump().await` - `client.create_snapshot().await` ### Request Example ```rust use meilisearch_sdk::client::Client; use meilisearch_sdk::tasks::Task; let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); // Export all indexes + documents + settings as a .dump file let dump_task = client .create_dump() .await .unwrap() .wait_for_completion(&client, None, None) .await .unwrap(); assert!(matches!(dump_task, Task::Succeeded { .. })); // Create a binary snapshot for this Meilisearch version let snap_task = client .create_snapshot() .await .unwrap() .wait_for_completion(&client, None, None) .await .unwrap(); assert!(matches!(snap_task, Task::Succeeded { .. })); ``` ### Response - Both methods return a task that can be awaited for completion. Upon success, the task indicates completion. ``` -------------------------------- ### Configure Index Settings Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Use `set_settings` to update various index configurations including searchable attributes, filterable attributes, sortable attributes, stop words, synonyms, typo tolerance, and embedders. The `wait_for_completion` method ensures the settings are applied before proceeding. Use `get_settings` to retrieve the current configuration. ```rust use meilisearch_sdk:: client::Client, settings::{Settings, TypoToleranceSettings, EmbedderSource, Embedder}, ; use std::collections::HashMap; #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); let movies = client.index("movies"); let embedder = Embedder { source: EmbedderSource::OpenAi, model: Some("text-embedding-3-small".into()), api_key: Some("sk-...".into()), dimensions: Some(512), ..Embedder::default() }; let settings = Settings::new() .with_searchable_attributes(["title", "overview"]) .with_filterable_attributes(["genres", "release_year"]) .with_sortable_attributes(["release_year", "rating"]) .with_ranking_rules(["words", "typo", "proximity", "attribute", "sort", "exactness"]) .with_stop_words(["a", "an", "the"]) .with_synonyms(HashMap::from([ ("marvel".to_string(), vec!["MCU".to_string()]), ])) .with_typo_tolerance(TypoToleranceSettings { enabled: Some(true), ..Default::default() }) .with_embedders(HashMap::from([("openai".to_string(), embedder)])); movies .set_settings(&settings) .await .unwrap() .wait_for_completion(&client, None, None) .await .unwrap(); let current = movies.get_settings().await.unwrap(); println!("searchable: {:?}", current.searchable_attributes); } ``` -------------------------------- ### Check README Update Status Source: https://github.com/meilisearch/meilisearch-rust/blob/main/CONTRIBUTING.md Use this script to verify if the `README.md` file is current with its template. The `--diff` option shows the specific changes. ```bash sh scripts/check-readme.sh ``` ```bash sh scripts/check-readme.sh --diff ``` -------------------------------- ### List Documents with Pagination using get_documents Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Retrieve a list of documents with pagination support. The result includes documents, limit, offset, and total count. ```rust use meilisearch_sdk::{client::Client, documents::DocumentsQuery}; use serde::Deserialize; #[derive(Deserialize, Debug)] struct Movie { id: u32, title: String } #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); let movies = client.index("movies"); let results = movies .get_documents::() .await .unwrap(); println!("total: {}", results.total); for m in results.results { println!("{}", m.title); } } ``` -------------------------------- ### Add Meilisearch Rust SDK to Cargo.toml Source: https://github.com/meilisearch/meilisearch-rust/blob/main/README.md Add this to your Cargo.toml to include the meilisearch-sdk crate. Optional dependencies like futures and serde can also be added for enhanced functionality. ```toml [dependencies] meilisearch-sdk = "0.33.0" futures = "0.3" # To be able to block on async functions if you are not using an async runtime serde = { version = "1.0", features = ["derive"] } ``` -------------------------------- ### Build Web App with wasm-pack Source: https://github.com/meilisearch/meilisearch-rust/blob/main/examples/web_app/README.md Compile the Rust project into WebAssembly for web deployment. The --target=web flag specifies the output format, and --no-typescript prevents TypeScript bindings generation. ```console wasm-pack build . --target=web --no-typescript ``` -------------------------------- ### Client::get_indexes / Client::list_all_indexes Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Retrieves a list of all indexes in the Meilisearch instance. `get_indexes` returns a paginated result, while `list_all_indexes` fetches all indexes at once. ```APIDOC ## Client::get_indexes / Client::list_all_indexes — list indexes `get_indexes` returns a paginated `IndexesResults`. `list_all_indexes` iterates all pages and returns `Vec`. ```rust use meilisearch_sdk::client::Client; #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); // Paginated let page = client.get_indexes().await.unwrap(); println!("total: {}, returned: {}", page.total, page.results.len()); // All at once let all = client.list_all_indexes().await.unwrap(); for idx in &all { println!("{}", idx.uid); } } ``` ``` -------------------------------- ### Client::create_index Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Schedules the creation of a new index in Meilisearch. It returns a TaskInfo which can be used to track the creation process and obtain an Index handle. ```APIDOC ## Client::create_index — create an index Schedules index creation and returns a `TaskInfo`. Call `.wait_for_completion` to block until the index is ready, then `.try_make_index` to obtain an `Index` handle. ```rust use meilisearch_sdk::client::Client; #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); let index = client .create_index("movies", Some("id")) // uid, optional primary key .await .unwrap() .wait_for_completion(&client, None, None) // default interval 50 ms, timeout 5 s .await .unwrap() .try_make_index(&client) .unwrap(); assert_eq!(index.uid, "movies"); } ``` ``` -------------------------------- ### Derive IndexConfig for Type-Driven Settings Generation Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Use the `#[derive(IndexConfig)]` macro to auto-generate a `Settings` struct and an async `generate_index` method from field attributes. This simplifies setting up index configurations based on your struct's fields. ```rust use meilisearch_sdk::{client::Client, documents::IndexConfig}; use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, IndexConfig)] struct Movie { #[index_config(primary_key)] id: u64, #[index_config(displayed, searchable)] title: String, #[index_config(displayed)] overview: String, #[index_config(filterable, sortable, displayed)] release_year: u32, #[index_config(filterable, displayed)] genres: Vec, } #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); // Auto-generates settings from field attributes let settings = Movie::generate_settings(); println!("{:?}", settings.searchable_attributes); // Creates the index named "movie" with correct primary key let _index = Movie::generate_index(&client).await.ok(); } ``` -------------------------------- ### Toggle Experimental Features with Meilisearch Rust Client Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Demonstrates how to enable or disable server-side experimental features such as metrics, logs route, vector search, `contains` filter, document editing by function, and multimodal search. ```rust use meilisearch_sdk::{client::Client, features::ExperimentalFeatures}; #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); // Enable selected features let mut features = ExperimentalFeatures::new(&client); features .set_metrics(true) .set_contains_filter(true) .set_network(true) .set_multimodal(true); features.update().await.unwrap(); // Read current state let state = ExperimentalFeatures::new(&client).get().await.unwrap(); println!("metrics: {}, network: {}", state.metrics, state.network); } ``` -------------------------------- ### Add Documents to Meilisearch Index Source: https://github.com/meilisearch/meilisearch-rust/blob/main/README.md Demonstrates how to add multiple documents to a Meilisearch index using the Rust SDK. If the index does not exist, it will be created. Ensure your `Movie` struct derives `Serialize` and `Deserialize`. ```rust use meilisearch_sdk::client::*; use serde::{Serialize, Deserialize}; use futures::executor::block_on; #[derive(Serialize, Deserialize, Debug)] struct Movie { id: usize, title: String, genres: Vec, } #[tokio::main(flavor = "current_thread")] async fn main() { // Create a client (without sending any request so that can't fail) let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY)).unwrap(); // An index is where the documents are stored. let movies = client.index("movies"); // Add some movies in the index. If the index 'movies' does not exist, Meilisearch creates it when you first add the documents. movies.add_documents(&[ Movie { id: 1, title: String::from("Carol"), genres: vec!["Romance".to_string(), "Drama".to_string()] }, Movie { id: 2, title: String::from("Wonder Woman"), genres: vec!["Action".to_string(), "Adventure".to_string()] }, Movie { id: 3, title: String::from("Life of Pi"), genres: vec!["Adventure".to_string(), "Drama".to_string()] }, Movie { id: 4, title: String::from("Mad Max"), genres: vec!["Adventure".to_string(), "Science Fiction".to_string()] }, Movie { id: 5, title: String::from("Moana"), genres: vec!["Fantasy".to_string(), "Action".to_string()] }, Movie { id: 6, title: String::from("Philadelphia"), genres: vec!["Drama".to_string()] }, ], Some("id")).await.unwrap(); } ``` -------------------------------- ### Add WASM Target and Check Compilation Source: https://github.com/meilisearch/meilisearch-rust/blob/main/CONTRIBUTING.md Configure the Rust toolchain to include the WebAssembly target and then check the compilation of the 'web_app' crate for this target. This is useful for projects involving WebAssembly. ```bash rustup target add wasm32-unknown-unknown cargo check -p web_app --target wasm32-unknown-unknown ``` -------------------------------- ### Run Clippy Linter with Warnings Disabled Source: https://github.com/meilisearch/meilisearch-rust/blob/main/CONTRIBUTING.md Execute Clippy, the Rust linter, and treat all warnings as errors. This ensures that the code adheres to Rust best practices and style guidelines. ```bash cargo clippy -- -D warnings ``` -------------------------------- ### Custom Search with Highlighting Source: https://github.com/meilisearch/meilisearch-rust/blob/main/README.md Executes a custom search query and highlights the matching terms in the results. The `with_attributes_to_highlight` method specifies which attributes to highlight. ```rust let search_result = client.index("movies_3") .search() .with_query("phil") .with_attributes_to_highlight(Selectors::Some(&["*"])) .execute::() .await .unwrap(); println!("{:?}", search_result.hits); ``` -------------------------------- ### Format Code with Cargo Source: https://github.com/meilisearch/meilisearch-rust/blob/main/CONTRIBUTING.md Run this command to automatically format your Rust code according to project standards. Use the `--check` flag to verify formatting without making changes. ```bash cargo fmt ``` ```bash cargo fmt --all -- --check ``` -------------------------------- ### Client::get_network / Client::update_network Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Manage a Meilisearch network (federated cluster) by registering remote instances. Requires the `network` experimental feature. ```APIDOC ## Client::get_network / Client::update_network — network topology Manage a Meilisearch network (federated cluster) by registering remote instances. Requires the `network` experimental feature. ### Description This method allows you to manage the network topology of a Meilisearch cluster by registering remote instances. It is useful for setting up federated clusters. ### Method - `update_network`: POST - `get_network`: GET ### Endpoint - `/network` (for `update_network`) - `/network` (for `get_network`) ### Parameters (for `update_network`) #### Request Body - **remotes** (object) - Optional - A map of remote instance names to their configuration. - **url** (string) - Required - The URL of the remote instance. - **search_api_key** (string) - Optional - The API key for searching on the remote instance. - **write_api_key** (string) - Optional - The API key for writing to the remote instance. - **self_name** (string) - Optional - The name of the current Meilisearch instance. ### Request Example (for `update_network`) ```json { "remotes": { "replica-1": { "url": "http://replica1:7700", "search_api_key": "searchKey1", "write_api_key": null } }, "self_name": "primary" } ``` ### Response (for `get_network`) #### Success Response (200) - **remotes** (object) - A map of remote instance names to their configuration. - **self_name** (string) - The name of the current Meilisearch instance. ### Response Example (for `get_network`) ```json { "remotes": { "replica-1": { "url": "http://replica1:7700", "search_api_key": "searchKey1", "write_api_key": null } }, "self_name": "primary" } ``` ``` -------------------------------- ### Manage Meilisearch Network Topology Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Register remote instances to manage a Meilisearch network (federated cluster). Requires the `network` experimental feature. ```rust use meilisearch_sdk::{client::Client, network::{NetworkUpdate, RemoteConfig}}; use std::collections::HashMap; #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); let update = NetworkUpdate { remotes: Some(HashMap::from([ ("replica-1".into(), Some(RemoteConfig { url: "http://replica1:7700".into(), search_api_key: "searchKey1".into(), write_api_key: None, })), ])), self_name: Some("primary".into()), ..Default::default() }; client.update_network(update).await.unwrap(); let state = client.get_network().await.unwrap(); println!("remotes: {:?}", state.remotes.as_ref().map(|r| r.keys().collect::>())); } ``` -------------------------------- ### Implement Custom HttpClient for Meilisearch SDK Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Plug in a custom asynchronous HTTP client by implementing the `HttpClient` trait. This allows integration with libraries like `awc` for Actix or for testing purposes. ```rust use async_trait::async_trait; use meilisearch_sdk::{ client::Client, errors::Error, request::{HttpClient, Method}, }; use serde::{de::DeserializeOwned, Serialize}; struct MyHttpClient { /* ... */ } #[async_trait(?Send)] impl HttpClient for MyHttpClient { async fn request< Query: Serialize + Send + Sync, Body: Serialize + Send + Sync, Output: DeserializeOwned + 'static + Send, >( &self, url: &str, method: Method, expected_status_code: u16, ) -> Result { // custom HTTP implementation todo!() } } fn create_custom_client() -> Client { Client::new_with_client( "http://localhost:7700", Some("masterKey"), MyHttpClient { /* ... */ }, ) } ``` -------------------------------- ### Client::create_key / KeyBuilder — manage API keys Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Create scoped API keys with specific actions and index restrictions. Keys can also carry an expiry timestamp. ```APIDOC ## Client::create_key / KeyBuilder — manage API keys ### Description Create scoped API keys with specific actions and index restrictions. Keys can also carry an expiry timestamp. ### Method ```rust KeyBuilder::new()...execute(&client).await ``` ### Parameters KeyBuilder allows setting: - `name`: Name of the key - `description`: Description for the key - `action`: Allowed actions (e.g., `Action::Search`) - `index`: Index restrictions - `expires_at`: Expiry timestamp ### Request Example ```rust use meilisearch_sdk::{client::Client, key::{Action, KeyBuilder}}; use time::{OffsetDateTime, Duration}; let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); let key = KeyBuilder::new() .with_name("search-only") .with_description("Read-only key for the movies index") .with_action(Action::Search) .with_index("movies") .with_expires_at(OffsetDateTime::now_utc() + Duration::days(365)) .execute(&client) .await .unwrap(); ``` ### Response - `key`: The created API key string. - `uid`: The unique identifier of the created key. ``` -------------------------------- ### SearchQuery — hybrid / vector search Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Shows how to combine keyword and semantic search using `with_hybrid`. It also explains how to provide a user-supplied vector via `with_vector` when using `userProvided` embedders. ```APIDOC ## SearchQuery — hybrid / vector search Combine keyword and semantic search with `with_hybrid`. Provide a user-supplied vector via `with_vector` when using `userProvided` embedders. ```rust use meilisearch_sdk::client::Client; use serde::Deserialize; #[derive(Deserialize, Debug)] struct Movie { id: u32, title: String } #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); let movies = client.index("movies"); // semantic_ratio 0.0 = pure keyword, 1.0 = pure semantic let query_vector: Vec = vec![0.1, 0.9, 0.3]; // must match embedder dimensions let results = movies .search() .with_query("space exploration") .with_hybrid("openai", 0.7) .with_vector(&query_vector) .with_retrieve_vectors(true) .execute::() .await .unwrap(); println!("query vector returned: {:?}", results.query_vector.is_some()); } ``` ``` -------------------------------- ### Client::get_tasks_with / TasksSearchQuery Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt List and filter tasks in the Meilisearch queue using `Client::get_tasks_with` and `TasksSearchQuery`. You can filter tasks by type, status, index UID, and date ranges. ```APIDOC ## Client::get_tasks / TasksSearchQuery — list and filter tasks Query the task queue with filters: type, status, index uid, date ranges, and cancellation source. ```rust use meilisearch_sdk::{client::Client, tasks::TasksSearchQuery}; #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); let results = client .get_tasks_with( &TasksSearchQuery::new(&client) .with_index_uids(["movies"]) .with_limit(20), ) .await .unwrap(); println!("total tasks: {}", results.total); for task in &results.results { println!("uid={} status={}", task.uid, task.status); } } ``` ``` -------------------------------- ### Client webhooks Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Create, update, list, and delete server-side webhooks that Meilisearch calls when tasks complete. ```APIDOC ## Client webhooks — register and manage webhooks Create, update, list, and delete server-side webhooks that Meilisearch calls when tasks complete. ### Description This section describes how to manage server-side webhooks using the Meilisearch SDK. Webhooks can be created, updated, listed, and deleted to receive notifications when Meilisearch tasks are completed. ### Methods - `create_webhook`: POST - `get_webhooks`: GET - `update_webhook`: PUT - `delete_webhook`: DELETE ### Endpoints - `/webhooks` (for `create_webhook`, `get_webhooks`) - `/webhooks/{uuid}` (for `update_webhook`, `delete_webhook`) ### Parameters (for `create_webhook`) #### Request Body - **url** (string) - Required - The URL to which the webhook notification will be sent. - **headers** (object) - Optional - A map of custom headers to include in the webhook request. ### Request Example (for `create_webhook`) ```json { "url": "https://my-app.example.com/hooks/meilisearch", "headers": { "Authorization": "Bearer my-secret" } } ``` ### Response (for `create_webhook`) #### Success Response (201 Created) - **uuid** (string) - The unique identifier of the created webhook. - **url** (string) - The URL of the webhook. - **headers** (object) - The headers configured for the webhook. - **created_at** (string) - The timestamp when the webhook was created. - **updated_at** (string) - The timestamp when the webhook was last updated. ### Response Example (for `create_webhook`) ```json { "uuid": "some-uuid", "url": "https://my-app.example.com/hooks/meilisearch", "headers": { "Authorization": "Bearer my-secret" }, "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:00:00Z" } ``` ### Parameters (for `update_webhook`) #### Path Parameters - **uuid** (string) - Required - The unique identifier of the webhook to update. #### Request Body - **url** (string) - Optional - The new URL for the webhook. - **headers** (object) - Optional - A map of custom headers to include in the webhook request. ### Response Example (for `update_webhook`) (Returns the updated webhook object, similar to the `create_webhook` success response) ### Response (for `get_webhooks`) #### Success Response (200 OK) - **results** (array) - A list of registered webhooks. - Each item in the array is a webhook object with `uuid`, `url`, `headers`, `created_at`, and `updated_at` fields. ### Response Example (for `get_webhooks`) ```json { "results": [ { "uuid": "some-uuid", "url": "https://my-app.example.com/hooks/meilisearch", "headers": { "Authorization": "Bearer my-secret" }, "created_at": "2023-10-27T10:00:00Z", "updated_at": "2023-10-27T10:00:00Z" } ] } ``` ``` -------------------------------- ### Meilisearch Test With Macro Source: https://github.com/meilisearch/meilisearch-rust/blob/main/meilisearch-test-macro/README.md A simplified Meilisearch test using the meilisearch_test macro. The macro automatically handles client creation, index creation/deletion, and provides an index instance to the test function. ```rust #[meilisearch_test] async fn test_get_tasks(index: Index, client: Client) -> Result<(), Error> { let tasks = index.get_tasks().await?; // The only task is the creation of the index assert_eq!(status.results.len(), 1); } ``` -------------------------------- ### Generate Tenant Tokens with Meilisearch Rust Client Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Shows how to generate JWT tenant tokens for scoped access to specific indexes, optionally with per-index filters. The token is signed client-side with a valid API key. ```rust use meilisearch_sdk::client::Client; use serde_json::json; use time::{OffsetDateTime, Duration}; #[tokio::main] async fn main() { // Must be a key created via the keys API (not masterKey) let client = Client::new("http://localhost:7700", Some("xxxxxxxxxxxxxxxx")).unwrap(); let token = client .generate_tenant_token( "76cf8b87-fd12-4688-ad34-260d930ca4f4".to_string(), // api_key_uid (UUID v4) json!({ "movies": { "filter": "user_id = 42" }, // restrict to user's own docs "public_index": {} // unrestricted access }), None, // no expiry Some(OffsetDateTime::now_utc() + Duration::hours(1)), ) .unwrap(); // Use the tenant token to create a scoped client let scoped_client = Client::new("http://localhost:7700", Some(token)).unwrap(); let results = scoped_client.index("movies").search().execute::().await.unwrap(); println!("user sees {} documents", results.hits.len()); } ``` -------------------------------- ### Perform Federated Search Across Multiple Indexes Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Use `multi_search` with `with_search_query_and_weight` to combine results from different indexes, allowing you to bias the ranking with weights. Ensure the `federation` parameter is configured with desired limits and offsets. ```rust use meilisearch_sdk:: client::Client, search::{FederationOptions, SearchQuery}, ; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Debug)] #[serde(untagged)] enum AnyDoc { Movie { id: u32, title: String }, Show { id: u32, name: String } } #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); let movies = client.index("movies"); let shows = client.index("tv_shows"); let q_movies = SearchQuery::new(&movies).with_query("space").build(); let q_shows = SearchQuery::new(&shows).with_query("space").build(); let response = client .multi_search() .with_search_query_and_weight(q_movies, 2.0) // boost movies .with_search_query(q_shows) .with_federation(FederationOptions { limit: Some(10), offset: Some(0), ..Default::default() }) .execute::() .await .unwrap(); println!("merged hits: {}", response.hits.len()); // Each hit includes _federation metadata: for hit in &response.hits { if let Some(fed) = &hit.federation { println!(" from index: {}", fed.index_uid); } } } ``` -------------------------------- ### Inspect Task Batches with BatchesQuery Source: https://context7.com/meilisearch/meilisearch-rust/llms.txt Use `BatchesQuery` to inspect how Meilisearch's autobatcher groups tasks. Supports pagination and filtering for detailed analysis of task batching. ```rust use meilisearch_sdk::{client::Client, batches::BatchesQuery}; #[tokio::main] async fn main() { let client = Client::new("http://localhost:7700", Some("masterKey")).unwrap(); let batches = BatchesQuery::new(&client) .with_limit(10) .execute() .await .unwrap(); for batch in &batches.results { println!( "batch uid={} tasks={{:?}} strategy={{:?}}", batch.uid, batch.task_uids, batch.batch_strategy ); } } ``` -------------------------------- ### Update Dependencies Source: https://github.com/meilisearch/meilisearch-rust/blob/main/CONTRIBUTING.md Ensure that all project dependencies are updated to their latest compatible versions. This is crucial for maintaining consistency across environments, especially in CI. ```bash cargo update ```