在Lumen中使用Elasticsearch

2021-01-12  本文已影响0人  腿长袖子短

1. 安装第三方包

"require": {
        "php": ">=7.1.3",
        "fzaninotto/faker": "^1.8",
        "illuminate/redis": "v5.7.*",
        "laravel/lumen-framework": "5.7.*",
        "laravel/tinker": "^1.0",
        "predis/predis": "^1.1",
        "vlucas/phpdotenv": "~2.2",
        "fadion/bouncy": "dev-l5"
    },

2. 在项目中的配置

$app->register(Fadion\Bouncy\BouncyServiceProvider::class);

'hosts' => [
        //http://user:password@URL:port
        'http://account:password@192.168.2.59:9200'
    ]

添加加载配置文件路径函数:

public function config_path()
    {
        return app()->basePath('config');
    }
public function boot()
    {
        $this->publishes(array(
            $this->config_path('bouncy.php'),
            $this->config_path('elasticsearch.php')
        ));
    }
public function register()
    {
        $this->loadConfigFile();
    }
    
    protected function loadConfigFile(){
        $this->app->configure('elasticsearch');
    }

3. 项目中使用

namespace App\Model;
use Fadion\Bouncy\BouncyTrait;
use Illuminate\Database\Eloquent\Model;

class Goods extends Model
{
    //添加es的插件使用
    use BouncyTrait;
  
    //定义es的index
    protected $indexName = 'shop_server_index';
    //定义es的type
    protected $typeName = 'shop_server_type';

    /**
     * 与模型关联的表名
     *
     * @var string
     */
    protected $table = 'ss_goods';

    /**
     * 表的主键名称
     *
     * @var integer
     */
    protected $primaryKey = 'goods_id';

    /**
     * 指示模型是否自动维护时间戳
     *
     * @var bool
     */
    public $timestamps = false;
  
    //定义es需要搜索出来的字段
    public function documentFields()
    {
        return [
            'goods_id'=>$this->goods_id,
            'goods_name'=>$this->goods_name,
            'cate_id'=>$this->cate_id,
            'cate_name'=>$this->cate_name,
            'goods_price'=>$this->goods_price,
            'submit_time'=>$this->submit_time
        ];
    }
}
public function es()
    {
        $r = $this->goods::find(1)->index();
        return response($r);
    }
image-20200407163110937.png

4. 总结

上一篇下一篇

猜你喜欢

热点阅读