Getting Started

This quick tour will help you get started with MeiliSearch in only a few steps.

Download and launch

First of all, let’s download and run MeiliSearch.

  1. $ curl -L https://install.meilisearch.com | sh
  2. $ ./meilisearch
  3. Server is listening on: http://127.0.0.1:7700

You can download & run MeiliSearch in many different ways (i.e: docker, apt, brew, …).

Environment variables and options can be set before and on launch to configure MeiliSearch. Amongst all the options, you can use the master key and the port options.

Communicate with MeiliSearch

Now that your MeiliSearch server is up and running, you should be able to communicate with it.

Communication to the server is done through a RESTful API or one of our SDKs.

Add Documents

To add documents to MeiliSearch you must provide:

  • Documents in the form of JSON objects.
  • An index name (uid). An index is where the documents are stored.

If the index does not exist, MeiliSearch creates it when you first add documents.

To be processed, all documents must share one common which will serve as for the document. Values in that field must always be unique.

  1. {
  2. "id": "123",
  3. "title": "Superman"
  4. }

The primary key is id, the document’s unique identifier is 123.

There are several ways to let MeiliSearch know what the primary key is. The easiest one is to have an that contains the string id in a case-insensitive manner.

Below is an example to showcase how to add documents to an index called movies using the following test dataset: movies.jsonGetting Started - 图1 (opens new window).

  1. $ curl \
  2. -X POST 'http://127.0.0.1:7700/indexes/movies/documents' \
  3. --data @movies.json
  1. $ npm install meilisearch
  2. # or
  3. $ yarn add meilisearch

Import

require syntax:

  1. const { MeiliSearch } = require('meilisearch')
  2. const movies = require('./movies.json')

import syntax:

  1. import { MeiliSearch } from 'meilisearch'
  2. import movies from '../small_movies.json'

Use

  1. const client = new MeiliSearch({ host: 'http://127.0.0.1:7700' })
  2. client.index('movie').addDocuments(movies)
  3. .then((res) => console.log(res))

About this package

  1. $ pip3 install meilisearch
  1. import meilisearch
  2. import json
  3. client = meilisearch.Client('http://127.0.0.1:7700')
  4. json_file = open('movies.json')
  5. movies = json.load(json_file)
  6. client.index('movies').add_documents(movies)

About this package

Using meilisearch-php with the Guzzle HTTP client:

  1. $ composer require meilisearch/meilisearch-php guzzlehttp/guzzle http-interop/http-factory-guzzle:^1.0
  1. <?php
  2. require_once __DIR__ . '/vendor/autoload.php';
  3. use MeiliSearch\Client;
  4. $client = new Client('http://127.0.0.1:7700');
  5. $movies_json = file_get_contents('movies.json');
  6. $movies = json_decode($movies_json);
  7. $client->index('movies')->addDocuments($movies);

About this package

  1. $ bundle add meilisearch
  1. require 'json'
  2. require 'meilisearch'
  3. client = MeiliSearch::Client.new('http://127.0.0.1:7700')
  4. movies_json = File.read('movies.json')
  5. movies = JSON.parse(movies_json)
  6. client.index('movies').add_documents(movies)

About this gem

  1. go get -u github.com/meilisearch/meilisearch-go
  1. package main
  2. import (
  3. "os"
  4. "encoding/json"
  5. "io/ioutil"
  6. "github.com/meilisearch/meilisearch-go"
  7. )
  8. func main() {
  9. var client = NewClient(meilisearch.Config{
  10. Host: "http://127.0.0.1:7700",
  11. })
  12. jsonFile, _ := os.Open("movies.json")
  13. defer jsonFile.Close()
  14. byteValue, _ := ioutil.ReadAll(jsonFile)
  15. var movies []map[string]interface{}
  16. json.Unmarshal(byteValue, &movies)
  17. update, err := client.Documents("movies").AddOrReplace(movies) // => { "updateId": 0 }
  18. if err != nil {
  19. panic(err)
  20. }
  21. }

About this package

  1. [dependencies]
  2. meilisearch-sdk = "0.4"
  3. tokio = { version = "0.2", features = ["macros"] } # required if you are not targeting wasm
  4. serde = { version="1.0", features = ["derive"] } # required if you are going to use documents
  5. serde_json = "1.0" # required in some parts of this guide

