Elasticsearch在Laravel中的实践

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 协议》,转载必须注明作者和本文链接
你还差得远呐!
本帖由系统于 2年前 自动加精
讨论数量: 2
pndx

Mark

2年前 评论

very good

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!