elasticsearch在Laravel中的使用以及常用命令

elasticsearch在Laravel中的使用以及常用命令

Model中

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
class Post extends Model
{
    use Searchable;
    public $timestamps = false; 
       /**
     * Get the index name for the model.
     *
     * @return string
     */
    public function searchableAs()
    {
        return 'posts_index';
    }

    /**
     * Get the indexable data array for the model.
     *
     * @return array
     */
    public function toSearchableArray()
    {
        $array = $this->toArray();

        // Customize array...

        return $array;
    }


    /**
     * 获取模型主键
     *
     * @return mixed
     */
    public function getScoutKey()
    {
        return $this->id;
    }

 }

控制器中

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Post;
use App\Models\Product;

class IndexController extends Controller
{
    public function index(){
    		
    	echo "这是首页";
    	
    }
    /**
     * 添加索引
     * @return [type]
     */
    public function insertSingle(){
    	   $Product = new Post();
		    $Product->name_zh = '中文名';
		    $Product->name_zh = '英文名';
		    $Product->save();
    }
    /**
     * 通过查询添加es
     * @return [type]
     */
    public function select(){
    	 Post::where('id','<',10)->searchable();
    	
    }
    /**
     * 通过查询删除es
     * @return [type]
     */
    public function delSelect(){
    	Post::where('id', '<', 5)->unsearchable();
    }

    /**
     * 数据更新
     * @return [type]
     */
    public  function updateSingle(){
    	$flight = Post::find(85);
    	$flight->name_zh = '中文名';
    	$flight->name_en = '英文名';
    	$flight->save();
    }

    /**
     * 添加数据自动同步es文档
     * http://127.0.0.1:9200/laravel56_shop/posts_index/85
     * @return [type]
     */
    public function insert(){
    	    $Post = new Post();
		    $Post->name_zh = '中文名';
		    $Post->name_en = '英文名';
		    $Post->save();
    }



    /**
     * es搜索
     * @param  Request
     * @return [type]
     */
    public function seacher(Request $request){
    	$keyword = $request->input('q');
    	// $posts=Post::search($keyword)->paginate(10)->toArray();
    	// var_dump($posts);
    	$info = Product::search($keyword)->where('status',2)->paginate(10)->toArray();
    	print_r($info);
    }
}

常用命令

批量导入:php artisan scout:import "App\Post"
删除所有模型的记录:php artisan scout:flush "App\Post"

参考文档

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值