PHP code example of shrimpliu / elastic-scout

1. Go to this page and download the library: Download shrimpliu/elastic-scout library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

shrimpliu / elastic-scout example snippets


'providers' => [

    ...

    ShrimpLiu\ElasticScout\ElasticScoutServiceProvider::class,
]


use ShrimpLiu\ElasticScout\Traits\ElasticSearchable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use ElasticSearchable;

    /**
     * Get the index name for the model.
     *
     * @return string
     */
    public function searchableAs()
    {
        return 'posts_index';
    }
}


use ShrimpLiu\ElasticScout\Traits\ElasticSearchable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use ElasticSearchable;

    /**
     * 自定义索引数据
     *
     * @return array
     */
    public function toSearchableArray()
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'author_id' => $this->author_id,
            'category_id' => $this->category_id,
            'author_name' => $this->author->name,
            'content' => $this->content,
            'is_publish' => (boolean)$this->is_publish,
            'insert_time' => $this->insert_time,
            'update_time' => $this->update_time
        ];
    }
    
    public function author()
    {
        return $this->belongsTo('App\Author', 'author_id');
    }
}


use ShrimpLiu\ElasticScout\Traits\ElasticSearchable;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use ElasticSearchable;

    /**
     * 自定义索引字段类型
     *
     * @return array
     */
    public function toSearchableArray()
    {
        return [
            'id' => ['type' => 'integer'],
            'author_id' => ['type' => 'integer'],
            'category_id' => ['type' => 'integer'],
            'author_name' => ['type' => 'string', 'index' => 'not_analyzed'],
            'is_publish' => ['type' => 'boolean'],
            'insert_time' => ['type' => 'date', 'format' => 'epoch_millis'],
            'update_time' => ['type' => 'date', 'format' => 'epoch_millis']
        ];
    }
}

$posts = App\Post::search('php laravel')->get();

$posts = App\Post::search('php laravel')->filter([
    'bool' => [
        'must' => [
            ['term' => ['category_id' => 233]],
            ['term' => ['is_publish' => true]]
        ],
        'must_not' => [
            ['term' => ['id' => 234]]
        ]
    ]
])->get();

$posts = App\Post::search('php laravel')->inRandomOrder()->get();

$posts = App\Post::suggest("title", "Laravel实现ES Scout驱动")->get();
shell
php artisan scout:flush "App\Post"