Elasticsearch 实现简单搜索
Elasticsearch实现简单搜索
第一步:安装配置
composer require elasticsearch/elasticsearch
选择版本兼容的分词插件,并将分词插件放到elasticsearch中的plugins文件夹下
启动服务:./bin/elasticsearch
第二步:建库建表
curl –X PUT ‘localhost:9200/(表名)’--新建数据库
对应的删除操作:curl –X DELETE‘localhost:9200/(表名)’
根据自己的需求创建表结构:
curl -H'Content-Type: application/json' -XPUT http://localhost:9200/(表名)/_mapping/doc?pretty -d'{
"properties": {
"name": { "type": "text", "analyzer": "ik_smart" },
"email": { "type": "keyword" },
//一维
"word1": {
"type": "nested" ,
"properties":{
"word2":{"type": "text", "analyzer": "ik_smart"}, //分词,可以模糊搜索
"word3":{"type":"keyword"}, //关键字搜索
}
},
//多维
"word4": {
"type": "nested",
"properties":{
"word5":{"type":"keyword"},
"word6":{
type": "nested",
"properties":{
"word7":{"type":"keyword"}
}
}
}
}
}
}'
database.php
'elasticsearch' => [
// Elasticsearch 支持多台服务器负载均衡,因此这里是一个数组
'hosts' => explode(',', env('ES_HOSTS','localhost')),
],
.env配置
ES_HOSTS=localhost
连接本地就好
第三步:PHP使用
注册es用例在Providers/AppServiceProvider.php 中
public function register()
{
// 注册一个名为 es 的单例
$this->app->singleton('es', function () {
// 从配置文件读取 Elasticsearch 服务器列表
$builder = ESClientBuilder::create()->setHosts(config('database.elasticsearch.hosts'));
// 如果是开发环境
if (app()->environment() === 'local') {
// 配置日志,Elasticsearch 的请求和返回数据将打印到日志文件中,方便我们调试
$builder->setLogger(app('log')->getMonolog());
}
return $builder->build();
});
}
搜索:
$queryparams = [
'index' => 'resumes',
'type' => 'doc',
'body' => [
"query" => [
"bool" => [
"must" => [
["match" => [
'name' => ''
]],
["match" => [
'sex' => ''
]],
[
"nested"=>[
"path"=> "education",
"query"=>[
"bool"=>[
"must"=>[
[
"match"=>[
"education.school"=> "北京大学"
]
],
]
]
]
]
]
]]]]];
$es = app('es');
$res = $es->search($queryparams);
return $res;
新增:
$es = app('es');
$es->index([
'index' => '表名',
'type' => 'doc',
'id' => $id,
'body' => $data
]);
更新:
$es = app('es');
$es->index([
'index' => '表名',
'type' => 'doc',
'id' => $id,
'body' => $data
]);
或者(更改数据后_version值更新)
$es = app('es');
$es->update([
'index' => '表名',
'type' => 'doc',
'id' => $id,
'body' =>['doc'=> $data]
]);
删除:
$es = app('es');
$es->delete([
'index' => '表名',
'type' => 'doc',
'id' => $id
]);
获取:
$es = app('es');
$es->get([
'index' => '表名',
'type' => 'doc',
'id' => $id
]);
第一次写,欢迎指出错误?
本作品采用《CC 协议》,转载必须注明作者和本文链接
:joy: 排版建议稍微调下下咯
@Joy_he 已调整,尽力了 :joy: :joy:
mark
mark
mark,我看官网上 scout推荐的比较多咧,你这个是scout/elasticsearch 包吗