Meilisearch Rust SDK

repository·main·Indexed 19 days ago

https://github.com/meilisearch/meilisearch-rust

The official asynchronous Rust wrapper for the Meilisearch API. It provides tools for interacting with Meilisearch instances, including document management, typo-tolerant searching, and attribute filtering. The SDK includes support for WebAssembly (WASM) and provides helper macros like `meilisearch_test` for integration testing and `IndexConfig` for automating index settings generation.

Tokens
33.8K
Snippets
134
Records
153
Agent score
63%

What's inside meilisearch-sdk

  1. Run the Meilisearch GraphQL example

    main

    This example demonstrates a full-stack setup using async_graphql and actix-web for the GraphQL server, diesel for PostgreSQL database queries, and meilisearch-sdk to perform searches.

    To run the example, you must first ensure a Meilisearch server is running. Then, execute the application using Cargo.

    # 1. Start Meilisearch
    meilisearch --master-key <your master key>
    
    # 2. Run the application
    cargo run --release
  2. Install the Meilisearch Rust SDK

    main

    To use the meilisearch-sdk in your Rust project, add it to your Cargo.toml dependencies. The crate is async by default, so you will likely need an async runtime like tokio or the futures crate to block on async functions.

    Optional dependencies:

    • futures = "0.3": Useful if you are not using an async runtime and need to block on futures.
    • serde = { version = "1.0", features = ["derive"] }: Highly recommended as most SDK features require serde for serialization/deserialization.

    You can also enable the sync feature to make most structs Sync, though this may result in slightly slower performance.

    [dependencies]
    meilisearch-sdk = "0.33.0"
    
    # Optional dependencies
    futures = "0.3"
    serde = { version = "1.0", features = ["derive"] }
  3. Run the WebAssembly web application

    main

    Because of browser security restrictions, you cannot open the compiled index.html file directly from the file system. You must serve the pkg directory using a web server.

    To serve the application locally, navigate to the examples/web_app/pkg directory and run a local server (e.g., using Python):

    ```console
    # Navigate to the pkg directory first
    cd pkg
    python3 -m http.server 8080

    Then, access the application at http://localhost:8080/ in your browser.

  4. Perform a search with filters

    main

    To use filtering, you must first register the attributes you want to filter by using set_filterable_attributes. This is a one-time operation per index, but note that updating these settings triggers an index rebuild.

    Once configured, you can apply filters using .with_filter("filter_expression") in your search query.

    // 1. Configure filterable attributes (do this once)
    let filterable_attributes = ["id", "genres"];
    client.index("movies").set_filterable_attributes(&filterable_attributes).await.unwrap();
    
    // 2. Perform the filtered search
    let search_result = client.index("movies")
      .search()
      .with_query("wonder")
      .with_filter("id > 1 AND genres = Action")
      .execute::<Movie>()
      .await
      .unwrap();
    
    println!("{:?}", search_result.hits);
  5. Use the `meilisearch_test` macro for testing

    main

    The meilisearch_test macro simplifies writing Meilisearch integration tests by automating client initialization and index lifecycle management. It handles the boilerplate of creating a Client, creating a uniquely named Index for parallel test execution, and ensuring the index is deleted after the test completes.

    To use it, annotate your async test function with #[meilisearch_test] and include the desired types (Client, Index, or String) in the function arguments. The macro will inject the initialized objects into your test.

    #[meilisearch_test]
    async fn test_get_tasks(index: Index, client: Client) -> Result<(), Error> {
      let tasks = index.get_tasks().await?;
      // Your test logic here
      Ok(())
    }
  6. What is a BatchStrategy and when is it used?

    main

    The BatchStrategy enum indicates the reason why the Meilisearch autobatcher decided to stop accumulating tasks into a single batch and start processing it. This is useful for debugging performance and understanding how Meilisearch groups operations.

    Available strategies:

    • SizeLimitReached: The batch reached its configured size threshold.
    • TimeLimitReached: The batch reached its configured time window threshold.
    • Unknown: A placeholder for forward-compatibility with future Meilisearch versions.
  7. Create and manage an Index

    main

    An Index represents a collection of documents in Meilisearch. You can interact with an index in two ways:

    1. Remote Creation: Use client.create_index(uid, primary_key) to create an index on the server. This returns a task that you can wait for using .wait_for_completion(). Once the task is finished, use .try_make_index(&client) to obtain an Index object.
    2. Local Initialization: If you know the index already exists, you can create a local handle using Index::new(uid, client). Meilisearch will automatically create the index on the server when you first perform an operation like adding documents or updating settings.

    Common index operations include .update() to apply changes (like setting a primary_key) and .delete() to remove the index.

    // Remote creation pattern
    let movies = client
        .create_index("index", None)
        .await
        .unwrap()
        .wait_for_completion(&client, None, None)
        .await
        .unwrap()
        .try_make_index(&client)
        .unwrap();
    
    // Local handle pattern
    let movies = Index::new("movies", client);
  8. Understand the SimilarResults and SimilarResult data structures

    main

    When performing a similarity search, the API returns a SimilarResults<T> object containing metadata about the query and a list of hits. Each hit is wrapped in a SimilarResult<T>.

    SimilarResults<T>

    • hits: A vector of SimilarResult<T> objects.
    • offset: The number of documents skipped.
    • limit: The number of results returned.
    • estimated_total_hits: Estimated total number of matches.
    • performance_details: Performance trace of the query (if requested).
    • processing_time_ms: Processing time of the query in milliseconds.
    • id: Identifier of the target document used for the search.

    SimilarResult<T>

    • result: The actual document data of type T (flattened into the object).
    • ranking_score: The global ranking score (_rankingScore), if requested.
    • ranking_score_details: Detailed ranking score information (_rankingScoreDetails), if requested.
  9. Use Multi-Search and Federation

    main

    Meilisearch supports searching across multiple indices in a single request using multi_search().

    You can chain multiple search queries together. Each query can optionally be assigned a weight to influence its importance in the federated results.

    Federation

    By calling .with_federation(FederationOptions), you enable the federation feature. This allows Meilisearch to merge results from different indices into a single list of hits, respecting the weights provided for each query.

    // Basic Multi-Search
    let response = client
        .multi_search()
        .with_search_query(query_1)
        .with_search_query(query_2)
        .execute::<Document>()
        .await
        .unwrap();
    
    // Multi-Search with Weights and Federation
    let mut multi_query = client.multi_search();
    multi_query.with_search_query_and_weight(query_test_index.clone(), 999.0);
    multi_query.with_search_query(query_video_index.clone());
    
    let response = multi_query
        .with_federation(FederationOptions::default())
        .execute::<AnyDocument>()
        .await?;
  10. How Meilisearch dumps work

    main

    Meilisearch dumps are .dump files used to export or import the entire state of a Meilisearch instance.

    Exporting (Creating a Dump)

    When you trigger a dump creation, Meilisearch exports all indexes, including their documents and settings, into a single .dump file. The file is saved in the configured dumps directory. If the directory does not exist, Meilisearch will create it.

    Importing (Launching with a Dump)

    To import a dump, you must launch Meilisearch with a specific instance option. During import, all indexes contained in the .dump file are restored. Warning: Any existing index with the same uid as an index in the dump file will be overwritten.

    Key Characteristics

    • Compatibility: Dumps are compatible between different Meilisearch versions.
    • Atomicity: A dump contains everything needed to reconstruct the instance state (indexes, documents, and settings).