1、要使用elasticsearch首先需要Java SE环境,在cmd中输入java -v检查版本,没有的话可以去此网站下载 Java Downloads | Oracle ,现在常用的是8.0版本 然后需要配置环境变量
2、官网下载elasticsearch 任何版本都可
3、elasticsearch-head可视化工具 可以去github下载 然后去目录执行npm命令安装 (可无)
4、kibana工具(可无)
5、使用elasticsearch首先需要启动,环境变量配好之后cmd输入elasticsearch -d 启动
6、框架内使用执行composer require elasticsearch/elasticsearch 安装扩展
7、创建索引 使用了ik分词器
// 创建索引
public function create(){
//简单索引
$client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
$params = [
'index' => 'movie',
'body' => [
'settings' => [
'number_of_shards' => 3,
'number_of_replicas' => 2
],
'mappings' => [
'_source' => [
'enabled' => true
],
'properties' => [
'name' => [
'type' => 'text',
"analyzer" => "ik_max_word",
"search_analyzer" => "ik_max_word"
],
'desc' => [
'type' => 'text',
"analyzer" => "ik_max_word",
"search_analyzer" => "ik_max_word"
]
]
]
]
];
// Create the index with mappings and settings now
$response = $client->indices()->create($params);
return $response;
}
8、更新/添加文档
// 添加数据
public function add(){
$data = Movie::select();
$data = (new Collection($data))->toArray();
$client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
foreach ($data as $v){
$params = [
'index' => 'movie',
'type' => '_doc',
//'id' => '1',
'body' => $v
];
$response = $client->index($params);
}
return $response;
}
9、搜索 使用高亮
// 搜索数据
public function search()
{
$key = input('key');
$data = \app\admin\model\Goods::select();
$client = ClientBuilder::create()->setHosts(['127.0.0.1:9200'])->build();
$params = [
'index' => 'goods',
//'type' => '_doc',
'body' => [
'query' => [
'bool' => [
'should' => [
[
'match' => [
'address' => $keyword,
]
],
[
'match' => [
'number' => $keyword,
]
]
]
]
],
'highlight' => [
'pre_tags' => ["<b style='color: red'>"],
'post_tags' => ["</b>"],
'fields' => [
"name" => new \stdClass()
]
]
]
];
$response = $client->search($params);
$data = $response['hits']['hits'];
$res = [];
foreach ($data as $v) {
if (!empty($v['highlight']['address'][0])) {
$v['_source']['address'] = $v['highlight']['address'][0];
}
if (!empty($v['highlight']['number'][0])) {
$v['_source']['number'] = $v['highlight']['number'][0];
}
array_push($res, $v['_source']);
}
return ['code' => 200, 'msg' => '搜索成功', 'data' => $res];
}