Elasticsearch在Laravel中的實踐

程式設計師的貓發表於2021-02-23

Elasticsearch

Elasticsearch 是一個基於 Apache Lucene (TM) 的開源搜尋引擎,無論在開源還是專有領域,Lucene 可 以被認為是迄今為止最先進、效能最好的、功能最全的搜尋引擎庫。但是,Lucene 只是一個庫。想要發揮其強大的作用,你需使用 Java 並要將其整合到你的應用中。Lucene 非常複雜,你需要深入的瞭解檢索相關知識來理解它是如何工作的。

Elasticsearch 也是使用 Java 編寫並使用 Lucene 來建立索引並實現搜尋功能,但是它的目的是透過簡單連貫的 RESTful API 讓全文搜尋變得簡單並隱藏 Lucene 的複雜性。
不過,Elasticsearch 不僅僅是 Lucene 和全文搜尋引擎,它還提供:

分散式的實時檔案儲存,每個欄位都被索引並可被搜尋
實時分析的分散式搜尋引擎
可以擴充套件到上百臺伺服器,處理 PB 級結構化或非結構化資料
而且,所有的這些功能被整合到一臺伺服器,你的應用可以透過簡單的 RESTful API、各種語言的客戶端甚至命令列與之互動。上手 Elasticsearch 非常簡單,它提供了許多合理的預設值,並對初學者隱藏了複雜的搜尋引擎理論。它開箱即用(安裝即可使用),只需很少的學習既可在生產環境中使用。

Elasticsearch 在 Apache 2 License 下許可使用,可以免費下載、使用和修改。

ElasticSearch 安裝

在 Laradock 中已經整合了 ElasticSearch。我們可以直接使用:

# 啟動
docker run -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" --name=elasticsearch docker.elastic.co/elasticsearch/elasticsearch:7.11.1

# 如果需要安裝外掛,執行命令:
docker exec -it elasticsearch  /bin/bash

/usr/share/elasticsearch/bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.11.1/elasticsearch-analysis-ik-7.11.1.zip

# 重啟容器
docker restart elasticsearch

注:The vm.max_map_count kernel setting must be set to at least 262144 for production use.

由於我是 centos 7 環境,直接設定在系統設定:

sysctl -w vm.max_map_count=262144

預設使用者名稱和密碼:「elastic」、「changeme」,埠號:9200

ElasticHQ

ElasticHQ is an open source application that offers a simplified interface for managing and monitoring Elasticsearch clusters.
Management and Monitoring for Elasticsearch.
www.elastichq.org/

Real-Time Monitoring
Full Cluster Management
Full Cluster Monitoring
Elasticsearch Version Agnostic
Easy Install - Always On
Works with X-Pack

輸入我們的 Elasticsearch Host,即可進入後臺。

預設的建立了:

一個叢集 Cluster:laradock-cluster
一個節點 Node:laradock-node
一個索引 Index:.elastichq

IK 分詞器安裝

ElasticSearch 主要是用於自己 Blog 或者公眾號文章的搜尋使用,所以需要選擇一箇中文分詞器配合使用,這裡剛開始推薦使用 IK 分詞器,下面開始安裝對應 ElasticSearch 版本 (7.5.1) 一致的外掛:
Elasticsearch-analysis-ik

// 安裝外掛
docker exec -it elasticsearch  /bin/bash

/usr/share/elasticsearch/bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.11.1/elasticsearch-analysis-ik-7.11.1.zip

注:可以將 zip 檔案先下載回來,然後再安裝,速度會快些。

檢驗分詞效果

根據 Elasticsearch API 測試,分詞的效果達到了:

curl -X POST "http://your_host/_analyze?pretty" -H 'Content-Type: application/json' -d'
{
  "analyzer": "ik_max_word",
  "text":     "我是中國人"
}
'
{
  "tokens" : [
    {
      "token" : "我",
      "start_offset" : 0,
      "end_offset" : 1,
      "type" : "CN_CHAR",
      "position" : 0
    },
    {
      "token" : "是",
      "start_offset" : 1,
      "end_offset" : 2,
      "type" : "CN_CHAR",
      "position" : 1
    },
    {
      "token" : "中國人",
      "start_offset" : 2,
      "end_offset" : 5,
      "type" : "CN_WORD",
      "position" : 2
    },
    {
      "token" : "中國",
      "start_offset" : 2,
      "end_offset" : 4,
      "type" : "CN_WORD",
      "position" : 3
    },
    {
      "token" : "國人",
      "start_offset" : 3,
      "end_offset" : 5,
      "type" : "CN_WORD",
      "position" : 4
    }
  ]
}

結合 Laravel

雖然 Elasticsearch 官方提供了對應的 PHP 版本的外掛,但我們還是希望和 Laravel 結合的更緊密些,所以這裡選擇和 Scout 結合使用,具體用到了 tamayo/laravel-scout-elastic 外掛。

composer require tamayo/laravel-scout-elastic

composer require laravel/scout
# 釋出 Scout 的配置檔案
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

#修改驅動為 elasticsearch:
# config/scout.php
'driver' => env('SCOUT_DRIVER', 'elasticsearch')

建立索引

建立索引有幾種方法,其中可以使用 Ela 視覺化工具 ElasticHQ 直接建立。

接下來我們需要更新這個索引,補充 Mappings 這部分,可以用 Postman。

另一種方法是用 Laravel 自帶的 Artisan 命令列功能。

這裡我們推薦使用 Artisan 命令列。

