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

2020-02-02 14:01:33于海丽

为了验证 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 使用文档:https://learnku.com/docs/laravel/6.x/scout/5191,下面直接上代码:

<?php

namespace App;

use AppToolsMarkdowner;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentSoftDeletes;
use LaravelScoutSearchable;

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 "AppArticle"

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

相关文章 大家在看