濮阳杆衣贸易有限公司

主頁(yè) > 知識(shí)庫(kù) > Laravel + Elasticsearch 實(shí)現(xiàn)中文搜索的方法

Laravel + Elasticsearch 實(shí)現(xiàn)中文搜索的方法

熱門標(biāo)簽:山西回?fù)芡夂粝到y(tǒng) 騰訊外呼管理系統(tǒng) 岳陽(yáng)外呼型呼叫中心系統(tǒng)在哪里 百應(yīng)電話機(jī)器人服務(wù) 揚(yáng)州地圖標(biāo)注app 山西探意電話機(jī)器人 河南電銷卡外呼系統(tǒng)哪家強(qiáng) 青島語(yǔ)音外呼系統(tǒng)招商 昭通辦理400電話

Elasticsearch

Elasticsearch 是一個(gè)基于 Apache Lucene(TM) 的開源搜索引擎,無(wú)論在開源還是專有領(lǐng)域,Lucene可 以被認(rèn)為是迄今為止最先進(jìn)、性能最好的、功能最全的搜索引擎庫(kù)。

但是,Lucene 只是一個(gè)庫(kù)。想要發(fā)揮其強(qiáng)大的作用,你需使用 Java 并要將其集成到你的應(yīng)用中。Lucene 非常復(fù)雜,你需要深入的了解檢索相關(guān)知識(shí)來(lái)理解它是如何工作的。

Elasticsearch 也是使用 Java 編寫并使用 Lucene 來(lái)建立索引并實(shí)現(xiàn)搜索功能,但是它的目的是通過(guò)簡(jiǎn)單連貫的 RESTful API 讓全文搜索變得簡(jiǎn)單并隱藏 Lucene 的復(fù)雜性。

不過(guò),Elasticsearch 不僅僅是 Lucene 和全文搜索引擎,它還提供:

  • 分布式的實(shí)時(shí)文件存儲(chǔ),每個(gè)字段都被索引并可被搜索
  • 實(shí)時(shí)分析的分布式搜索引擎
  • 可以擴(kuò)展到上百臺(tái)服務(wù)器,處理PB級(jí)結(jié)構(gòu)化或非結(jié)構(gòu)化數(shù)據(jù)

而且,所有的這些功能被集成到一臺(tái)服務(wù)器,你的應(yīng)用可以通過(guò)簡(jiǎn)單的 RESTful API、各種語(yǔ)言的客戶端甚至命令行與之交互。上手 Elasticsearch 非常簡(jiǎn)單,它提供了許多合理的缺省值,并對(duì)初學(xué)者隱藏了復(fù)雜的搜索引擎理論。它開箱即用(安裝即可使用),只需很少的學(xué)習(xí)既可在生產(chǎn)環(huán)境中使用。

Elasticsearch 在 Apache 2 license 下許可使用,可以免費(fèi)下載、使用和修改。

ElasticSearch 安裝

在 Laradock 中已經(jīng)集成了 ElasticSearch。我們可以直接使用:

docker-compose up -d elasticsearch

如果需要安裝插件,執(zhí)行命令:

docker-compose exec elasticsearch /usr/share/elasticsearch/bin/elasticsearch-plugin install {plugin-name}

// 重啟容器
docker-compose restart elasticsearch

注:

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

由于我是 centos 7 環(huán)境,直接設(shè)置在系統(tǒng)設(shè)置:
sysctl -w vm.max_map_count=262144

默認(rèn)用戶名和密碼:「elastic」、「changeme」,端口號(hào):9200

ElasticHQ

ElasticHQ is an open source application that offers a simplified interface for managing and monitoring Elasticsearch clusters.

Management and Monitoring for Elasticsearch.

http://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,即可進(jìn)入后臺(tái)。

默認(rèn)的創(chuàng)建了:

一個(gè)集群 cluster:laradock-cluster
一個(gè)節(jié)點(diǎn) node:laradock-node
一個(gè)索引 index:.elastichq

