安装Meilisearch SDK
composer require meilisearch/meilisearch-php guzzlehttp/guzzle http-interop/http-factory-guzzle:^1.0
基本使用
<?php
namespace app\controller;
use app\BaseController;
use app\ToolLibrary\JsonUtil;
use app\ToolLibrary\RemoteCallTools;
use Meilisearch\Client;
use think\facade\Env;
use think\facade\View;
class SearchController extends BaseController {
public function index(){
$client = new Client('http://127.0.0.1:7700', 'masterKey');
$index = $client->index('movies');
$documents = [
['id' => 1, 'user_id' => 101, 'title' => 'Carol', 'genres' => ['Romance, Drama']],
['id' => 2, 'user_id' => 101, 'title' => 'Wonder Woman', 'genres' => ['Action, Adventure']],
['id' => 3, 'user_id' => 103, 'title' => 'Life of Pi', 'genres' => ['Adventure, Drama']],
['id' => 4, 'user_id' => 103, 'title' => 'Mad Max: Fury Road', 'genres' => ['Adventure, Science Fiction']],
['id' => 5, 'user_id' => 103, 'title' => 'Moana', 'genres' => ['Fantasy, Action']],
['id' => 6, 'user_id' => 103, 'title' => 'Philadelphia', 'genres' => ['Drama']],
];
$index->addDocuments($documents);
$updatedDocuments = [
['id' => 1, 'title' => 'The Great Gatsby (Updated)', 'author' => 'F. Scott Fitzgerald', 'genre' => 'Literature']
];
$index->updateDocuments($updatedDocuments);
$index->deleteDocuments([2]);
$client->deleteIndex('books');
$indexes = $client->getIndexes();
$result = $index->search('inception');
$result->getHits();
$currentUserId = 101;
$index->updateFilterableAttributes(['user_id']);
$result = $index->search('note', [
'filter' => 'user_id = ' . $currentUserId
]);
$index->updateSortableAttributes(['created_at']);
$result = $index->search('关键词', [
'sort' => ['created_at:desc']
]);
$page = 1;
$perPage = 2;
$offset = ($page - 1) * $perPage;
$searchResult = $index->search('the', [
'limit' => $perPage,
'offset' => $offset,
'sort' => ['created_at:desc'],
'filter' => 'genre = Action OR genre = Sci-Fi'
]);
echo "总匹配数: " . $searchResult->getTotalHits() . PHP_EOL;
$result = $index->search('inception', [
'attributesToHighlight' => ['title'],
'attributesToCrop' => ['description'],
'cropLength' => 20
]);
print_r($result->getHits());
$index->updateSearchableAttributes(['title', 'description', 'content']);
}
}