Laravel操作ElasticSearch

在Laravel项目中操作ElasticSearch可以通过以下步骤来实现,通常会借助相应的ElasticSearch客户端扩展包。

安装ElasticSearch客户端包

在Laravel项目中,常用的是 `elasticsearch/elasticsearch` 这个PHP客户端库来与ElasticSearch进行交互,使用Composer进行安装:

```bash

composer require elasticsearch/elasticsearch

```### 配置ElasticSearch连接

1. 创建配置文件

在Laravel项目的 `config` 目录下创建 `elasticsearch.php` 配置文件(如果不存在的话),内容示例如下:

```php

php 复制代码
<?php

return [
    'hosts' => [
        [
            'host' => env('ELASTICSEARCH_HOST', 'localhost'),
            'port' => env('ELASTICSEARCH_PORT', 9200),
            'scheme' => env('ELASTICSEARCH_SCHEME', 'http')
        ]
    ],
];

```

这里通过环境变量来获取ElasticSearch服务器的主机地址、端口以及通信协议等信息,你可以在项目的 `.env` 文件中根据实际情况设置对应环境变量的值,比如:

```bash

ELASTICSEARCH_HOST=your_elasticsearch_host

ELASTICSEARCH_PORT=9200

ELASTICSEARCH_SCHEME=http

```#### 2. 创建服务提供者(可选)

可以创建一个自定义的服务提供者来更方便地管理ElasticSearch客户端实例的注入等操作,例如创建 `ElasticSearchServiceProvider.php` 文件放在 `app/Providers` 目录下:

```php

php 复制代码
<?php

namespace App\Providers;

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

class ElasticSearchServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->singleton('elasticsearch', function () {
            $config = config('elasticsearch');
            return ClientBuilder::create()
                ->setHosts($config['hosts'])
                ->build();
        });
    }
}

```

然后在 `config/app.php` 文件的 `providers` 数组中注册这个服务提供者:

```php

php 复制代码
'providers' => [
    // 其他服务提供者
    App\Providers\ElasticSearchServiceProvider::class,
],

```### 基本操作示例

索引操作

  • **创建索引**:

在控制器或者其他合适的类方法中,可以这样创建索引:

```php

php 复制代码
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Elasticsearch\Client;

class ElasticSearchController extends Controller
{
    protected $client;

    public function __construct(Client $client)
    {
        $this->client = $client;
    }

    public function createIndex()
    {
        $params = [
            'index' =>'my_index',
            'body' => [
                'settings' => [
                    'number_of_shards' => 1,
                    'number_of_replicas' => 0
                ]
            ]
        ];

        $response = $this->client->indices()->create($params);

        return response()->json($response);
    }
}

```

  • **查看索引是否存在**:

```php

php 复制代码
public function checkIndexExists()
{
    $params = [
        'index' =>'my_index'
    ];

    $exists = $this->client->indices()->exists($params);

    return response()->json(['exists' => $exists]);
}

```

  • **删除索引**:

```php

php 复制代码
public function deleteIndex()
{
    $params = [
        'index' =>'my_index'
    ];

    $response = $this->client->indices()->delete($params);

    return response()->json($response);
}

```#### 文档操作

  • **插入文档**:

```php

php 复制代码
public function insertDocument()
{
    $params = [
        'index' =>'my_index',
        'type' => '_doc',
        'id' => '1',
        'body' => [
            'title' => '示例文档标题',
            'content' => '这是示例文档的内容'
        ]
    ];

    $response = $this->client->index($params);

    return response()->json($response);
}

```

  • **获取文档**:

```php

php 复制代码
public function getDocument()
{
    $params = [
        'index' =>'my_index',
        'type' => '_doc',
        'id' => '1'
    ];

    $response = $this->client->get($params);

    return response()->json($response);
}

```

  • **更新文档**:

```php

php 复制代码
public function updateDocument()
{
    $params = [
        'index' =>'my_index',
        'type' => '_doc',
        'id' => '1',
        'body' => [
            'doc' => [
                'title' => '更新后的示例文档标题'
            ]
        ]
    ];

    $response = $this->client->update($params);

    return response()->json($response);
}

```

  • **删除文档**:

```php

php 复制代码
public function deleteDocument()
{
    $params = [
        'index' =>'my_index',
        'type' => '_doc',
        'id' => '1'
    ];

    $response = $this->client->delete($params);

    return response()->json($response);
}

```#### 查询操作

例如进行一个简单的匹配查询:

```php

php 复制代码
public function search()
{
    $params = [
        'index' =>'my_index',
        'type' => '_doc',
        'body' => [
            'query' => [
                'match' => [
                    'title' => '示例'
                ]
            ]
        ]
    ];

    $response = $this->client->search($params);

    return response()->json($response);
}

```

以上就是在Laravel项目中操作ElasticSearch的基本流程和常见操作示例,实际应用中可以根据具体业务需求进一步拓展和优化这些操作,比如构建更复杂的查询逻辑、进行数据的批量处理等。

相关推荐
Elasticsearch19 小时前
如何使用 Agent Builder 排查 Kubernetes Pod 重启和 OOMKilled 事件
elasticsearch
BingoGo1 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php
JaguarJack1 天前
OpenSwoole 26.2.0 发布:支持 PHP 8.5、io_uring 后端及协程调试改进
后端·php·服务端
Elasticsearch2 天前
通用表达式语言 ( CEL ): CEL 输入如何改进 Elastic Agent 集成中的数据收集
elasticsearch
JaguarJack2 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
后端·php·服务端
BingoGo2 天前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
php
BingoGo3 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·laravel
JaguarJack3 天前
告别 Laravel 缓慢的 Blade!Livewire Blaze 来了,为你的 Laravel 性能提速
后端·php·laravel
郑州光合科技余经理3 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
QQ5110082854 天前
python+springboot+django/flask的校园资料分享系统
spring boot·python·django·flask·node.js·php