1. 程式人生 > >laravel-elasticsearch 配置以及運用

laravel-elasticsearch 配置以及運用

參考文件:

  搭建elasticsearch伺服器

  laravel-elastic

  elasticsearch官方文件

 

執行環境:

  php7

  laravel框架 5.5

 

呼叫:

//執行命令,載入laravel-elastic驅動 
# composer require babenkoivan/scout-elasticsearch-driver

//修改laravel配置檔案(如果 框架版本小於5.4)
//在config/app.php最後增加

'providers' => [
    Laravel\Scout\ScoutServiceProvider::class,
    ScoutElastic\ScoutElasticServiceProvider::class,
]


//執行命令,釋出(命令生成elastic配置檔案)
# php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"
# php artisan vendor:publish --provider="ScoutElastic\ScoutElasticServiceProvider"

//修改elastic配置檔案 config/sout.php
//(兩處地方需要改)
'driver' => env('SCOUT_DRIVER', 'elastic'),

'elastic' => [
    'index' => env('ELASTICSEARCH_INDEX', 'my_elastic'),
        'hosts' => [
        env('ELASTICSEARCH_HOST', 'http://(伺服器elastic的ip):9200'),
    ],
],


//修改 config/scout_elastic.php
return [
    'client' => [
        'hosts' => [
            env('SCOUT_ELASTIC_HOST', '/(伺服器elastic的ip):9200')
        ]
    ],
    'update_mapping' => env('SCOUT_ELASTIC_UPDATE_MAPPING', true),
    'indexer' => env('SCOUT_ELASTIC_INDEXER', 'single'),
    'document_refresh' => env('SCOUT_ELASTIC_DOCUMENT_REFRESH')
];

//修改環境配置檔案 根目錄下的 .env 檔案,增加
SCOUT_DRIVER=elastic
SCOUT_ELASTIC_HOST=伺服器elastic的ip:9200
ELASTICSEARCH_HOST=http://伺服器elastic的ip:9200
ELASTICSEARCH_INDEX=my_elastic

!!!/* 注意了 上面配置的 my_elastic 相當於資料庫的名字 */!!!

//索引就是資料庫名嘛
//生成索引檔案  MyElasticIndexConfigurator 為 資料庫名字IndexConfigurator
php artisan make:index-configurator MyElasticIndexConfigurator



//其中找到 檔案 MyElasticIndexConfigurator

protected $name = 'my_index';    //資料庫名字
protected $settings = [
    'refresh_interval' => '5s',
    'number_of_shards' => 1,
    'number_of_replicas' => 0,
];
protected $defaultMapping = [
];



//新增 搜尋的規則資料夾     App\Search\Rules
//新增 搜尋的資料表文件夾   App\Search\Models

//向伺服器請求,新增索引(新增資料庫意思)
//其中MyElasticIndexConfigurator 為 剛剛上面建立的索引檔案,注意名稱空間App
php artisan elastic:create-index App\\MyElasticIndexConfigurator



//生成一個elasticsearch專用的 Model,如 使用者表文件
//注意--index選項 意思是,把UserModel這個表 放到 索引 --index指定的檔案,即 資料表存放到資料庫下
//執行以下命令
php artisan make:searchable-model Search\\Models\\UserModel --index-configurator=MyIndexConfigurator

//開啟上面建立的 UserModel
//看下指定的索引(資料庫)是否正確
protected $indexConfigurator = \App\LogisticsArticleIndexConfigurator::class;
//指定資料庫的表名
protected $table = 'users';


//UserModel完整如下
//其中規則檔案生成 下一步新增
namespace App\Search\Models;
use App\Search\Rules\UserRule;
use ScoutElastic\Searchable;
use Illuminate\Database\Eloquent\Model;
class UserModel extends Model
{
    use Searchable;
    //表名
    protected $table = 'users';

    protected $indexConfigurator = \App\MyElasticIndexConfigurator::class;
    /**
    * 索引型別 類似 mysql的表
    * @return string
    */
    public function searchableAs()
    {
        return 'users';
    }

    //搜尋規則,指定規則檔案
    protected $searchRules = [
        UserRule::class
    ];

    protected $mapping = [
        '_source' => [
            'enabled' => true
        ],
        'properties' => [ //⽂文件型別設定(相當於mysql的資料型別)
            'id' => [
                'type' => 'integer', // //型別 string、integer、float、double、boolean、date,text,keyword
                //'index'=> 'not_analyzed',//索引是否精確值 analyzed not_analyzed
            ],
            'content' => [
                'type' => 'text', // 欄位型別為全⽂文檢索,如果需要關鍵字,則修改為keyword,注意keyword欄位為整體查詢,不不能作為模糊搜尋
                "analyzer" => "ik_max_word",
                "search_analyzer" => "ik_max_word",
             ]
        ]
    ];

    //當查詢的時候,預設返回的內容
    public function toSearchableArray()
    {
        return [
            'id'=>$this->id,
            'content'=>$this->content
        ];
        //return array_only($this->toArray(), ['id', 'name', 'email']);
    }
}

//執行命令 搜尋規則檔案新增
# php artisan make:search-rule App\\Search\\Rules\\UserRule
//開啟建立的規則檔案,內容如下
//規則怎麼配置,看看參考文件的 laravel-elastic有說明
public function buildHighlightPayload()
{
    return [
        'fields' => [
        // 'title' => [
        // 'type' => 'plain'
        // ],
            'content' => [
                'type' => 'plain'
            ]
        ]
    ];
}
/**
* @inheritdoc
*/
public function buildQueryPayload()
{
    return [
        'must' => [
            'match' => [
            // 'title' => $this->builder->query,
            'content' => $this->builder->query
            ]
        ]
    ];
}


//下一步,把userModel對應的資料表資料 對映(插入到)elastic伺服器上
//執行命令
//userModel更改了,則需要更新下
# php artisan elastic:update-mapping App\\Search\\Models\\UserModel
//把資料庫的資料 插入對映到 elastic伺服器上
# php artisan scout:import "App\Search\Models\UserModel"

//說明:如果 UserModel的 properties 既欄位的屬性型別更改了,那麼 執行上面的兩個命令將會失敗
//因此需要 先執行刪除索引,建立索引 這兩個命令,重複上面的步驟。


//最後控制器 呼叫elasticearch的model進行查詢
\App\Search\Models\UserModel::search('查詢的字眼')->get();