三、快速入门

这个快速入门教程将帮助你在几个步骤内就能使用 MeiliseSearch。

下载 & 启动

下载 & 启动请查看二 、安装 & SDK & 各种工具

添加文档

往MeiliSearch添加文档,需要:

  • JSON 对象数组形式的文档。
  • 一个索引的名字(uid)。索引是文档存储的位置。

如果索引不存在,则 Meilisearch 在首次添加文档时创建它。

要进行处理,所有文档必须共享一个公共字段,该字段将作为文档的主键。该字段中的值必须始终是唯一的。

[
  {
    "id": "123",
    "title": "Superman"
  }
]

主键是id, 文档的唯一标识是“123”。

有几种方法可以让 Meilisearch 知道主键是什么。最简单的方法是使用一个以不区分大小写的方式包含字符串 id 的属性。

如下示例,展示如何将文档添加到名为 movies 的索引中。首先需要点击下载测试文件: movies.json。然后,将下载的文件移动到你的工作目录。

cURL

curl \
  -X POST 'http://127.0.0.1:7700/indexes/movies/documents' \
  -H 'Content-Type: application/json' \
  --data-binary @movies.json

JS

安装

npm install meilisearch
//或者 yarn add meilisearch

使用

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

//或者
//import { MeiliSearch } from 'meilisearch'
//import movies from '../small_movies.json'

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

Python

安装

pip3 install meilisearch

使用

import meilisearch
import json

client = meilisearch.Client('http://127.0.0.1:7700')

json_file = open('movies.json')
movies = json.load(json_file)
client.index('movies').add_documents(movies)

PHP

安装

composer require meilisearch/meilisearch-php \
    guzzlehttp/guzzle \
    http-interop/http-factory-guzzle:^1.0

使用

<?php

require_once __DIR__ . '/vendor/autoload.php';

use MeiliSearch\Client;

$client = new Client('http://127.0.0.1:7700');

$movies_json = file_get_contents('movies.json');
$movies = json_decode($movies_json);

$client->index('movies')->addDocuments($movies);

Java

安装

<--! MAVEN -->
<dependency>
  <groupId>com.meilisearch.sdk</groupId>
  <artifactId>meilisearch-java</artifactId>
  <version>0.7.0</version>
  <type>pom</type>
</dependency>

# Gradle
implementation 'com.meilisearch.sdk:meilisearch-java:0.7.0'

Ruby

安装

$ bundle add meilisearch

使用

require 'json'
require 'meilisearch'

client = MeiliSearch::Client.new('http://127.0.0.1:7700')

movies_json = File.read('movies.json')
movies = JSON.parse(movies_json)

client.index('movies').add_documents(movies)

Go

安装

go get -u github.com/meilisearch/meilisearch-go

使用

package main

import (
  "os"
  "encoding/json"
  "io/ioutil"

  "github.com/meilisearch/meilisearch-go"
)

func main() {
  client := meilisearch.NewClient(meilisearch.ClientConfig{
    Host: "http://127.0.0.1:7700",
  })

  jsonFile, _ := os.Open("movies.json")
  defer jsonFile.Close()

  byteValue, _ := ioutil.ReadAll(jsonFile)
  var movies []map[string]interface{}
  json.Unmarshal(byteValue, &movies)

  _, err := client.Index("movies").AddDocuments(movies)
  if err != nil {
      panic(err)
  }
}

c#

安装

dotnet add package MeiliSearch

使用

using System.IO;
using System.Text.Json;
using Meilisearch;
using System.Threading.Tasks;
using System.Collections.Generic;

namespace Meilisearch_demo
{
    public class Movie
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public string Poster { get; set; }
        public string Overview { get; set; }
        public IEnumerable<string> Genres { get; set; }
    }

    internal class Program
    {
        static async Task Main(string[] args)
        {
            MeilisearchClient client = new MeilisearchClient("http://localhost:7700", "masterKey");
            var options = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            };

            string jsonString = await File.ReadAllTextAsync("movies.json");
            var movies = JsonSerializer.Deserialize<IEnumerable<Movie>>(jsonString, options);

            var index = client.Index("movies");
            await index.AddDocumentsAsync<Movie>(movies);
        }
    }
}

Rust

安装

  [dependencies]
  meilisearch-sdk = "0.14"
  # futures: because we want to block on futures
  futures = "0.3"
  # serde: required if you are going to use documents
  serde = { version="1.0",   features = ["derive"] }
  # serde_json: required in some parts of this guide
  serde_json = "1.0"

使用

  1. Rust 库中的文档是强类型的。你必须在一个结构体上实现 Document trait,这样才能在 Meilisearch 中使用它
#[derive(Serialize, Deserialize, Debug)]
struct Movie {
  id: String,
  title: String,
  poster: String,
  overview: String,
  release_date: i64,
  genres: Vec<String>
}
impl Document for Movie {
  type UIDType = String;
  fn get_uid(&self) -> &Self::UIDType { &self.id }
}
  1. 在本文档的其他部分中,您通常会需要这个 Movie 结构体。你也可以使用无模式值,在你自己的结构体中放一个 serde_json::Value,如下所示:
#[derive(Serialize, Deserialize, Debug)]
struct Movie {
  id: String,
  #[serde(flatten)]
  value: serde_json::Value,
}

