PHP code example of sllhsmile / hyperf-elasticsearch
1. Go to this page and download the library: Download sllhsmile/hyperf-elasticsearch library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
sllhsmile / hyperf-elasticsearch example snippets
declare(strict_types=1);
namespace App\Model;
use SllhSmile\Elasticsearch\Model\DocumentModel;
final class Article extends DocumentModel
{
protected string $index = 'articles';
protected string $connection = 'default';
protected array $casts = [
'views' => 'int',
'published' => 'bool',
];
}
declare(strict_types=1);
namespace App\Service;
use App\Model\Article;
use SllhSmile\Elasticsearch\Hyperf\Manager;
final class ArticleSearchService
{
public function __construct(private readonly Manager $elasticsearch)
{
}
public function demo(): array
{
$indices = $this->elasticsearch->connection()->indexManager();
if (! $indices->exists('articles')) {
$indices->create(
index: 'articles',
mappings: [
'properties' => [
'title' => ['type' => 'text'],
'status' => ['type' => 'keyword'],
'views' => ['type' => 'integer'],
'published' => ['type' => 'boolean'],
],
],
);
}
Article::create(
attributes: [
'title' => 'Hyperf Elasticsearch 入门',
'status' => 'published',
'views' => 10,
'published' => true,
],
id: 'article-1',
options: ['refresh' => 'wait_for'],
);
$result = Article::query()
->where('status', 'published')
->whereMatch('title', 'Hyperf')
->orderBy('_score', 'desc')
->size(20)
->search();
return [
'total' => $result->total(),
'items' => array_map(
static fn (Article $article): array => array_merge(
['id' => $article->getKey()],
$article->toArray(),
),
$result->hits(),
),
];
}
}
$article = Article::create(['title' => 'PHP', 'views' => 10], 'article-2');
$article = Article::find('article-2'); // 文档不存在时返回 null
$article?->update(['views' => 11]);
$article?->delete();
$result = Article::query()
->where('status', 'published')
->whereRange('views', ['gte' => 10])
->highlight(['title'])
->trackTotalHits()
->size(20)
->search();
foreach ($result as $article) {
echo $article->title;
}
$result = Article::query()
->replaceDsl([
'query' => [
'function_score' => [
'query' => ['match' => ['title' => 'Hyperf']],
'boost_mode' => 'multiply',
],
],
'size' => 10,
])
->search();
bash
php bin/hyperf.php vendor:publish sllhsmile/hyperf-elasticsearch --id=elasticsearch-config