注释(大白话解读es):
- es就相当于一个数据库,在数据添加时,需要添加一份到es的数据库里。
- 而es搜索就是,先接收前端传过来的数据,然后将es数据库实例化,并在es数据库里搜索
- 搜索出来之后就返回给前端,如果es库里没有找到就去mysql库里找,如果也没有就返回null
- 就拿本人用的header举例
首先启动es
- elasticsearch.bat
前端将需要添加的数据传给后端
/** * 提交数据 */ sub:function(e){ var title = this.data.title var det = this.data.det var goods_price = this.data.goods_price wx.request({ url: 'http://www.syq.com/index.php/api/add', data:{ title:title, det:det, goods_price:goods_price }, success:function(res){ console.log(res) } }) },
后端接收数据并操作
- 接收前端数据
- 将数据加入mysql
- 然后将数据库里的数据拽出来,扔进es库里
/**
* 添加数据
*/
public function add()
{
$title = \request()->get('title');
$det = \request()->get('det');
$goods_price = \request()->get('goods_price');
//添加入库
$data = modellers::create([
'title' => $title,
'det' => $det,
'goods_price' => $goods_price
]);
//将数据转换为数组形式,将你想添加的数据添加进去
$mess = [
'title' => $data['title']
];
$es = new es();
//分别是es库名字,表名字 ,mysql表里的id, 还有你想添加的数据
$es->es('cao', 'ni', $data['id'], $mess);
}
封装es类(添加和搜索)
<?php
namespace App;
//这个记得引用
use Elasticsearch\ClientBuilder;
class es
{
public function __construct(){
$this->client = ClientBuilder::create()->setHosts(['127.0.0.1'])->build();
}
/**
* 索引一个文件
*/
public function es($index,$type,$id,$body){
$params = [
'index' => $index,
'type' => $type,
'id' => $id,
'body' => $body
];
$response = $this->client->index($params);
return $response;
}
/**
* 搜索一个文件
*/
public function search($index,$type,$body){
$params = [
'index' => $index,
'type' =>$type,
'body' => [
'query' => [
'match' => [
//这是搜索那个数据,我的数据名字是title
'title' => $body
]
],
//这是高亮
'highlight'=>[
'pre_tags'=>["<span style='color: red'>"],
'post_tags'=>["</span>"],
'fields'=>[
//声明那个数据高亮
"title"=>new \stdClass()
]
]
]
];
$response = $this->client->search($params);
return $response;
}
}
前端将你要搜索的数据传送到后端
/**
* 点击搜索
*/
sous:function(){
var that = this
var title = this.data.title
wx.request({
url: 'http://www.syq.com/index.php/api/search',
data:{
title:title
},
success:function(res){
//数据搜索到了之后,将搜索到的数据赋值到前端
var data = (res.data.data)
that.setData({
data:data
})
}
})
}
后端接收数据并搜索
/**
* 搜索数据
*/
public function search(){
$title = \request()->get('title');
//实例化es
$es = new es();
//搜索不需要id
$data = $es->search('cao','ni',$title);
$score=$data['hits']['hits'];
foreach ($score as $k=>$v){
$score[$k]['_source']['title']=$v['highlight']['title'][0];
}
//搜索到数据并返回到前端
$title= array_column($score,'_source');
return json_encode(['code'=>200,'msg'=>'成功','data'=>$title]);
}
前端结束后到数据后,赋值到页面
要用一个特定的标签,才可以实现高亮效果
<view class="container log-list">
<block wx:for="{{data}}" wx:for-item="list">
<image src="/image/hzh.jpeg"></image>
//要用rich-text标签,和nodes参数才能实现高亮
<rich-text nodes="{{list.title}}"></rich-text>
<text class="log-item">{{list.goods_price}}</text>
<button bindtap="check" data-id="{{list.id}}">查看详情</button>
</block>
</view>
感谢观看!!!