php artisan make:command ESOpenCommand

根據官網提示,我們可以在 ESOpenCommand 上向 Elasticsearch 伺服器傳送 PUT 請求,這裡藉助 Elasticsearch 提供的 PHP 外掛,在我們使用 tamayo/laravel-scout-elastic 外掛時,已經安裝了 Elasticsearch PHP 外掛:

下面就可以藉助外掛,建立我們的 Index,直接看程式碼:

public function handle()
    {
    $host = config('scout.elasticsearch.hosts');
    $index = config('scout.elasticsearch.index');
    $client = ClientBuilder::create()->setHosts($host)->build();

    if ($client->indices()->exists(['index' => $index])) {
        $this->warn("Index {$index} exists, deleting...");
        $client->indices()->delete(['index' => $index]);
    }

    $this->info("Creating index: {$index}");

    return $client->indices()->create([
        'index' => $index,
        'body' => [
            'settings' => [
                'number_of_shards' => 1,
                'number_of_replicas' => 0
            ],
            'mappings' => [
                '_source' => [
                    'enabled' => true
                ],
                'properties' => [
                    'id' => [
                        'type' => 'long'
                    ],
                    'title' => [
                        'type' => 'text',
                        'analyzer' => 'ik_max_word',
                        'search_analyzer' => 'ik_smart'
                    ],
                    'subtitle' => [
                        'type' => 'text',
                        'analyzer' => 'ik_max_word',
                        'search_analyzer' => 'ik_smart'
                    ],
                    'content' => [
                        'type' => 'text',
                        'analyzer' => 'ik_max_word',
                        'search_analyzer' => 'ik_smart'
                    ]
                ],
            ]
        ]
    ]);
}

好了,我們執行 Kibana 看到我們已經建立好了 Index:

注 Kibana 本地 Docker 安裝:

docker pull docker.elastic.co/kibana/kibana:7.11.1
docker run -d --name kibana  --link elasticsearch -e ELASTICSEARCH_HOSTS=http://elasticsearch:9200 -p 5601:5601 docker.elastic.co/kibana/kibana:7.11.1

為了驗證 Index 是否可用,可以插入一條資料看看:

curl -XPOST your_host/coding01_open/_create/1 -H 'Content-Type:application/json' -d '{"content":"中韓漁警衝突調查:韓警平均每天扣1艘中國漁船"}

可以透過瀏覽器看看對應的資料:

有了 Index,下一步我們就可以結合 Laravel,匯入、更新、查詢等操作了。

Laravel Model 使用

Laravel 框架已經為我們推薦使用 Scout 全文搜尋,我們只需要在 Article Model 加上官方所說的內容即可,很簡單,推薦大家看 Scout 使用文件:Scout 全文搜尋《Laravel 6 中文文件》,下面直接上程式碼:

<?php

namespace App;

use App\Tools\Markdowner;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Scout\Searchable;

class Article extends Model
{
    use Searchable;

    protected $connection = 'blog';
    protected $table = 'articles';
    use SoftDeletes;

    /**
     * The attributes that should be mutated to dates.
     *
     * @var array
     */
    protected $dates = ['published_at', 'created_at', 'deleted_at'];

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'user_id',
        'last_user_id',
        'category_id',
        'title',
        'subtitle',
        'slug',
        'page_image',
        'content',
        'meta_description',
        'is_draft',
        'is_original',
        'published_at',
        'wechat_url',
    ];

    protected $casts = [
        'content' => 'array'
    ];

    /**
     * Set the content attribute.
     *
     * @param $value
     */
    public function setContentAttribute($value)
    {
        $data = [
            'raw'  => $value,
            'html' => (new Markdowner)->convertMarkdownToHtml($value)
        ];

        $this->attributes['content'] = json_encode($data);
    }

    /**
     * 獲取模型的可搜尋資料
     *
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) array
     */
    public function toSearchableArray()
    {
        $data = [
            'id' => $this->id,
            'title' => $this->title,
            'subtitle' => $this->subtitle,
            'content' => $this->content['html']
        ];

        return $data;
    }

    public function searchableAs()
    {
        return '_doc';
    }
}

Scout 提供了 Artisan 命令 import 用來匯入所有已存在的記錄到搜尋索引中。

php artisan scout:import "App\Article"

看看 Kibana,已存入 12 條資料,和資料庫條數吻合。

有了資料,我們可以測試看看能不能查詢到資料。

還是一樣的,建立一個命令:

class ElasearchCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:search {query}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * [[@return](https://learnku.com/users/31554)](https://learnku.com/users/31554) mixed
     */
    public function handle()
    {
        $article = Article::search($this->argument('query'))->first();
        $this->info($article->title);
    }
}

這是我的 titles,我隨便輸入一個關鍵字: 「清單」 看是否能搜到。

總結

整體完成了:

  • Elasticsearch 安裝;
  • Elasticsearch IK 分詞器外掛安裝;
  • Elasticsearch 視覺化工具 ElasticHQ 和 Kibana 的安裝和簡單使用;
  • Scout 的使用;
  • Elasticsearch 和 Scout 結合使用。

接下來就要將更多的內容存入 Elasticsearch 中,為自己的 Blog、公眾號、自動化搜尋等場景提供全文搜尋。

原文作者:coding01
轉自連結:部落格:Laravel + Elasticsearch 實現中文搜尋
版權宣告:著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請保留以上作者資訊和原文連結。

本作品採用《CC 協議》,轉載必須註明作者和本文連結
你還差得遠吶!

相關文章