IK 分詞器安裝

ElasticSearch 主要是用于自己 blog 或者公眾號(hào)文章的搜索使用,所以需要選擇一個(gè)中文分詞器配合使用,這里剛開始推薦使用 IK 分詞器,下面開始安裝對(duì)應(yīng) ElasticSearch版本 (7.5.1) 一致的插件:

https://github.com/medcl/elasticsearch-analysis-ik/releases

// 安裝插件
docker-compose exec elasticsearch /usr/share/elasticsearch/bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.5.1/elasticsearch-analysis-ik-7.5.1.zip

注:可以將 zip 文件先下載回來(lái),然后再安裝,速度會(huì)快些。

檢驗(yàn)分詞效果

根據(jù) Elasticsearch API 測(cè)試,分詞的效果達(dá)到了:

 ~ curl -X POST "http://your_host/_analyze?pretty" -H 'Content-Type: application/json' -d'
{
 "analyzer": "ik_max_word",
 "text":   "我是中國(guó)人"
}
'

{
 "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" : "中國(guó)人",
   "start_offset" : 2,
   "end_offset" : 5,
   "type" : "CN_WORD",
   "position" : 2
  },
  {
   "token" : "中國(guó)",
   "start_offset" : 2,
   "end_offset" : 4,
   "type" : "CN_WORD",
   "position" : 3
  },
  {
   "token" : "國(guó)人",
   "start_offset" : 3,
   "end_offset" : 5,
   "type" : "CN_WORD",
   "position" : 4
  }
 ]
}

結(jié)合 Laravel

雖然 Elasticsearch 官方提供了對(duì)應(yīng)的 PHP 版本的插件,但我們還是希望和 Laravel 結(jié)合的更緊密些,所以這里選擇和 Scout 結(jié)合使用,具體用到了 tamayo/laravel-scout-elastic 插件。

composer require tamayo/laravel-scout-elastic
 
composer require laravel/scout
 
php artisan vendor:publish

選擇:Laravel\Scout\ScoutServiceProvider

修改驅(qū)動(dòng)為 elasticsearch

'driver' => env('SCOUT_DRIVER', 'elasticsearch'),

創(chuàng)建索引

創(chuàng)建索引有幾種方法,其中可以使用 Ela 可視化工具 ElasticHQ 直接創(chuàng)建。

接下來(lái)我們需要更新這個(gè)索引,補(bǔ)充 Mappings 這部分,可以用 Postman。

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

這里我們推薦使用 Artisan 命令行。
php artisan make:command ESOpenCommand

根據(jù)官網(wǎng)提示,我們可以在 ESOpenCommand 上向 Elasticsearch 服務(wù)器發(fā)送 PUT 請(qǐng)求,這里借助 Elasticsearch 提供的 PHP 插件,在我們使用 tamayo/laravel-scout-elastic 插件時(shí),已經(jīng)安裝了 Elasticsearch PHP 插件:

下面就可以借助插件,創(chuàng)建我們的 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'
          ]
        ],
      ]
    ]
  ]);
}

好了,我們執(zhí)行 Kibana 看到我們已經(jīng)創(chuàng)建好了 Index:

注 Kibana 本地 Docker 安裝:

后續(xù)會(huì)重點(diǎn)說(shuō)明 Kibana 如何使用

docker run -d --name kibana -e ELASTICSEARCH_HOSTS=http://elasticsearch_host -p 5601:5601 -e SERVER_NAME=ki.test kibana:7.5.2

為了驗(yàn)證 Index 是否可用,可以插入一條數(shù)據(jù)看看:

curl -XPOST your_host/coding01_open/_create/1 -H 'Content-Type:application/json' -d'
{"content":"中韓漁警沖突調(diào)查:韓警平均每天扣1艘中國(guó)漁船"}

