一 : 打开本地的elasticsearch和kibana环境
-
win键 + r 键
-
输入cmd 启动命令行工具
-
切换到es目录 启动es
-
切换到kibana目录 启动kibana
二 : 在框架内下载composer插件
composer require elasticsearch/elasticsearch
三 : 使用命令创建elasticsearch的控制器
php artisan make:controller Api/esasticSearchController
四 : 在控制器内的命名空间下调用
use ElasticsearchClientBuilder;
五 : 添加索引的方法
public function createDatabase()
{
//本地调用实例化
$client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
//创建索引
$params = [
'index' => 'goods',//数据库名
'body' => [
'settings' => [
'number_of_shards' => 5,//创建后可以更改
'number_of_replicas' => 1//创建后不可以更改
],
'mappings' => [
'_doc' => [
'_source' => [
'enabled' => true
],
'properties' => [
//搜索的字段名
'title' => [
'type' => 'text',
'analyzer' => 'ik_max_word',//ik分词器
'search_analyzer' => 'ik_max_word'
]
]
]
]
]
];
//将索引添加到kibana中
$response = $client->indices()->create($params);
//判断结果
if($response){
//执行成功
return "索引添加成功";
}else{
//执行失败
return "索引添加失败";
}
}
六 : 将数据添加到kibana中
public function createData()
{
//本地调用实例化
$hosts = [
'127.0.0.1:9200'
];
//请求连接
$client = ClientBuilder::create()->setHosts($hosts)->build();
//查询数据表所有的数据并转化数组格式
$date = ApiTitle::all()->toArray();
//循环
foreach ($date as $v)
{
$data = [
'index' => 'goods',//更改索引名(数据库名) 其余不变
'type' => '_doc',
'id' => $v['id'],
'body' => $v,
];
$response = $client->index($data);
}
//判断 是否添加数据成功
if($response){
return "添加数据成功";
}else{
return "添加数据失败";
}
}
七 : 创建需要搜索文章的控制器
php artisan make:controller Api/TitleController
八 : 搜索的方法
public function search(Request $request)
{
//接值
$word = $request->get('title');
if (!$word){
return ['code' => 500,'msg' => '未检测到值','data' => ''];
}
//请求连接
$client = ClientBuilder::create()->build();
//搜索的值和库中的值进行对比
$params = [
'index' => 'goods',//数据库名
'type' => '_doc',
'body' => [
'query' => [
'match' => [
//要搜索的字段↓
'title' => $word//要搜索的内容
]
],
'highlight' => [
'pre_tags' => [""],//样式
'post_tags' => [""],
'fields' => [
//要搜索的字段↓
"title" => new stdClass()
]
]
],
];
//执行搜索
$results = $client->search($params);
//循环取出值
foreach ($results['hits']['hits'] as &$v){
$v['_source']['title'] = $v['highlight']['title'][0];
}
//替换
$response =array_column($results['hits']['hits'],'_source');
//返回
return ['code' => 200,'msg' => '请求成功','data' => $response];
}
PS:如果在微信小程序中使用的话是直接将标签和值一起输出到页面的,需要加入解析富文本的标签才可以将标签转化格式



