一、为什么使用ES
- 因为业务需要,现在需要统计所有出入库、报价、采购的一些数量数据
- 但是最早开发的小伙伴为赶时间将很多数据,没有去做拆分,直接在字段中存入json字符串,可是要统计的数据都在这个json中
- 能想到的解决方案如下:
① 拆表,重写CURD功能
② 数据量不大的前提下直接全表扫描在代码中处理数据
③ 使用mysql存储过程,其实也算是在全表扫描
④ 升级mysql版本到8+,使用其自带的json数据结构去处理数据
⑤ 使用es代替方案①的拆表操作
二、环境
- PHP:8.0.2
- ES:7.6.1
- IK分词器:7.6.1
- es-head
- JDK:1.8
- win10
- 框架
三、启动ES
- ES安装包
- 进入启动目录: cd es安装目录/bin
- 启动ES:./elasticsearch.bat (确保已经安装jdk)
- 安装es-head插件:如何安装es-head
- 安装ik分词器 ik分词器安装包
- 将分词器安装包放置到 es安装目录/plugins
- 重启es
四、安装PHP依赖
- composer require elasticsearch/elasticsearch:^7.6.1
五、在PHP中使用ES
namespace app\common\model;
use Elasticsearch\ClientBuilder;
class EsModel
{
protected $client;
public function __construct()
{
try {
$this->client = ClientBuilder::create()
->setHosts(['127.0.0.1:9200'])
->build();
} catch (\Exception $e) {
echo $e->getMessage();
exit;
}
}
public function addIndex(){
$indexParams = [
'index' => 'product_info',
'body' => [
'settings' => [
'number_of_shards' => 5,
'number_of_replicas' => 1
],
'mappings' => [
'properties' => [
'title_name' => [
'type' => 'text',
'analyzer' => 'ik_smart'
],
'describe' => [
'type' => 'text',
'analyzer' => 'ik_smart'
]
]
]
]
];
$this->client->indices()->create($indexParams);
}
public function addEsData(){
$data = [
[
"index" => ['_id' => 1,]
],
[
"title_name" => "一个新的文章",
"describe" => "陈美凤日前出席假发品牌32周年活动,只见她顶著一头粉色的秀发,再配上深V领黑西服"
],
];
$params = [
'index' => 'product_info',
'body' => $data,
];
$response = $this->client->bulk($params);
}
}
六、查看es数据以及分词结果
- 使用谷歌浏览器打开组件es-head
- es-head复合查询
- http://localhost:9200/{index}/{type}/{id}/_termvectors?fields={fieldName}
index:product_info
type:_doc
id:1
fieldName:describe