1.下载laravel8 支持的es插件
composer require elasticsearch/elasticsearch
2.在要使用的地方引入ES
use ElasticsearchClientBuilder;
3.生成ES对象
$client = ClientBuilder::create()‐>setHosts('连接地址')‐>build();
4.添加信息到es
$client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
//测试数据
$data=[
'id' => 2,
'username' => '小方',
'password' => '111111',
];
//拼接数据
$params = [
'index' => 'test',
'type' => '_doc',
'id' => $data['id'],
'body' => $data
];
//存储到es中
$response = $client->index($params);
return $response;
5.生成es索引
$client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
// 创建索引
$params = [
'index' => 'test',
'body' => [
'settings' => [
'number_of_shards' => 5,
'number_of_replicas' => 1
],
'mappings' => [
'properties' => [
'fang_name' => [
'type' => 'text'
]
]
]
]
];
$response = $client->indices()->create($params);
// print_r($response);
6.搜索内容
$client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
$keyWord='小方';
$params = [
'index' => 'test',
'type' => '_doc',
'body' => [
'query' => [
'match' => [
'username'=>[
'query' => $keyWord
]
]
],
'highlight'=>[
'fields'=>[
'fang_name'=>[
'pre_tags'=>[
''
],
'post_tags'=>[
''
]
]
]
]
]
];
$results = $client->search($params);
foreach ($results['hits']['hits'] as $key => $item)
{
$results['hits']['hits'][$key]['_source']['username'] = $item['highlight'] ['username'][$key];
}
$results = array_column($results['hits']['hits'], '_source');
return $results;
7.修改es内容
$data=[
'id' => 2,
'username' => '小方啊',
'password' => '222222',
];
$params = [
'index' => 'test',
'type' => '_doc',
'id' => $data['id'],
'body' => [
'username' => $data['username'],
'password' => $data['password'],
],
];
$response = $client->index($params);
return $response;
8.删除es数据
$data=[
'id' => 2,
'username' => '小方啊',
'password' => '222222',
];
$params = [
'index' => 'test',
'type' => '_doc',
'id' => $data['id'],
];
$response = $client->delete($params);
return $response;