Documents in the Rust library are strongly typed. You have to implement the Document trait on a struct to be able to use it with Meilisearch.

  1. #[derive(Serialize, Deserialize, Debug)]
  2. struct Movie {
  3. id: String,
  4. title: String,
  5. poster: String,
  6. overview: String,
  7. release_date: i64,
  8. genres: Vec<String>
  9. }
  10. impl Document for Movie {
  11. type UIDType = String;
  12. fn get_uid(&self) -> &Self::UIDType { &self.id }
  13. }

You will often need this Movie struct in other parts of this documentation. (you will have to change it a bit sometimes) You can also use schemaless values, by putting a serde_json::Value inside your own struct like this:

  1. #[derive(Serialize, Deserialize, Debug)]
  2. struct Movie {
  3. id: String,
  4. #[serde(flatten)]
  5. value: serde_json::Value,
  6. }
  7. impl Document for Movie {
  8. type UIDType = String;
  9. fn get_uid(&self) -> &Self::UIDType { &self.id }
  10. }

Then, add documents into the index:

  1. use meilisearch_sdk::{indexes::*, document::*, client::*, search::*, progress::*, settings::*};
  2. use serde::{Serialize, Deserialize};
  3. use std::{io::prelude::*, fs::File};
  4. #[tokio::main]
  5. async fn main() {
  6. let client = Client::new("http://localhost:7700", "masterKey");
  7. // reading and parsing the file
  8. let mut file = File::open("movies.json").unwrap();
  9. let mut content = String::new();
  10. file.read_to_string(&mut content).unwrap();
  11. let movies_docs: Vec<Movie> = serde_json::from_str(&content).unwrap();
  12. // adding documents
  13. let movies = client.get_or_create_index("movies").await.unwrap();
  14. movies.add_documents(&movies_docs, None).await.unwrap();
  15. }

About this package

API references

Checking updates

Most actions are asynchronous, which allows you to stack them. All of the actions are executed in the order in which they were sent.

The document addition process returns a JSON object containing only an updateId attribute.

This kind of successful response indicates that the operation has been taken into account, but may not have been executed yet.

You can check the status of the operation via the updateId and the get update status route.

Checking the update status is not a mandatory step to search through your documents but could prove useful in tracing the origin of errors or unexpected behaviors.

API references

Search

Now that your documents have been ingested into MeiliSearch, you are able to search them.

MeiliSearch offers many parameters that you can play with to refine your search or change the format of the returned documents. However, by default, the search is already relevant.

The search engine is now aware of your documents and can serve those via an HTTP server.

  1. $ curl 'http://127.0.0.1:7700/indexes/movies/search' \
  2. --data '{ "q": "botman" }'
  1. index.search('botman').then((res) => console.log(res))

About this package

  1. index.search('botman')

About this package

  1. $index->search('botman');

About this package

  1. index.search('botman')

About this gem

  1. results, err := client.Search("movies").Search(meilisearch.SearchRequest{
  2. Query: "botman",
  3. })
  4. if err != nil {
  5. panic(err)
  6. }

About this package

You can build a Query and execute it later:

  1. let query: Query = Query::new(&movies)
  2. .with_query("botman")
  3. .build();
  4. let results: SearchResults<Movie> = movies.execute_query(&query).await.unwrap();

You can build a Query and execute it directly:

  1. let results: SearchResults<Movie> = Query::new(&movies)
  2. .with_query("botman")
  3. .execute()
  4. .await
  5. .unwrap();

You can search in an Index directly:

  1. let results: SearchResults<Movie> = movies.search()
  2. .with_query("botman")
  3. .execute()
  4. .await
  5. .unwrap();

About this package

