PHP系列 | MeiliSearch 輕量搜索引擎入門介紹

介紹
MeiliSearch是一個功能強大,快速,開源,易於使用和部署的搜索引擎。搜索和索引都是高度可定製的。允許輸入、過濾器和同義詞等特性都是開箱即用的。是近兩年開源的項目,同樣也支持中文分詞,在小數據規模下可以實現比ElasticSearch更加快速和易用的搜索體驗。

第 1 步:設置和安裝

我們將從下載和安裝 Meil​​isearch 開始。您可以選擇在本地安裝 Meil​​isearch 或通過雲服務部署

Docker部署

# Fetch the latest version of Meilisearch image from DockerHub
docker pull getmeili/meilisearch:latest

# Launch Meilisearch
docker run -it --rm \
    -p 7700:7700 \
    -v d:/work/meilisearch/data.ms:/data.ms \
    getmeili/meilisearch:latest

運行Meilisearch

成功運行 Meil​​isearch 後,您應該會看到以下響應:

 恭喜!您已準備好繼續下一步!

第 2 步:添加文檔

對於這個快速入門,我們將使用PHP作爲演示案例

安裝PHP的SDK

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

SDK 地址 https://github.com/meilisearch/meilisearch-php/

添加索引文檔

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

use MeiliSearch\Client;

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

# An index is where the documents are stored.
$index = $client->index('movies');

$documents = [
    ['id' => 1,  'title' => 'Carol', 'genres' => ['Romance, Drama']],
    ['id' => 2,  'title' => 'Wonder Woman', 'genres' => ['Action, Adventure']],
    ['id' => 3,  'title' => 'Life of Pi', 'genres' => ['Adventure, Drama']],
    ['id' => 4,  'title' => 'Mad Max: Fury Road', 'genres' => ['Adventure, Science Fiction']],
    ['id' => 5,  'title' => 'Moana', 'genres' => ['Fantasy, Action']],
    ['id' => 6,  'title' => 'Philadelphia', 'genres' => ['Drama']],
];

# If the index 'movies' does not exist, Meilisearch creates it when you first add the documents.
$index->addDocuments($documents); // => { "uid": 0 }

 基礎搜索

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

# An index is where the documents are stored.
$index = $client->index('movies');
// Meilisearch is typo-tolerant:
$hits = $index->search('wondre woman')->getHits();
print_r($hits);

 打印信息

 自定義搜索

$index->search(
    'phil',
    [
        'attributesToHighlight' => ['*'],
    ]
)->getRaw(); // Return in Array format

 輸出結果

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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章