Giter VIP home page Giter VIP logo

meilisearch-rust's Introduction

Meilisearch-Rust

Meilisearch Rust SDK

crates.io Tests License Bors enabled

โšก The Meilisearch API client written for Rust ๐Ÿฆ€

Meilisearch Rust is the Meilisearch API client for Rust developers.

Meilisearch is an open-source search engine. Learn more about Meilisearch.

Table of Contents

๐Ÿ“– Documentation

This readme contains all the documentation you need to start using this Meilisearch SDK.

For general information on how to use Meilisearchโ€”such as our API reference, tutorials, guides, and in-depth articlesโ€”refer to our main documentation website.

โšก Supercharge your Meilisearch experience

Say goodbye to server deployment and manual updates with Meilisearch Cloud. No credit card required.

๐Ÿ”ง Installation

To use meilisearch-sdk, add this to your Cargo.toml:

[dependencies]
meilisearch-sdk = "0.24.1"

The following optional dependencies may also be useful:

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"] }

This crate is async but you can choose to use an async runtime like tokio or just block on futures. You can enable the sync feature to make most structs Sync. It may be a bit slower.

Using this crate is possible without serde, but a lot of features require serde.

Run a Meilisearch Instance

This crate requires a Meilisearch server to run.

There are many easy ways to download and run a Meilisearch instance.

For example,using the curl command in your Terminal:

# Install Meilisearch
curl -L https://install.meilisearch.com | sh

# Launch Meilisearch
./meilisearch --master-key=masterKey

NB: you can also download Meilisearch from Homebrew or APT.

๐Ÿš€ Getting started

Add Documents

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<String>,
}


fn main() { block_on(async move {
    // Create a client (without sending any request so that can't fail)
    let client = Client::new(MEILISEARCH_URL, Some(MEILISEARCH_API_KEY));

    // 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();
})}

With the uid, you can check the status (enqueued, processing, succeeded or failed) of your documents addition using the task.

Basic Search

// Meilisearch is typo-tolerant:
println!("{:?}", client.index("movies_2").search().with_query("caorl").execute::<Movie>().await.unwrap().hits);

Output:

[Movie { id: 1, title: String::from("Carol"), genres: vec!["Romance", "Drama"] }]

Json output:

{
  "hits": [{
    "id": 1,
    "title": "Carol",
    "genres": ["Romance", "Drama"]
  }],
  "offset": 0,
  "limit": 10,
  "processingTimeMs": 1,
  "query": "caorl"
}

Custom Search

let search_result = client.index("movies_3")
  .search()
  .with_query("phil")
  .with_attributes_to_highlight(Selectors::Some(&["*"]))
  .execute::<Movie>()
  .await
  .unwrap();
println!("{:?}", search_result.hits);

Json output:

{
    "hits": [
        {
            "id": 6,
            "title": "Philadelphia",
            "_formatted": {
                "id": 6,
                "title": "<em>Phil</em>adelphia",
                "genre": ["Drama"]
            }
        }
    ],
    "offset": 0,
    "limit": 20,
    "processingTimeMs": 0,
    "query": "phil"
}

Custom Search With Filters

If you want to enable filtering, you must add your attributes to the filterableAttributes index setting.

let filterable_attributes = [
    "id",
    "genres",
];
client.index("movies_4").set_filterable_attributes(&filterable_attributes).await.unwrap();

You only need to perform this operation once.

Note that Meilisearch will rebuild your index whenever you update filterableAttributes. Depending on the size of your dataset, this might take time. You can track the process using the tasks.

Then, you can perform the search:

let search_result = client.index("movies_5")
  .search()
  .with_query("wonder")
  .with_filter("id > 1 AND genres = Action")
  .execute::<Movie>()
  .await
  .unwrap();
println!("{:?}", search_result.hits);

Json output:

{
  "hits": [
    {
      "id": 2,
      "title": "Wonder Woman",
      "genres": ["Action", "Adventure"]
    }
  ],
  "offset": 0,
  "limit": 20,
  "estimatedTotalHits": 1,
  "processingTimeMs": 0,
  "query": "wonder"
}

๐ŸŒ Running in the Browser with WASM

This crate fully supports WASM.

The only difference between the WASM and the native version is that the native version has one more variant (Error::Http) in the Error enum. That should not matter so much but we could add this variant in WASM too.

However, making a program intended to run in a web browser requires a very different design than a CLI program. To see an example of a simple Rust web app using Meilisearch, see the our demo.

WARNING: meilisearch-sdk will panic if no Window is available (ex: Web extension).

๐Ÿค– Compatibility with Meilisearch

This package guarantees compatibility with version v1.x of Meilisearch, but some features may not be present. Please check the issues for more info.

โš™๏ธ Contributing

Any new contribution is more than welcome in this project!

If you want to know more about the development workflow or want to contribute, please visit our contributing guidelines for detailed instructions!


Meilisearch provides and maintains many SDKs and Integration tools like this one. We want to provide everyone with an amazing search experience for any kind of project. If you want to contribute, make suggestions, or just know what's going on right now, visit us in the integration-guides repository.

meilisearch-rust's People

Contributors

bors[bot] avatar mubelotix avatar curquiza avatar meili-bot avatar bidoubiwa avatar vishalsodani avatar irevoire avatar brunoocasali avatar sanders41 avatar abhizer avatar meili-bors[bot] avatar omid avatar romilpunetha avatar ginglis13 avatar isaaccloos avatar amaihoefner avatar evpeople avatar alallema avatar icyjoseph avatar dependabot[bot] avatar puddingpy avatar mk1107 avatar washbin avatar ugzuzg avatar shimatar0 avatar jasperav avatar dependabot-preview[bot] avatar aeledfyr avatar vishnugt avatar sccalabr avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.