近期公司项目有用到搜索引擎的使用,在一番和智商的博弈后,学会了 ElasticSearch 的使用皮毛。
众多 Elastic 插件,只写了一种
,殊途同归,不管使用哪个插件,应该都是大同小异。
Fadion/Bouncy
-
-
- 环境准备
- 安装 ElasticSearch
- Laravel ElasticSearch 插件安装
- Lumen 插件引用
- 配置文件
- ElasticSearch 使用前设置
- ElasticSearch 使用
- 使用总结
-
环境准备
Windows 7 , Apache-Tomcat-8.5.32 ,Laravel-Lumen ,ElasticSearch
自行
or
BaiDu
配置好java环境
安装 ElasticSearch
下载好 ElasticSearch 后,打开 bin 文件夹, windows系统以管理员身份运行elasticsearch.bat
测试是否安装成功 127.0.0.1:9200,
如果成功,会出现如下界面。
Laravel ElasticSearch 插件安装
Lumen 插件引用
在lumen 的 composer.json 包依赖管理里加入如下插件。
"require": {
"fadion/bouncy": "dev-l5"
},
并运行,
composer update "fadion/bouncy"
, 使 Lumen 更新到此插件。
如下代码需要添加在 bootstrap/app.php 里。即注册新的服务。注册在
AppServiceProvider
之后。
配置文件
把
"fadion/bouncy"
包中的config文件夹中的文件复制到自己的
config
文件夹中,并把
config.php
重命名为
bouncy.php
,如图所示:
引入新的配置文件。
$this->app->configure('elasticsearch');
如果此时 elasticSearch 和 tomcat 启动正常,此时 Lumen 已经可以和 ElasticSearc 互动了。
ElasticSearch 使用前设置
在将要进行索引搜索的 Model 文件里,添加 BouncyTrait 的使用。
添加指定函数
,设定要搜索出来的字段
documentFields
<?php
namespace App\Repository\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Prettus\Repository\Contracts\Transformable;
use Prettus\Repository\Traits\TransformableTrait;
use Illuminate\Database\Eloquent\Builder;
use Fadion\Bouncy\BouncyTrait;
/**
1. Class Products.
2. 3. @package namespace App\Repository\Models;
*/
class Products extends Model implements Transformable
{
use TransformableTrait;
use SoftDeletes;
use BouncyTrait;
/**
* The attributes that are mass assignable.
*
* @var array
*/
public function documentFields()
{
return [
'name'=>$this->name,
'is_new'=>$this->is_new,
'is_onsales'=>$this->is_onsales,
'is_recommend'=>$this->is_recommend,
];
}
}
ElasticSearch 使用
在搜索函数里,此处搜索关键词已经指定,可根据实际需求改成搜索变量。
此时应该是支持分词的。此插件亦支持分页。
public function index(){
// Products::all()->index(); // 全部设置为搜索索引。
$params = [
'query' => [
'match' => [
'name' => '大华 补 光灯'
]
],
'size' =>
];
$data = Products::search($params)->paginate()->toArray();
echo '<pre>';
var_dump($data);
}
如下为搜索结果:
使用总结
- ElasticSearch 的使用 和 solr 的原理是类似的,缺少了一部分精准的信息设置:如 SQL ,指定字段的分词。都不如solr 强大。
- 在使用之前需要将表数据加入到 搜索索引中。如果数据源数据经过操作
或者修改
、新增
,都应该对索引列表进行操作修改。删除
- 详细插件文档学习请移步 Fadion/Bouncy