当前位置: 移动技术网 > IT编程>开发语言>PHP > Laravel使用scout集成elasticsearch做全文搜索的实现方法

Laravel使用scout集成elasticsearch做全文搜索的实现方法

2018年12月06日  | 移动技术网IT编程  | 我要评论

本文介绍了laravel使用scout集成elasticsearch做全文搜索的实现方法,分享给大家,具体如下:

安装需要的组件

composer require tamayo/laravel-scout-elastic
composer require laravel/scout 

如果composer require laravel/scout 出现报错

using version ^6.1 for laravel/scout
./composer.json has been updated
loading composer repositories with package information
updating dependencies (including require-dev)
your requirements could not be resolved to an installable set of packages.

 problem 1
  - tamayo/laravel-scout-elastic 4.0.0 requires laravel/scout ^5.0 -> satisfiable by laravel/scout[5.0.x-dev].
  - tamayo/laravel-scout-elastic 4.0.0 requires laravel/scout ^5.0 -> satisfiable by laravel/scout[5.0.x-dev].
  - tamayo/laravel-scout-elastic 4.0.0 requires laravel/scout ^5.0 -> satisfiable by laravel/scout[5.0.x-dev].
  - conclusion: don't install laravel/scout 5.0.x-dev
  - installation request for tamayo/laravel-scout-elastic ^4.0 -> satisfiable by tamayo/laravel-scout-elastic[4.0.0].


installation failed, reverting ./composer.json to its original content.

那么使用命令

composer require laravel/scout ^5.0

修改一下配置文件(config/app.php),添加如下两个provider

'providers' => [ 
    //es search 加上以下内容 
    laravel\scout\scoutserviceprovider::class, 
    scoutengines\elasticsearch\elasticsearchprovider::class, 
]

添加完成,执行命令,生成config文件

php artisan vendor:publish --provider="laravel\scout\scoutserviceprovider"

修改config/scout.php

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

  'elasticsearch' => [
    'index' => env('elasticsearch_index', '你的index名字'),
    'hosts' => [
      env('elasticsearch_host', ''),
    ],
  ],

在.env 配置es的 账号:密码@连接

elasticsearch_host=elastic:密码@你的域名.com:9200

创建一个生成mapping的命令行文件,到 app/console/commands

<?php
namespace app\console\commands;
use guzzlehttp\client;
use illuminate\console\command;

class esinit extends command {

  protected $signature = 'es:init';

  protected $description = 'init laravel es for news';

  public function __construct() { parent::__construct(); }

  public function handle() { //创建template
    $client = new client(['auth'=>['elastic', 'wangcai5388']]);
    $url = config('scout.elasticsearch.hosts')[0] . '/_template/news';
    $params = [
      'json' => [
        'template' => config('scout.elasticsearch.index'),
        'settings' => [
          'number_of_shards' => 5
        ],
        'mappings' => [
          '_default_' => [
            'dynamic_templates' => [
              [
                'strings' => [
                  'match_mapping_type' => 'string',
                  'mapping' => [
                    'type' => 'text',
                    'analyzer' => 'ik_smart',
                    'ignore_above' => 256,
                    'fields' => [
                      'keyword' => [
                        'type' => 'keyword'
                      ]
                    ]
                  ]
                ]
              ]
            ]
          ]
        ]
      ]
    ];
    $client->put($url, $params);

    // 创建index
    $url = config('scout.elasticsearch.hosts')[0] . '/' . config('scout.elasticsearch.index');

    $params = [
      'json' => [
        'settings' => [
          'refresh_interval' => '5s',
          'number_of_shards' => 5,
          'number_of_replicas' => 0
        ],
        'mappings' => [
          '_default_' => [
            '_all' => [
              'enabled' => false
            ]
          ]
        ]
      ]
    ];
    $client->put($url, $params);

  }
}

在kernel中注册这个命令

<?php

namespace app\console;

use app\console\commands\esinit;
use illuminate\console\scheduling\schedule;
use illuminate\foundation\console\kernel as consolekernel;

class kernel extends consolekernel
{
  /**
   * the artisan commands provided by your application.
   *
   * @var array
   */
  protected $commands = [
    esinit::class
  ];

执行这个命令 生成 mapping

php artisan es:init

修改model支持 全文搜索

<?php
namespace app\activitynews\model;

use app\model\category;
use app\star\model\star;
use illuminate\database\eloquent\model;
use laravel\scout\searchable;


class activitynews extends model
{
  use searchable;

  protected $table = 'activity_news';
  protected $fillable = [
    'type_id',
    'category_id',
    'title',
    'sub_title',
    'thumb',
    'intro',
    'star_id',
    'start_at',
    'end_at',
    'content',
    'video_url',
    'status',
    'is_open',
    'is_top',
    'rank',
  ];

  public function star()
  {
    return $this->hasone(star::class, 'id', 'star_id');
  }

  public function category()
  {
    return $this->hasone(category::class, 'id', 'category_id');
  }

  public static function getactivityidbyname($name)
  {
    return self::select('id')
      ->where([
        ['status', '=', 1],
        ['type_id', '=', 2],
        ['title', 'like', '%' . $name . '%']
      ])->get()->pluck('id');
  }

}

导入全文索引信息

php artisan scout:import "app\activitynews\model\activitynews"

测试简单的全文索引

php artisan tinker

>>> app\activitynews\model\activitynews::search('略懂皮毛')->get();

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

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

相关文章:

验证码:
移动技术网