以PHP代码为例
1、引入 PHP SDK
composer require meilisearch/meilisearch-php http-interop/http-factory-guzzle
2、创建索引
<?php
use Meilisearch\Client;
$client = new Client('http://localhost:7700', 'masterKey');
$client->createIndex('movies', ['primaryKey' => 'id']);
3、导入文档
<?php
$client->index('movies')->addDocuments([
[
'id' => 287947,
'title' => 'Shazam',
'poster' => 'https://image.tmdb.org/t/p/w1280/xnopI5Xtky18MPhK40cZAGAOVeV.jpg',
'overview' => 'A boy is given the ability to become an adult superhero in times of need with a single magic word.',
'release_date' => '2019-03-23'
]
]);
4、搜索
<?php
$client->index('movies')->search('american ninja', [
'hitsPerPage' => 20, # 每页数据量
'page' => 1, # 页码
'matchingStrategy' => 'all', # 匹配策略 last, all, or frequency
'attributesToSearchOn' => ['title', 'overview'] # 限制只将这两个字段作为搜索字段
]);
6、索引重建方法
索引创建后,因为一些后台操作可能导致索引未及时更新,可以采用定时重建索引的方式使索引保持最新的状态
利用交换索引的方式实现以上功能
<?php
use Meilisearch\Client;
# 检查索引是否存在,若不存在创建之;若存在创建新的索引,数据导入后执行交换索引操作,再删除新的索引
$client = new Client('http://localhost:7700', 'masterKey');
$indexName = 'movies';
try {
$indexInfo = $client->index($indexName)->fetchRawInfo();
} catch (\Exception) {
$indexInfo = null;
}
if (!empty($indexInfo)) {
$needSwap = true;
$indexName = 'movies_new';
}
$client->createIndex($indexName, ['primaryKey' => 'id']);
# 数据导入操作
Movies::query()->where(['status' => 1])
->select(['id', 'name', 'desc'])
->chunkById(100, function ($musics) use ($client, $indexName) {
$musics = $musics->toArray();
$client->index($indexName)->addDocuments($musics);
});
if ($needSwap) {
# 交换索引
$client->swapIndexes([['movies', $indexName]]);
# 删除刚才新建的索引
$client->deleteIndex($indexName);
}
参考文档:www.meilisearch.com
[1]
创建索引: https://www.meilisearch.com/docs/reference/api/indexes[2]
导入文档: https://www.meilisearch.com/docs/reference/api/documents#add-or-replace-documents[3]
搜索: https://www.meilisearch.com/docs/reference/api/search[4]
www.meilisearch.com: https://www.meilisearch.com/docs/reference/api/overview