Laravel 下 Elasticsearch 使用

安装scout

composer require laravel/scout
在config/app.php 的 providers 数组中添加
Laravel\Scout\ScoutServiceProvider::class
执行命令
php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider

安装laravel-scout-elastic

composer安装
composer require tamayo/laravel-scout-elastic
在config/app.php 的 providers 数组中添加
ScoutEngines\Elasticsearch\ElasticsearchProvider::class
修改scout.php文件:

  'driver' => env('SCOUT_DRIVER', 'elasticsearch'),
     在最后添加
            //配置elasticsearch引擎
        'elasticsearch' => [
            'index' => env('ELASTICSEARCH_INDEX', 'laravel'),//laravel就是索引的名字,可以随便起
            'hosts' => [
                env('ELASTICSEARCH_HOST', 'http://127.0.0.1:9200'),
            ],
        ]

可能composer时可能会报错,是版本太高,实现降权(降低版本就好)【 composer require laravel/scout ^5.0.3】

创建命令

执行命令 php artisan make:command 命令的名
php artisan make:command ESinit
会在 app\Console\Commands\目录下创建 ESinit.php
class ESinit extends Command

{
    /**
     * The name and signature of the console command.
     * 这是命令的名字
     * @var string
     */
    //运行命令的名称
    protected $signature = 'es:init';
/**
     * The console command description.
     * 命令的描述
     * @var string
     */
    //protected $description = 'Command description';
    protected $description = 'init laravel es for post';

    /**
     * Create a new command instance.
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 在这里写要写的东西
     * Execute the console command.
     * @return mixed
     */
    public function handle()
    {
        //coding,待会儿我们要在这里写代码
    }
}

在 app\Console\Kernel.php 里写

    protected $commands = [
            \App\Console\Commands\ESinit::class
        ];
composer require guzzlehttp/guzzle 

安装guzzlehttp/guzzle成功后,在ESinit.php里的handle()方法里写

//创建template
$client = new Client(); //这里的Clinet()是你vendor下的GuzzleHttp下的Client文件
$url = config('scout.elasticsearch.hosts')[0].'/inssa';   //这里写logstash配置中index参数
$client->delete($url);//确定没有这个url

/*
 * 这个模板作用于我要做用的索引
 * */
$param = [
    'json'=>[
        /*
         * 这句是取在scout.php(scout是驱动)里我们配置好elasticsearch引擎的
         * index项。
         * PS:其实都是取数组项,scout本身就是return一个数组,
         * scout.elasticsearch.index就是取
         * scout[elasticsearch][index]
         * */
        'template'=>config('scout.elasticsearch.index'),
        'mappings'=>[
            '_default_'=>[
                'dynamic_templates'=>[
                    [
                        'string'=>[
                            'match_mapping_type'=>'string',//传进来的是string
                            'mapping'=>[
                                'type'=>'text',//把传进来的string按text(文本)处理
                                'analyzer'=>'ik_smart',//用ik_smart进行解析(ik是专门解析中的插件)
                                'fields'=>[
                                    'keyword'=>[
                                        'type'=>'keyword'
                                    ]
                                ]
                            ]
                        ]
                    ]
                ]
            ]
        ],
    ],
];
$client->put($url,$param);

$this->info('============create template success============');

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

$param = [
    'json'=>[
        'settings'=>[
            'refresh_interval'=>'5s',
            'number_of_shards'=>1,
            'number_of_replicas'=>0,
        ],

        'mappings'=>[
            '_default_'=>[
                '_all'=>[
                    'enabled'=>false
                ]
            ]
        ]
    ]
];

$client->put($url,$param);
$this->info('============create index success============');

首先得启动Es

执行 php artisan es:init命令,出现下边的信息就说明执行成功了

    ============create template success============ 
    ============create index success==============

修改你要搜索的model,以Admin为eg:

引用命名空间

use Laravel\Scout\Searchable;

类中引用Searchable

use Searchable;

重写searchableAs()方法 toSearchableArray() 方法

 public function searchableAs() {
        return 'post';
    }
    public function toSearchableArray() {
        return [
            'title'=>$this->title,
            'content'=>$this->content
        ];
    }

控制器调用方法,展示数据

  $posts  = \App\Model\Admin::search('')->get();

sdfsdf

本作品采用《CC 协议》,转载必须注明作者和本文链接
本帖由系统于 3年前 自动加精
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
讨论数量: 32

费那个劲,es端搭好后直接调api就行

5年前 评论

file
请问创建索引的时候为什么会报错啊

4年前 评论
永恒死神 4年前
zjh159357 4年前

file 请问下这个怎么解决哈

2年前 评论

whereId(1)->update($data) 时,es没有更新呢?

3年前 评论

elasticsearch7 以上的版本报错:{"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"Root mapping definition has unsupported parameters: (truncated...),需要怎么调整

file

3年前 评论

file

查询没有反应,是我写的不对吗? 数据库 name 和 content 有 搜索的字符串

3年前 评论

file

@大佬们, @Shine-x 这个咋解决, 求教

4年前 评论

{"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"Failed to parse mapping [default]: java.util.Link (truncated...)
想问下大神们,启动es:init的时候抛出这个错误了。es版本是5.1.1的,tamayo/laravel-scout-elastic扩展也是5.0的。

4年前 评论

我想要在scout里面使用多个索引应该怎么办啊?

4年前 评论

elasticsearch有密码的情况下,怎么搞呢?代码里没看到有set账号密码的地方呢?

4年前 评论
shuxin0824 (作者) 4年前

大佬,作者麻烦把大家报的错误解决一下哈,es:init就报错了

4年前 评论
Shine-x (楼主) 4年前
Shine-x (楼主) 4年前
liangfeng (作者) 4年前
liangfeng (作者) 4年前
liangfeng (作者) 4年前
Shine-x (楼主) 4年前
kopa 4年前

@zt982865723 安装成功后 mysql还要和es进行数据同步的

4年前 评论

php artisan scout:import 显示成功 我去查询却没有数据

4年前 评论
xiaobao 4年前

执行 php artisan es:init 时候报错了

file

4年前 评论

php artisan scout:import "\App\Models\Sample" 导入数据 会发现实际上会少几条数据 我用elasticsearch-head 查看

5年前 评论

elasticsearch 实现用户搜索, 之前因为有需求,所以也搞了一个,这是在测试项目上测试的代码哈,互相学习下哈!

5年前 评论

不错,写的不错,学习了

5年前 评论

@woann 那样感觉没laravel得感觉 :joy:

5年前 评论

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