在 composer.json 文件中引入 elasticsearch-php:然后指定更新 composer update elasticsearch/elasticsearch
{
"require":
"elasticsearch/elasticsearch": "~6.0"
}
创建索引
public function sou(){
$client = ClientBuilder ::create()->setHosts(['127.0.0.1:9200'])->build();
$params = [
'index' => 'qxw',
'body' => [
'settings'=>[
'number_of_shards'=>5, //分片数量(后期不可更改)
'number_of_replicas'=>1 //副本数量(后期可更改)
],
'mappings'=>[
// 'table'=>[
// 'enabled'=>true //php版本7.0之后表名默认为‘_doc’,表名可以不加
// ],
//加载ik分词器的字段
'properties' => [
'name' => [
'type' => 'text',
'analyzer' => 'ik_max_word',
'search_analyzer' => 'ik_max_word'
],
'desc' => [
'type' => 'text',
'analyzer' => 'ik_max_word',
'search_analyzer' => 'ik_max_word'
],
]
],
]
];
$response = $client->indices()->create($params);
}
添加数据到数据库
public function add(){
$client = ClientBuilder::create()->build();
$params = [
'index' => 'qxw',
'type' => '_doc',
//'id' => '1',
'body' => [
'img' => "https://househomecdn.4fqp.com/storage/build/2021/02/21/202102211302369904.jpg",
'name' => "半山洋房",
'desc' => "安吉树兰健康谷售楼处树兰医院旁 小洋房",
]
];
$response = $client->index($params);
print_r($response);
}
搜索
高亮搜索
public function showtime(Request $request){
$title=$request->input('title');
// $title="洋房";
$client = ClientBuilder::create()->build();
$params = [
'index' => 'qxw',
//'type' => '_doc',
'body' => [
'query' => [
'match' => [
'name' => $title
]
],
'highlight' => [
'pre_tags' => ["<em style='color: lightcoral'>"],
'post_tags' => ["</em>"],
'fields' => [
"name" => new \stdClass()
]
]
]
];
$results = $client->search($params);
// print_r($results['hits']['hits']);
$arr=[];
foreach ($results['hits']['hits'] as $k=>$v){
// print_r($v);
// $arr['name']=$v['highlight']['nane'][0];
$arr[$k]['img']=$v['_source']['img'];
$arr[$k]['name']=$v['highlight']['name'][0];
$arr[$k]['desc']=$v['_source']['desc'];
}
// print_r($arr);
return $arr;
}
小程序端
xml
<view>
<form catchsubmit="formSubmit" catchreset="formReset">
<input class="weui-input" name="title" placeholder="这是一个输入框" />
<button style="margin: 30rpx 0" type="primary" formType="submit">搜索</button>
</form>
<block wx:for="{{str}}" wx:key='key'>
<view>
<rich-text nodes="{{item.title}}"></rich-text>
<text>{{item.content}}</text>
</view>
</block>
css
.a{
width: 100%;
height: 100px;
}
.a-1{
width: 40%;
/* height: 100px; */
float: left;
}
.a-1 image{
width: 80px;
height: 80px;
}
.a-2{
width: 60%;
height: 50px;
float: right;
}
js
//高亮搜索
formSubmit(e) {
console.log(e);
var _this = this;
//console.log(e.detail.value.title)
var title = e.detail.value.title;
wx.request({
url: 'http://localhost/index.php/api/showtime',
data:{
title:title
},
success:function(add){
console.log(add.data)
var fang = add.data;
_this.setData({
fang
})
}
})
},