laravel8 elasticsearch 配置搭建使用
laravel 8框架 扩展elasticsearch
首先 elasticsearch 的版本号 需要和 扩展的版本号对应
composer require elasticsearch/elasticsearch
然后是配置到common 调用文件
<?php
namespace App\Es;
use Elasticsearch\ClientBuilder;
class MyEs
{
//ES客户端链接
private $client;
/**
* 构造函数
* MyElasticsearch constructor.
*/
public function __construct()
{
// 带有账号、密码的客服端信息 $hosts = [ [ 'host' => '127.0.0.1', // 域名 'port' => '9200', // 端口 'scheme' => 'http', // 协议 'user' => 'elastic', // 账号 'pass' => '123456' // 密码 ] ];$this->client = ClientBuilder::create()->setHosts($hosts)->build();
}
/**
* 判断索引是否存在
* @param string $index_name
* @return bool|mixed|string
*/
public function exists_index($index_name = 'test_ik')
{
$params = [
'index' => $index_name
];
try {
return $this->client->indices()->exists($params);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
$msg = $e->getMessage();
$msg = json_decode($msg,true);
return $msg;
}
}
/**
* 创建索引
* @param string $index_name
* @return array|mixed|string
*/
public function create_index($index_name = 'test_ik') { // 只能创建一次
$params = [
'index' => $index_name,
'body' => [
'settings' => [
'number_of_shards' => 5,
'number_of_replicas' => 1
]
]
];
try {
return $this->client->indices()->create($params);
} catch (\Elasticsearch\Common\Exceptions\BadRequest400Exception $e) {
$msg = $e->getMessage();
$msg = json_decode($msg,true);
return $msg;
}
}
/**
* 删除索引
* @param string $index_name
* @return array
*/
public function delete_index($index_name = 'test_ik') {
$params = ['index' => $index_name];
$response = $this->client->indices()->delete($params);
return $response;
}
/**
* 添加文档
* @param $id
* @param $doc ['id'=>100, 'title'=>'phone']
* @param string $index_name
* @param string $type_name
* @return array
*/
public function add_doc($id,$doc,$index_name = 'test_ik',$type_name = 'goods')
