创建索引
/**
* 创建索引
*/
public function index()
{
$client=ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
$parms=[
'index'=>'q', //索引名
'body'=>[
'settings'=>[
'number_of_shards'=>5, //分片数量(后期不可更改)
'number_of_replicas'=>1 //副本数量(后期可更改)
],
'mappings'=>[
// 'table'=>[
// 'enabled'=>true //php版本7.0之后表名默认为‘_doc’,表名可以不加
// ],
//加载ik分词器的字段
'properties' => [
'fang_name' => [
'type' => 'text',
'analyzer' => 'ik_max_word',
'search_analyzer' => 'ik_max_word'
],
]
],
]
];
$response=$client->indices()->create($parms);
print_r($response);
}
添加数据
/**
* //添加数据
*
* @throws \think\db\exception\DataNotFoundException
* @throws \think\db\exception\DbException
* @throws \think\db\exception\ModelNotFoundException
*/
public function add()
{
$data=Fangs::select();
$data&&$data=$data->toArray();
foreach ($data as $k=>$v)
{
$da=$v;
// print_r($da);
$client=ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
$parms=[
'index'=>'q',
'type'=>'_doc',
// 'body'=>$da
'body'=>[
'fang_name'=>$da['fang_name']
]
];
$response=$client->index($parms);
print_r($response);
}
}
高亮搜索
/**
*高亮搜索
*/
public function reads(Request $request)
{
$title=$request->param('fang_name');
$client = ClientBuilder::create()->build();
$params = [
'index' => 'q',
//'type' => '_doc',
'body' => [
'query' => [
'match' => [
'fang_name' => $title
]
],
'highlight' => [
'pre_tags' => ["<em style='color: lightcoral'>"],
'post_tags' => ["</em>"],
'fields' => [
"fang_name" => new \stdClass()
]
]
]
];
$results = $client->search($params);
$arr=[];
foreach ($results['hits']['hits'] as $k=>$v){
$arr[$k]['name']=$v['highlight']['fang_name'];
}
return json(['code'=>0,'msg'=>'成功','data'=>$arr]);
}
普通搜索
/**
* 搜索
*/
public function read()
{
$client=ClientBuilder::create()->build();
$params=[
'index'=>'q',
'type'=>'_doc',
'body'=>[
'query'=>[
'match'=>['fang_name'=>'李四']
]
]
];
$results = $client->search($params);
print_r($results);
}
小程序
<view>
<form catchsubmit="formSubmit" catchreset="formReset">
<input class="weui-input" name="fang_name" placeholder="这是一个输入框" />
<button style="margin: 30rpx 0" type="primary" formType="submit">搜索</button>
</form>
<block>
<view>
<rich-text nodes=" {{str}}"></rich-text>
</view>
</block>
</view>
js
data: {
str:[]
},
formSubmit(e){
let _this=this
let fang_name=e.detail.value.fang_name
wx.request({
url: 'http://www.week.com/index.php/admin/users/reads',
data:{
fang_name:fang_name
},
success:function(ret){
var fang=ret.data.data[0].name[0]
console.log(fang)
_this.setData({
str:fang
})
}
})
},