laravel elasticsearch 插件scout

张映 发表于 2018-05-19

分类目录: elasticsearch, php

标签:, ,

elasticsearch的安装,以及中文分词的安装,前面几篇文章都详细的说到了。

1,安装laravel/scout

composer require laravel/scout

//修改config/app.php
'providers' => [
        //es search 加上以下内容
        Laravel\Scout\ScoutServiceProvider::class,
]

2,安装scout的es驱动

composer require tamayo/laravel-scout-elastic

3,配置scout

3.1,注册好 Scout 的服务提供器之后,你还需使用Artisan 命令 vendor:publish 生成 Scout 的配置文件

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider" //注意providers加好在执行,不然没有scout.php

3.2,修改config/app.php

'providers' => [
        //es search 加上以下内容
        Laravel\Scout\ScoutServiceProvider::class,
        ScoutEngines\Elasticsearch\ElasticsearchProvider::class,
]

3.3,修改config/scout.php

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

'elasticsearch' => [
    'index' => env('ELASTICSEARCH_INDEX', 'question1'),
    'hosts' => [
        env('ELASTICSEARCH_HOST', 'http://localhost:9200'),
    ],
],

4,创建elasticsearch的索引和模板

4.1,创建,创建es索引和模板的php文件

php artisan make:command ESInit  //创建一个ESInit.php

4.2,安装Guzzlehttp

composer require Guzzlehttp/guzzle

4.3,修改app/console/Commands/ESInit.php

<?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 question'; 

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

public function handle() { //创建template
$client = new Client();
$url = config('scout.elasticsearch.hosts')[0] . '/_template/question1'; $client->delete($url);
        $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');
        if($client->head($url)){
            $client->delete($url);
        }
        $params = [
            'json' => [
                'settings' => [
                    'refresh_interval' => '5s',
                    'number_of_shards' => 5,
                    'number_of_replicas' => 0
                ],
                'mappings' => [
                    '_default_' => [
                        '_all' => [
                            'enabled' => false
                        ]
                    ]
                ]
            ]
        ];
        $client->put($url, $params);

    }
}

4.4,加载ESInit.php,修改app/console/Kernel.php

<?php

namespace App\Console;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use Illuminate\Support\Facades\Log ;
use Illuminate\Support\Facades\App ;

class Kernel extends ConsoleKernel
{
    /**
     * The Artisan commands provided by your application.
     *
     * @var array
     */
    protected $commands = [
        \App\Console\Commands\ESInit::class  //加上
    ];

4.5,创建es索引和模板

php artisan es:init

4.6,查看模板和索引

$ curl -XGET "http://127.0.0.1:9200/_template/template_1/?pretty" //查看模板
{
  "template_1" : {
    "order" : 0,
    "index_patterns" : [
      "question1"
    ],
    "settings" : {
      "index" : {
        "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"
                  }
                }
              }
            }
          }
        ]
      }
    },
    "aliases" : { }
  }
}
$ curl -XGET 'localhost:9200/question1/?pretty'  //查看mapping
{
  "question1" : {
    "aliases" : { },
    "mappings" : {
      "_default_" : {
        "_all" : {
          "enabled" : false
        },
        "dynamic_templates" : [
          {
            "strings" : {
              "match_mapping_type" : "string",
              "mapping" : {
                "analyzer" : "ik_smart",
                "fields" : {
                  "keyword" : {
                    "type" : "keyword"
                  }
                },
                "ignore_above" : 256,
                "type" : "text"
              }
            }
          }
        ]
      },
      "question1" : {
        "_all" : {
          "enabled" : false
        },
        "dynamic_templates" : [
          {
            "strings" : {
              "match_mapping_type" : "string",
              "mapping" : {
                "analyzer" : "ik_smart",
                "fields" : {
                  "keyword" : {
                    "type" : "keyword"
                  }
                },
                "ignore_above" : 256,
                "type" : "text"
              }
            }
          }
        ],
        "properties" : {
          "collect_num" : {
            "type" : "long"
          },
          "content" : {
            "type" : "text",
            "fields" : {
              "keyword" : {
                "type" : "keyword"
              }
            },
            "analyzer" : "ik_smart"
          },
          "title" : {
            "type" : "text",
            "fields" : {
              "keyword" : {
                "type" : "keyword"
              }
            },
            "analyzer" : "ik_smart"
          },
          "type_id" : {
            "type" : "long"
          }
        }
      }
    },
    "settings" : {
      "index" : {
        "refresh_interval" : "5s",
        "number_of_shards" : "5",
        "provided_name" : "question1",
        "creation_date" : "1526698224479",
        "number_of_replicas" : "0",
        "uuid" : "AAMqTdTKSSmGhs4lCEF5Iw",
        "version" : {
          "created" : "6020399"
        }
      }
    }
  }
}

5,同步数据到elasticsearch

5.1,创建表,在这里就不详细说了

5.2,创建models文件,php artisan make:model t_question1

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Laravel\Scout\Searchable;

class t_question1 extends Model
{

    protected $table = 't_question1';
    protected $primaryKey = 'question_id';
    protected $guarded = [];
    // 可以注入是的数据字段
    protected $fillable = ['question', 'analysis', 'collect_num' , 'type_id' ];

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

    // 定义索引里面的类型
    public function searchableAs()
    {
        return 'question1';
    }

    // 定义有那些字段需要搜索
    public function toSearchableArray()
    {
        return [
            'title' => $this->question,
            'content' => $this->analysis,
            'collect_num' => $this->collect_num,
            'type_id' => $this->type_id
        ];
    }

}

5.3,将表里面的数据同步到索引中

$ php artisan scout:import "App\Models\t_question1"
Imported [App\Models\t_question1] models up to ID: 25
All [App\Models\t_question1] records have been imported.

到这儿数据库的数据就同步到,我们的es中,在这里要注意,mapping中的字段,只能加不能减的,如果想减少字段,只能删除mapping重新建索引。关于laravel中对es数据的增,删,改查,后面会详细的说明。



转载请注明
作者:海底苍鹰
地址:http://blog.51yip.com/php/1919.html

3 条评论

  1. Riley 留言

    你好,想請教一下,

    我依步驟執行完 php artisan es:init 後有在kibana 上看到index建立成功,

    執行php artisan scout:import "App\Models\t_question1"後也有成功顯示訊息,

    但數據資料卻沒有匯入,在kibana上數據是0條 。

    請問這個問題是哪方面的錯誤,謝謝!

  2. 张映 留言

    提示成功,有没有显示,成功的条数

  3. Riley 留言

    你好,謝謝你的回覆,

    有顯示成功的條數,但kibana上是0條,我後來發現是ik套件未安裝成功的問題導致,

    現在試著重新安裝,有問題再請教你,非常感謝!