<?php
namespace AppHttpControllersadmin;
use IlluminateHttpRequest;
use AppHttpControllersController;
use AppadminArticleModel;
use IlluminateSupportFacadesEvent;
use AppEventsEs;
use IlluminateSupportFacadesValidator;
use ElasticsearchClientBuilder;
use NunoMaduroCollisionHighlighter;
class ArticleController extends Controller
{
private $esClient;//定义成员变量esclient
public function __construct()
{
$this->esClient = ClientBuilder::create()->setHosts(config("esconfig"))->build();
}
//创建索引并指定分词器
public function makeIndex(Request $request) {
$index = $request->input("index_name");
// 创建索引
$params = [
// 生成索引的名称
'index' => $index,
// 类型 body
'body' => [
'settings' => [
// 分区数
'number_of_shards' => 5,
// 副本数
'number_of_replicas' => 1
],
'mappings' => [
// 字段 类似表字段,设置类型
'properties' => [
'title' => [
'type' => 'text',
'analyzer' => 'ik_max_word',
'search_analyzer' => 'ik_max_word'
],
'content' => [
'type' => 'text',
// 中文分词 张三你好 张三 你好 张三你好
'analyzer' => 'ik_max_word',
'search_analyzer' => 'ik_max_word'
]
]
]
]
];
// 创建索引
$response = $this->esClient->indices()->create($params);
return $response;
}
/**
* @desc 添加文章
* @param Request $request
* @return array
*/
public function create(Request $request) {
$validator = Validator::make($request->all(), [
'title' => 'required|max:100',
'content' => 'required',
]);
if ($validator->fails()) {
return ["code" => "failed","message" => "参数错误"];
}
$articleModel = new ArticleModel();
$articleModel->title = $request->input("title");
$articleModel->content = $request->input("content");
if($articleModel->save()) {
$id = $articleModel->id;
$title = $articleModel->title;
$content = $articleModel->content;
$params = [
'index' => 'articles',
'type' => '_doc',
'id' => $id,
'body' => [
'title' => $title,
'content' => $content,
],
];
// 添加数据到索引文档中
$this->esClient->index($params);
//事件分发,索引文章
// Event::dispatch(new Es($articleModel));
return ["code" => "succ","message" => "成功"];
}
}
public function search(Request $request) {
$searchKey = $request->input("searchkey");
$response = [];
if($searchKey) {
$params = [
'index' => 'articles',
'body' => [
'_source' => true,
'query' => [
'multi_match' => [
'query' => $searchKey,
"fields" => ["title", "content"]
]
],
'highlight' => array(
'fields' => array(
'title' => new Highlighter(),
'content' => new Highlighter()
)
)
]
];
$response = $this->esClient->search($params);
$tmp = $tmpResult = [];
if($response['hits']['total']['value'] > 0 ) {
foreach($response['hits']['hits'] as $res) {
$tmp["_id"] = $res["_id"];
$tmp["_source"] = $res["_source"];
$tmp["title"] = isset($res["highlight"]["title"][0])?$res["highlight"]["title"][0]:'';
$tmp["content"] = $res["highlight"]["content"][0];
$tmpResult[] = $tmp;
}
}
}
return ["code" => "succ","message" => "成功",'data' => $tmpResult];
//return view("admin.search",compact("tmpResult"));
}
}