laravel elasticsearch 插件scout

张映 发表于 2018-05-19

分类目录: php

标签:, ,

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

1,安装laravel/scout

composer require laravel/scout

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"

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

留下评论

留下评论
  • (必需)
  • (必需) (will not be published)
  • (必需)   5X6=?