impl Document for Movie {
  type UIDType = String;
  fn get_uid(&self) -> &Self::UIDType { &self.id }
}
  1. 然后,将文档添加到索引中
use meilisearch_sdk::{
  indexes::*,
  document::*,
  client::*,
  search::*,
  progress::*,
  settings::*
};
use serde::{Serialize, Deserialize};
use std::{io::prelude::*, fs::File};
use futures::executor::block_on;

fn main() { block_on(async move {
  let client = Client::new("http://localhost:7700", "masterKey");

  // reading and parsing the file
  let mut file = File::open("movies.json").unwrap();
  let mut content = String::new();
  file.read_to_string(&mut content).unwrap();
  let movies_docs: Vec<Movie> = serde_json::from_str(&content).unwrap();

  // adding documents
  client.index("movies").add_documents(&movies_docs, None).await.unwrap();
})}

Swift

安装

  dependencies: [
    .package(url: "https://github.com/meilisearch/meilisearch-swift.git", from: "0.12.0")
  ]

使用

  let path = Bundle.main.url(forResource: "movies", withExtension: "json")
  let documents: Data = Data(contentsOf: path)

  let client = try! MeiliSearch(host: "http://localhost:7700")
  client.index("movies").addDocuments(documents: documents) { (result: Result<Update, Swift.Error>) in
      switch result {
      case .success(let update):
          print(update)
      case .failure(let error):
          print(error)
      }
  }

Dart

安装

dependencies:
  meilisearch: ^0.3.1

使用

import 'package:meilisearch/meilisearch.dart';
import 'dart:io';
import 'dart:convert';

var client = MeiliSearchClient('http://127.0.0.1:7700', 'masterKey');

final jsonFile = await File('movies.json').readAsString();
final movies = json.decode(jsonFile);
await client.index('movies').addDocuments(movies);

检查任务状态

Meilisearch 中的大多数操作都是异步的,包括文档添加过程。下面是添加文档后应该收到的响应的一个示例。

{
    "uid": 1,
    "indexUid": "movies",
    "status": "enqueued",
    "type": "documentAddition",
    "enqueuedAt": "2021-08-11T09:25:53.000000Z"
}

异步操作返回一个包含多个字段的 JSON 对象,其中最重要的是 uid。这表示已经考虑了该操作,并且一旦到达队列的前端,将对其进行处理。若要查看任务的当前状态,请查看该文章

查询

现在文档已经添加到 Meilisearch 中了,你可以搜索它们了。

Meilisearch 提供了许多参数,您可以使用这些参数来改进搜索或更改返回文档的格式。然而,默认情况下,搜索已经是相关的了。

cURL

curl \
  -X POST 'http://127.0.0.1:7700/indexes/movies/search' \
  -H 'Content-Type: application/json' \
  --data-binary '{ "q": "botman" }'

JS

client.index('movies').search('botman').then((res) => console.log(res))

Python

client.index('movies').search('botman')

PHP

$client->index('movies')->search('botman');

JAVA

client.index("movies").search("botman");

Ruby

client.index('movies').search('botman')

Go

resp, err := client.Index("movies").Search("botman", &meilisearch.SearchRequest{})
if err != nil {
    panic(err)
}

c#

MeilisearchClient client = new MeilisearchClient("http://localhost:7700", "masterKey");
var index = client.Index("movies");

SearchResult<Movie> movies = await index.SearchAsync<Movie>("harry pottre");
foreach (var movie in movies.Hits)
{
    Console.WriteLine(movie.Title);
}

Rust

let query: Query = Query::new(&movies)
  .with_query("botman")
  .build();

let results: SearchResults<Movie> = client.index("movies").execute_query(&query).await.unwrap();

Swift

  client.index("movies").search(searchParameters) { (result: Result<SearchResult<Movie>, Swift.Error>) in
      switch result {
      case .success(let searchResult):
          print(searchResult)
      case .failure(let error):
          print(error)
      }
  }

Dart

await client.index('movies').search('botman');

MeiliSearch返回

{
  "hits": [
    {
      "id": "29751",
      "title": "Batman Unmasked: The Psychology of the Dark Knight",
      "poster": "https://image.tmdb.org/t/p/w1280/jjHu128XLARc2k4cJrblAvZe0HE.jpg",
      "overview": "Delve into the world of Batman and the vigilante justice tha",
      "release_date": "2008-07-15"
    },
    {
      "id": "471474",
      "title": "Batman: Gotham by Gaslight",
      "poster": "https://image.tmdb.org/t/p/w1280/7souLi5zqQCnpZVghaXv0Wowi0y.jpg",
      "overview": "ve Victorian Age Gotham City, Batman begins his war on crime",
      "release_date": "2018-01-12"
    },
    …
  ],
  "offset": 0,
  "limit": 20,
  "processingTimeMs": 2,
  "query": "botman"
}

默认情况下,Meilisearch 只返回搜索查询的前20个结果。你可以在这里阅读更多关于限制参数的信息。

搜索预览

MeiliSearch还提供了开箱即用的搜索预览,使用浏览器访问 http://ip:7700 进入其预览界面。

3foxd-3u4q5.gif