可以通過(guò)瀏覽器看看對(duì)應(yīng)的數(shù)據(jù):

有了 Index,下一步我們就可以結(jié)合 Laravel,導(dǎo)入、更新、查詢等操作了。

Laravel Model 使用

Laravel 框架已經(jīng)為我們推薦使用 Scout 全文搜索,我們只需要在 Article Model 加上官方所說(shuō)的內(nèi)容即可,很簡(jiǎn)單,推薦大家看 Scout 使用文檔:https://learnku.com/docs/laravel/6.x/scout/5191,下面直接上代碼:

?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);
  }

  /**
   * 獲取模型的可搜索數(shù)據(jù)
   *
   * @return 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 用來(lái)導(dǎo)入所有已存在的記錄到搜索索引中。

php artisan scout:import "App\Article"

看看 Kibana,已存入 12 條數(shù)據(jù),和數(shù)據(jù)庫(kù)條數(shù)吻合。

有了數(shù)據(jù),我們可以測(cè)試看看能不能查詢到數(shù)據(jù)。

還是一樣的,創(chuàng)建一個(gè)命令:

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 void
   */
  public function __construct()
  {
    parent::__construct();
  }

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

這是我的 titles,我隨便輸入一個(gè)關(guān)鍵字:「清單」,看是否能搜到。

總結(jié)

整體完成了:

  • Elasticsearch 安裝;
  • Elasticsearch IK 分詞器插件安裝;
  • Elasticsearch 可視化工具 ElasticHQ 和 Kibana 的安裝和簡(jiǎn)單使用;
  • Scout 的使用;
  • Elasticsearch 和 Scout 結(jié)合使用。

接下來(lái)就要將更多的內(nèi)容存入 Elasticsearch 中,為自己的 blog、公眾號(hào)、自動(dòng)化搜索等場(chǎng)景提供全文搜索。

參考

推薦一個(gè)命令行應(yīng)用開發(fā)工具——Laravel Zero

Artisan 命令行 https://learnku.com/docs/laravel/6.x/artisan/5158

Scout 全文搜索 https://learnku.com/docs/laravel/6.x/scout/5191

How to integrate Elasticsearch in your Laravel App – 2019 edition https://madewithlove.be/how-to-integrate-elasticsearch-in-your-laravel-app-2019-edition/

Kibana Guide https://www.elastic.co/guide/en/kibana/index.html

elasticsearch php-api [https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/index.html](https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/index.html)

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • Python操作Elasticsearch處理timeout超時(shí)
  • es(elasticsearch)整合SpringCloud(SpringBoot)搭建教程詳解
  • python中的Elasticsearch操作匯總
  • 使用postman操作ElasticSearch的方法

標(biāo)簽:銅川 湛江 婁底 黃南 鎮(zhèn)江 南陽(yáng) 宜賓 寶雞

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Laravel + Elasticsearch 實(shí)現(xiàn)中文搜索的方法》,本文關(guān)鍵詞  Laravel,Elasticsearch,實(shí)現(xiàn),中文,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《Laravel + Elasticsearch 實(shí)現(xiàn)中文搜索的方法》相關(guān)的同類信息!
  • 本頁(yè)收集關(guān)于Laravel + Elasticsearch 實(shí)現(xiàn)中文搜索的方法的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    临夏市| 达州市| 抚宁县| 昭觉县| 吐鲁番市| 林口县| 江安县| 盘锦市| 霍城县| 壤塘县| 上栗县| 顺义区| 丽江市| 莱州市| 泸水县| 长顺县| 如皋市| 宁海县| 汶川县| 萨嘎县| 南通市| 库尔勒市| 东明县| 黄山市| 长丰县| 丹江口市| 永春县| 西乡县| 庆阳市| 宁乡县| 安图县| 化德县| 仪陇县| 漳平市| 清徐县| 青川县| 建平县| 大宁县| 乡城县| 蒲城县| 若尔盖县|