MeiliSearch response:

  1. {
  2. "hits": [
  3. {
  4. "id": "29751",
  5. "title": "Batman Unmasked: The Psychology of the Dark Knight",
  6. "poster": "https://image.tmdb.org/t/p/w1280/jjHu128XLARc2k4cJrblAvZe0HE.jpg",
  7. "overview": "Delve into the world of Batman and the vigilante justice tha",
  8. "release_date": "2008-07-15"
  9. },
  10. {
  11. "id": "471474",
  12. "title": "Batman: Gotham by Gaslight",
  13. "poster": "https://image.tmdb.org/t/p/w1280/7souLi5zqQCnpZVghaXv0Wowi0y.jpg",
  14. "overview": "ve Victorian Age Gotham City, Batman begins his war on crime",
  15. "release_date": "2018-01-12"
  16. }
  17. ...
  18. ],
  19. "offset": 0,
  20. "limit": 20,
  21. "processingTimeMs": 2,
  22. "query": "botman"
  23. }

API references

Web Interface

We also deliver an out-of-the-box web interface in which you can test MeiliSearch interactively.

To do so, open your web browser and enter MeiliSearch address (in our case: http://127.0.0.1:7700) into the browser address bar.
This will lead you to a web page with a search bar that will allow you to search in the selected index.

Integrate to Your Project

The only step missing now is adding the search bar to your project. The easiest way of achieving this is to use instant-meilisearchGetting Started - 图2 (opens new window): a developer tool that generates all the search components needed to start searching.

Instant MeiliSearchGetting Started - 图3 (opens new window) works on common front-end environments, such as JavaScriptGetting Started - 图4 (opens new window), ReactGetting Started - 图5 (opens new window), and Vue.jsGetting Started - 图6 (opens new window).

instant-meilisearch uses InstantSearchGetting Started - 图7 (opens new window) an open-source library that generates everything you need from a search interface.

Let’s Try!

  • Create an html file, for example, index.html.
  • Open it in a text editor (e.g. Notepad, Sublime Text, Visual Studio Code).
  • Copy-paste any of the code examples below and save the file.
  • Open index.html in your browser (double click on it in your folder).

We use browser builds for ease of integration. It is possible to do this with npm or yarn. Please refer to instant-meilisearchGetting Started - 图8 (opens new window) for documentation.

The following code sample uses plain JavaScriptGetting Started - 图9 (opens new window).

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="utf-8" />
  5. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@meilisearch/instant-meilisearch/templates/basic_search.css" />
  6. </head>
  7. <body>
  8. <div class="wrapper">
  9. <div id="searchbox" focus></div>
  10. <div id="hits"></div>
  11. </div>
  12. <script src="https://cdn.jsdelivr.net/npm/@meilisearch/instant-meilisearch/dist/instant-meilisearch.umd.min.js"></script>
  13. <script src="https://cdn.jsdelivr.net/npm/instantsearch.js@4"></script>
  14. <script>
  15. const search = instantsearch({
  16. indexName: "movies",
  17. searchClient: instantMeiliSearch(
  18. "http://localhost:7700"
  19. )
  20. });
  21. search.addWidgets([
  22. instantsearch.widgets.searchBox({
  23. container: "#searchbox"
  24. }),
  25. instantsearch.widgets.configure({ hitsPerPage: 8 }),
  26. instantsearch.widgets.hits({
  27. container: "#hits",
  28. templates: {
  29. item: `
  30. <div>
  31. <div class="hit-name">
  32. {{#helpers.highlight}}{ "attribute": "title" }{{/helpers.highlight}}
  33. </div>
  34. </div>
  35. `
  36. }
  37. })
  38. ]);
  39. search.start();
  40. </script>
  41. </body>
  42. </html>

The code above comes in multiple parts:

  • The first four lines of the <body> add both searchbox and hits elements. Ultimately, instant-meilisearch adds the search bar and search results in these elements.
  • <script src=".."> tags are CDNsGetting Started - 图10 (opens new window) that import libraries needed to run instant-meilisearch.
  • The JavaScript part is where you customize instant-meilisearch.

To use instant-meilisearch using npm or yarn please visit instant-meilisearchGetting Started - 图11 (opens new window).

The following code sample uses Vue.jsGetting Started - 图12 (opens new window) framework.

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8" />
  5. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@meilisearch/instant-meilisearch/templates/basic_search.css" />
  6. </head>
  7. <body>
  8. <div id="app" class="wrapper">
  9. <ais-instant-search :search-client="searchClient" index-name="movies" >
  10. <ais-configure :hits-per-page.camel="10" />
  11. <ais-search-box placeholder="Search here…" class="searchbox"></ais-search-box>
  12. <ais-hits>
  13. <div slot="item" slot-scope="{ item }">
  14. <ais-highlight :hit="item" attribute="title" />
  15. </div>
  16. </ais-hits>
  17. </ais-instant-search>
  18. </div>
  19. </body>
  20. <script src="https://cdn.jsdelivr.net/npm/vue"></script>
  21. <script src="https://cdn.jsdelivr.net/npm/vue-instantsearch@3.2.0/dist/vue-instantsearch.js"></script>
  22. <script src="https://cdn.jsdelivr.net/npm/@meilisearch/instant-meilisearch/dist/instant-meilisearch.umd.min.js"></script>
  23. <script>
  24. Vue.use(VueInstantSearch)
  25. var app = new Vue({
  26. el: '#app',
  27. data: {
  28. searchClient: instantMeiliSearch('http://127.0.0.1:7700')
  29. }
  30. })
  31. </script>
  32. </html>

The code above comes in multiple parts:

  • In Vue.js customization happens directly in the <body> tag. To make instant-meilisearch work with Vue.js some components must be added. In the above example, ais-instant-search, ais-search-box and ais-hits are mandatory components to generate theinstant-meilisearch interface.
  • <script src=".."> tags are CDNsGetting Started - 图13 (opens new window) that import libraries needed to run instant-meilisearch with Vue.jsGetting Started - 图14 (opens new window).
  • The <script> containing JavaScript initialize Vue.js. The code creates a new Vue instance that is mandatory to link Vue.js with the DOM.

To use instant-meilisearch in Vue.js using npm or yarn please visit meilisearch-vueGetting Started - 图15 (opens new window).

The following code sample uses ReactGetting Started - 图16 (opens new window) framework.

  1. <!DOCTYPE html>
  2. <head>
  3. <meta charset="utf-8" />
  4. <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@meilisearch/instant-meilisearch/templates/basic_search.css" />
  5. </head>
  6. <html>
  7. <body>
  8. <div id="app" class="wrapper"></div>
  9. </body>
  10. <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
  11. <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
  12. <script src="https://cdn.jsdelivr.net/npm/react-instantsearch-dom@6.7.0/dist/umd/ReactInstantSearchDOM.js"></script>
  13. <script src="https://cdn.jsdelivr.net/npm/@meilisearch/instant-meilisearch/dist/instant-meilisearch.umd.min.js"></script>
  14. <script>
  15. const { InstantSearch, SearchBox, Hits, Highlight, Configure } = ReactInstantSearchDOM;
  16. const searchClient = instantMeiliSearch(
  17. "http://localhost:7700"
  18. );
  19. const App = () => (
  20. React.createElement(InstantSearch, {
  21. indexName: "movies",
  22. searchClient: searchClient
  23. }, [
  24. React.createElement(SearchBox, { key: 1 }),
  25. React.createElement(Hits, { hitComponent: Hit, key: 2 }),
  26. React.createElement(Configure, { hitsPerPage: 10 })]
  27. )
  28. );
  29. function Hit(props) {
  30. return React.createElement(Highlight, {
  31. attribute: "title",
  32. hit: props.hit
  33. })
  34. }
  35. const domContainer = document.querySelector('#app');
  36. ReactDOM.render(React.createElement(App), domContainer);
  37. </script>
  38. </html>

The code above comes in multiple parts:

  • The <body> of the page is the entry point for React. instant-meilisearch adds the search bar and search results here by manipulating the DOM.
  • <script src=".."> tags are CDNsGetting Started - 图17 (opens new window) that import libraries needed to run instant-meilisearch in ReactGetting Started - 图18 (opens new window).
  • The <script> containing JavaScript initalize React and renders the code that will be rendered in the body. Customization of instant-meilisearch happens here as well.

To use instant-meilisearch in React using npm or yarn please visit meilisearch-reactGetting Started - 图19 (opens new window).

You should now have a MeiliSearch database and a working front-end search interface 🚀🔥 Check out What’s Next to continue your MeiliSearch journey.