Laravel + Elasticsearch 实现中文搜索的方法

2025-05-27 0 93

Laravel + Elasticsearch 实现中文搜索的方法

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。我们可以直接使用:

  1. dockercompose up d elasticsearch

如果需要安装插件,执行命令:

  1. dockercompose exec elasticsearch /usr/share/elasticsearch/bin/elasticsearchplugin install {pluginname}
  2. // 重启容器
  3. dockercompose 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

Laravel + Elasticsearch 实现中文搜索的方法

ElasticHQ

Laravel + Elasticsearch 实现中文搜索的方法

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

Laravel + Elasticsearch 实现中文搜索的方法

输入我们的 Elasticsearch Host,即可进入后台。

Laravel + Elasticsearch 实现中文搜索的方法

默认的创建了:

一个集群 cluster:laradock-cluster
一个节点 node:laradock-node
一个索引 index:.elastichq

IK 分词器安装

ElasticSearch 主要是用于自己 blog 或者公众号文章的搜索使用,所以需要选择一个中文分词器配合使用,这里刚开始推荐使用 IK 分词器,下面开始安装对应 ElasticSearch版本 (7.5.1) 一致的插件:

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

Laravel + Elasticsearch 实现中文搜索的方法

  1. // 安装插件
  2. dockercompose exec elasticsearch /usr/share/elasticsearch/bin/elasticsearchplugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v7.5.1/elasticsearch-analysis-ik-7.5.1.zip

Laravel + Elasticsearch 实现中文搜索的方法

注:可以将 zip 文件先下载回来,然后再安装,速度会快些。

检验分词效果

根据 Elasticsearch API 测试,分词的效果达到了:

  1. ~ curl X POST "http://your_host/_analyze?pretty" H 'Content-Type: application/json' d'
  2. {
  3. "analyzer": "ik_max_word",
  4. "text": "我是中国人"
  5. }
  6. '
  7. {
  8. "tokens" : [
  9. {
  10. "token" : "我",
  11. "start_offset" : 0,
  12. "end_offset" : 1,
  13. "type" : "CN_CHAR",
  14. "position" : 0
  15. },
  16. {
  17. "token" : "是",
  18. "start_offset" : 1,
  19. "end_offset" : 2,
  20. "type" : "CN_CHAR",
  21. "position" : 1
  22. },
  23. {
  24. "token" : "中国人",
  25. "start_offset" : 2,
  26. "end_offset" : 5,
  27. "type" : "CN_WORD",
  28. "position" : 2
  29. },
  30. {
  31. "token" : "中国",
  32. "start_offset" : 2,
  33. "end_offset" : 4,
  34. "type" : "CN_WORD",
  35. "position" : 3
  36. },
  37. {
  38. "token" : "国人",
  39. "start_offset" : 3,
  40. "end_offset" : 5,
  41. "type" : "CN_WORD",
  42. "position" : 4
  43. }
  44. ]
  45. }

结合 Laravel

虽然 Elasticsearch 官方提供了对应的 PHP 版本的插件,但我们还是希望和 Laravel 结合的更紧密些,所以这里选择和 Scout 结合使用,具体用到了 tamayo/laravel-scout-elastic 插件。

  1. composer require tamayo/laravelscoutelastic
  2. composer require laravel/scout
  3. php artisan vendor:publish

选择:Laravel\\Scout\\ScoutServiceProvider

Laravel + Elasticsearch 实现中文搜索的方法

修改驱动为 elasticsearch

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

创建索引

创建索引有几种方法,其中可以使用 Ela 可视化工具 ElasticHQ 直接创建。

Laravel + Elasticsearch 实现中文搜索的方法

Laravel + Elasticsearch 实现中文搜索的方法

接下来我们需要更新这个索引,补充 Mappings 这部分,可以用 Postman。

Laravel + Elasticsearch 实现中文搜索的方法

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

这里我们推荐使用 Artisan 命令行。

  1. php artisan make:command ESOpenCommand

根据官网提示,我们可以在 ESOpenCommand 上向 Elasticsearch 服务器发送 PUT 请求,这里借助 Elasticsearch 提供的 PHP 插件,在我们使用 tamayo/laravel-scout-elastic 插件时,已经安装了 Elasticsearch PHP 插件:

Laravel + Elasticsearch 实现中文搜索的方法

下面就可以借助插件,创建我们的 Index,直接看代码:

  1. public function handle()
  2. {
  3. $host = config('scout.elasticsearch.hosts');
  4. $index = config('scout.elasticsearch.index');
  5. $client = ClientBuilder::create()->setHosts($host)->build();
  6. if ($client->indices()->exists(['index' => $index])) {
  7. $this->warn("Index {$index} exists, deleting…");
  8. $client->indices()->delete(['index' => $index]);
  9. }
  10. $this->info("Creating index: {$index}");
  11. return $client->indices()->create([
  12. 'index' => $index,
  13. 'body' => [
  14. 'settings' => [
  15. 'number_of_shards' => 1,
  16. 'number_of_replicas' => 0
  17. ],
  18. 'mappings' => [
  19. '_source' => [
  20. 'enabled' => true
  21. ],
  22. 'properties' => [
  23. 'id' => [
  24. 'type' => 'long'
  25. ],
  26. 'title' => [
  27. 'type' => 'text',
  28. 'analyzer' => 'ik_max_word',
  29. 'search_analyzer' => 'ik_smart'
  30. ],
  31. 'subtitle' => [
  32. 'type' => 'text',
  33. 'analyzer' => 'ik_max_word',
  34. 'search_analyzer' => 'ik_smart'
  35. ],
  36. 'content' => [
  37. 'type' => 'text',
  38. 'analyzer' => 'ik_max_word',
  39. 'search_analyzer' => 'ik_smart'
  40. ]
  41. ],
  42. ]
  43. ]
  44. ]);
  45. }

