laravel 以服务提供者的方式使用 elasticsearch

发布于 2023-04-11 01:44:00阅读 1336

安装

安装elasticsearch官方扩展包

composer require elasticsearch/elasticsearch

以服务提供者的方式使用 elasticsearch

可以参考这篇文章:Laravel 以服务提供者的方式使用第三方扩展包

下面给出关键配置

config/es.php

<?php
declare(strict_types=1);

return [
    'hosts' => explode(',', env('ELASTIC_HOSTS')),//['http://elasticsearch:9200']
    'username'  => env('ELASTIC_USERNAME', ''),
    'password'  => env('ELASTIC_PASSWORD', ''),
    'prefix'  => env('ELASTIC_PREFIX'),
];

Providers/ElasticsearchServiceProvider.php

<?php

namespace App\Providers;

use Elasticsearch\ClientBuilder;
use Illuminate\Support\ServiceProvider;

class ElasticsearchServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->singleton(ClientBuilder::class, function ($app) {
            $conf = config('es');
            $client = ClientBuilder::create()->setHosts($conf['hosts']);
            if ($conf['username']) $client->setBasicAuthentication($conf['username'], $conf['password']);
            return $client->build();
        });

        $this->app->alias(ClientBuilder::class, 'es');
    }
}

使用

    $this->prefix = config('es.prefix');
    $this->initArticleIndex();

    /**
     * 创建索引
     */
    protected function initArticleIndex()
    {
        $this->setMapping();

        app('es')->indices()
            ->create([
                'index' => $this->prefix . 'article_index',
                'body'  => [
                    'settings' => [
                        'number_of_shards'   => 2,
                        'number_of_replicas' => 1,
                        'max_result_window'  => 100000
                    ],
                    'mappings' => [
                        'properties' => $this->mapping
                    ]
                ]
            ]);

        app('es')->indices()
            ->putAlias([
                'index' => $this->prefix . 'article_index',
                'name'  => $this->prefix . 'article'
            ]);
    }

    /**
     * 设置字段
     * @throws \Common\Types\Exception
     */
    protected function setMapping()
    {
        $fields = Article::getFields();
        foreach ($fields as $key => $value) {
            if ( ! in_array($value, ['keyword', 'text', 'long', 'integer', 'byte', 'date', 'float', 'double'])) {
                throw new Exception('类型不存在');
            }
            $this->mapping[$key] = ['type' => $value];
        }
    }

参考

参考文档包含一个完整的商品同步,搜索的示例,非常不错

https://blog.csdn.net/weixin_41753567/article/details/125605497

广而告之,我的新作品《语音助手》上架Google Play了,欢迎下载体验