当前位置: 移动技术网 > IT编程>开发语言>PHP > Laravel + Elasticsearch 实现中文搜索的方法

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

2020年05月10日  | 移动技术网IT编程  | 我要评论

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-compose up -d elasticsearch

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

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 环境,直接设置在系统设置:
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.

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,即可进入后台。

默认的创建了:

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

ik 分词器安装

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

// 安装插件
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 文件先下载回来,然后再安装,速度会快些。

检验分词效果

根据 elasticsearch api 测试,分词的效果达到了:

 ~ curl -x post "http://www.lhsxpumps.com/_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
 
php artisan vendor:publish

选择:laravel\scout\scoutserviceprovider

修改驱动为 elasticsearch

'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 安装:

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

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

为了验证 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 使用文档:,下面直接上代码:

<?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 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 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,我随便输入一个关键字:「清单」,看是否能搜到。

总结

整体完成了:

  • elasticsearch 安装;
  • elasticsearch ik 分词器插件安装;
  • elasticsearch 可视化工具 elastichq 和 kibana 的安装和简单使用;
  • scout 的使用;
  • elasticsearch 和 scout 结合使用。

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

参考

推荐一个命令行应用开发工具——laravel zero

artisan 命令行

scout 全文搜索

how to integrate elasticsearch in your laravel app – 2019 edition

kibana guide

elasticsearch php-api [)

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网