Laravel + Elasticsearch 实现中文搜索的方法

好了,我们执行 Kibana 看到我们已经创建好了 Index:

Laravel + Elasticsearch 实现中文搜索的方法

注 Kibana 本地 Docker 安装:

后续会重点说明 Kibana 如何使用

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

为了验证 Index 是否可用,可以插入一条数据看看:

  1. curl XPOST your_host/coding01_open/_create/1 H 'Content-Type:application/json' d'
  2. {"content":"中韩渔警冲突调查:韩警平均每天扣1艘中国渔船"}

Laravel + Elasticsearch 实现中文搜索的方法

可以通过浏览器看看对应的数据:

Laravel + Elasticsearch 实现中文搜索的方法

有了 Index,下一步我们就可以结合 Laravel,导入、更新、查询等操作了。

Laravel Model 使用

Laravel 框架已经为我们推荐使用 Scout 全文搜索,我们只需要在 Article Model 加上官方所说的内容即可,很简单,推荐大家看 Scout 使用文档:https://learnku.com/docs/laravel/6.x/scout/5191,下面直接上代码:

  1. <?php
  2. namespace App;
  3. use App\\Tools\\Markdowner;
  4. use Illuminate\\Database\\Eloquent\\Model;
  5. use Illuminate\\Database\\Eloquent\\SoftDeletes;
  6. use Laravel\\Scout\\Searchable;
  7. class Article extends Model
  8. {
  9. use Searchable;
  10. protected $connection = 'blog';
  11. protected $table = 'articles';
  12. use SoftDeletes;
  13. /**
  14. * The attributes that should be mutated to dates.
  15. *
  16. * @var array
  17. */
  18. protected $dates = ['published_at', 'created_at', 'deleted_at'];
  19. /**
  20. * The attributes that are mass assignable.
  21. *
  22. * @var array
  23. */
  24. protected $fillable = [
  25. 'user_id',
  26. 'last_user_id',
  27. 'category_id',
  28. 'title',
  29. 'subtitle',
  30. 'slug',
  31. 'page_image',
  32. 'content',
  33. 'meta_description',
  34. 'is_draft',
  35. 'is_original',
  36. 'published_at',
  37. 'wechat_url',
  38. ];
  39. protected $casts = [
  40. 'content' => 'array'
  41. ];
  42. /**
  43. * Set the content attribute.
  44. *
  45. * @param $value
  46. */
  47. public function setContentAttribute($value)
  48. {
  49. $data = [
  50. 'raw' => $value,
  51. 'html' => (new Markdowner)->convertMarkdownToHtml($value)
  52. ];
  53. $this->attributes['content'] = json_encode($data);
  54. }
  55. /**
  56. * 获取模型的可搜索数据
  57. *
  58. * @return array
  59. */
  60. public function toSearchableArray()
  61. {
  62. $data = [
  63. 'id' => $this->id,
  64. 'title' => $this->title,
  65. 'subtitle' => $this->subtitle,
  66. 'content' => $this->content['html']
  67. ];
  68. return $data;
  69. }
  70. public function searchableAs()
  71. {
  72. return '_doc';
  73. }
  74. }

Scout 提供了 Artisan 命令 import 用来导入所有已存在的记录到搜索索引中。

  1. php artisan scout:import "App\\Article"

Laravel + Elasticsearch 实现中文搜索的方法

看看 Kibana,已存入 12 条数据,和数据库条数吻合。

Laravel + Elasticsearch 实现中文搜索的方法

有了数据,我们可以测试看看能不能查询到数据。

还是一样的,创建一个命令:

  1. class ElasearchCommand extends Command
  2. {
  3. /**
  4. * The name and signature of the console command.
  5. *
  6. * @var string
  7. */
  8. protected $signature = 'command:search {query}';
  9. /**
  10. * The console command description.
  11. *
  12. * @var string
  13. */
  14. protected $description = 'Command description';
  15. /**
  16. * Create a new command instance.
  17. *
  18. * @return void
  19. */
  20. public function __construct()
  21. {
  22. parent::__construct();
  23. }
  24. /**
  25. * Execute the console command.
  26. *
  27. * @return mixed
  28. */
  29. public function handle()
  30. {
  31. $article = Article::search($this->argument('query'))->first();
  32. $this->info($article->title);
  33. }
  34. }

Laravel + Elasticsearch 实现中文搜索的方法

这是我的 titles,我随便输入一个关键字:「清单」,看是否能搜到。

Laravel + Elasticsearch 实现中文搜索的方法

总结

整体完成了:

  • Elasticsearch 安装;
  • Elasticsearch IK 分词器插件安装;
  • Elasticsearch 可视化工具 ElasticHQ 和 Kibana 的安装和简单使用;
  • Scout 的使用;
  • Elasticsearch 和 Scout 结合使用。

接下来就要将更多的内容存入 Elasticsearch 中,为自己的 blog、公众号、自动化搜索等场景提供全文搜索。

参考

推荐一个命令行应用开发工具——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)

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

原文链接:https://segmentfault.com/a/1190000021670576

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Laravel + Elasticsearch 实现中文搜索的方法 https://www.kuaiidc.com/70583.html

相关文章

发表评论
暂无评论