PHP系列 | 搜尋引擎meilisearch入門介紹
阿新 • • 發佈:2022-03-13
介紹
MeiliSearch是一個功能強大,快速,開源,易於使用和部署的搜尋引擎。搜尋和索引都是高度可定製的。允許輸入、過濾器和同義詞等特性都是開箱即用的。是近兩年開源的專案,同樣也支援中文分詞,在小資料規模下可以實現比ElasticSearch更加快速和易用的搜尋體驗。
第 1 步:設定和安裝
我們將從下載和安裝 Meilisearch 開始。您可以選擇在本地安裝 Meilisearch 或通過雲服務部署
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
成功執行 Meilisearch 後,您應該會看到以下響應:
恭喜!您已準備好繼續下一步!
第 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"
}