先下载es composer
composer require elasticsearch/elasticsearch
先进行判断es中是否有这个索引
$client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
// 写文档
$index=['index'=>'title'];
//判断是否有该索引
$res=$client->indices()->exists($index);
没有这个索引添加索引
if($res!=true)
{
$params = [
//表名
'index' => '表名',
'body' => [
'settings' => [
'number_of_shards' => 5,
'number_of_replicas' => 1
],
'mappings' => [
'_doc' => [
'_source' => [
'enabled' => true
],
'properties' => [
//所需要展示的字符安
'name' => [
'type' => 'text',
'analyzer' => 'ik_max_word',
'search_analyzer' => 'ik_max_word'
],
'title' => [
'type' => 'text',
'analyzer' => 'ik_max_word',
'search_analyzer' => 'ik_max_word'
]
]
]
]
]
];
$client->indices()->create($params);
}
添加数据内容
//添加
$data=$request->input();
unset($data['_token']);
$first=Title::create($data);
$params = [
'index' => 'title',
'type' => '_doc',
'id' => $first->id,
'body' => [
'name' => $first->name,
'title' => $first->title,
],
];
$client->index($params);
//搜索内容
public function index(Request $request)
{
//连接es服务
$client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
$name=$request->input('name');
//搜索的字段
if($name)
{
$create = [
'index' => 'title',
'type' => '_doc',
'body' => [
'query' => [
'match' => [
'name'=>$name
]
],
'highlight' => [//高亮
"pre_tags" => ["<span style='color: red'>"],
"post_tags" => ["</span>"],
"fields" => [
"name" => new \StdClass()
]
]
],
];
$res=$client->search($create)['hits']['hits'];
$data=[];
foreach ($res as $k=>$v){
$data[$k]['name']=$v['highlight']['name'][0];
$data[$k]['title']=$v['_source']['title'];
}
}else{
$data=Title::get()->toArray();
}
return response()->json(['code'=>200,'msg'=>'请求成功','data'=>$data]);
}
微信小程序 展示
<rich-text nodes="{{item.name}}"></rich-text>
解析html标签