Laravel 通过 Elasticsearch 进行全文搜索

1,056 阅读1分钟

#1 ubuntu 18.04上安装Elasticsearch7.x

#1 check java-version
java -version
#2 install java-8-jdk
sudo apt install openjdk-8-jdk

#3 installing the apt-transport-https
sudo apt install apt-transport-https
#4 import GPG-Key
wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -
#5 add the Elasticsearch repository to the system by issuing
sudo sh -c 'echo "deb https://artifacts.elastic.co/packages/7.x/apt stable main" > /etc/apt/sources.list.d/elastic-7.x.list'
#6
sudo apt update
#7
sudo apt install elasticsearch
#8
sudo systemctl enable elasticsearch.service
sudo systemctl start elasticsearch.service
#9
curl -X GET "localhost:9200/"
# 在 https://www.elastic.co/cn/downloads/elasticsearch 下载deb
# 将deb拷贝到云主机
# 安装
sudo dpkg -i elasticsearch-7.8.0-amd64.deb
# 修改配置,令Elasticsearch只能本机访问
sudo vi /etc/elasticsearch/elasticsearch.yml
# network.host: localhost
sudo systemctl enable elasticsearch && sudo systemctl restart elasticsearch
#1 出现错误排查
cd /usr/share/elasticsearch/bin
#2 运行
./elasticsearch

##### homestead 一定要用下面的命令启动
systemctl start elasticsearch

#3 可有可无
sudo chown -R root:elasticsearch /etc/default/elasticsearch
#查看进程
ps aux | grep elasticsearch

####卸载
#step1 删除先前版本的ElasticSearch
sudo apt-get --purge autoremove elasticsearch
#step2 删除ElasticSearch目录
sudo rm -rf /var/lib/elasticsearch/
sudo rm -rf /etc/elasticsearch

#2 安装分词插件

/usr/share/elasticsearch/bin$ sudo ./elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.8.0/elasticsearch-analysis-ik-7.8.0.zip

#3 安装 Scout 扩展

# 安装 Scout  Laravel版本是5.7,只能安装v7的版本
composer require laravel/scout:"^7.0"
$ # 发布配置文件
$ php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

#4 安装babenkoivan/scout-elasticsearch-driver

## php7.2 会自动安装最高版本,babenkoivan/scout-elasticsearch-driver 只支持最高7.3
sudo composer require elasticsearch/elasticsearch:"7.3.*"
##
sudo composer require babenkoivan/scout-elasticsearch-driver

#5 常用命令

## 创建索引
php artisan elastic:create-index "App\Search\Indexes\HotelsIndexConfigurator"
## 更新索引
php artisan elastic:update-index "App\Search\Indexes\HotelsIndexConfigurator"
## 更新mapping
php artisan elastic:update-mapping "App\Models\Hotel\Hotel"

## 导入模型数据到索引中
php artisan scout:import "App\Models\Hotel\Hotel"
## 清除模型数据
php artisan scout:flush "App\Models\Hotel\Hotel"

## 查看索引是否创建
curl http://127.0.0.1:9200/_cat/indices

## 查看索引内容
curl http://127.0.0.1:9200/hotel_docs/_search?pretty=true

## 查看所有索引
curl http://127.0.0.1:9200/_cat/indices?v

## 查看mapping
curl http://127.0.0.1:9200/hotel_docs/_mapping?pretty=true