PHP code example of tp5er / think-scout

1. Go to this page and download the library: Download tp5er/think-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/ */

    

tp5er / think-scout example snippets


declare (strict_types = 1);
namespace app\model;
use think\Model;
use tp5er\think\scout\Searchable;
use think\facade\Event;
use tp5er\think\scout\DataSync;
/**
 * @mixin \think\Model
 */
class User extends Model
{
    use Searchable;
    
    public static function onAfterDelete(Model $model)
    {
       // Event::trigger('onScoutDeleted', $model);
       // 或
       // (new DataSync($model))->chunkDeleted(1);
       
    }

    public static function onAfterWrite(Model $model)
    {
       // Event::trigger('onScoutUpdated', $model);
       // 或
       // (new DataSync($model))->chunkUpdated(1);
    }


return [
    /**
     * Default Search Engine
     * Supported:  "collection", "null" "elastic"
     */
    'default'     => env('SCOUT_DRIVER', 'collection'),
    //Soft Deletes
    'soft_delete' => false,
    //分块处理数据
    'chunk'       => 20,
    //engine Configuration
    'engine'      => [
        'collection' => [
            'driver' => \tp5er\think\scout\Engines\CollectionEngine::class,
        ],
        'null'       => [
            'driver' => \tp5er\think\scout\Engines\NullEngine::class,
        ],
        'elastic'    => [
            'driver' => \tp5er\think\scout\Engines\ElasticEngine::class,
            'prefix' => '',
            //https://www.elastic.co/guide/cn/elasticsearch/php/current/_configuration.html
            'hosts'  => [
                [
                    'host'   => 'localhost',
                    'port'   => "9200",
                    'scheme' => null,
                    'user'   => null,
                    'pass'   => null,
                ],
            ],
        ]
    ],
];
~~~

## 配置模型索引

每个模型与给定的搜索「索引」同步,这个「索引」包含该模型的所有可搜索记录。换句话说,你可以把每一个「索引」设想为一张 MySQL
数据表。默认情况下,每个模型都会被持久化到与模型的「表」名(通常是模型名称的复数形式)相匹配的索引。你也可以通过覆盖模型上的 searchableAs 方法来自定义模型的索引:

~~~

declare (strict_types = 1);
namespace app\model;
use think\Model;
use tp5er\think\scout\Searchable;

/**
 * @mixin \think\Model
 */
class User extends Model
{
    use Searchable;
    
    /**
     * Get the index name for the model.
     *
     * @return string
     */
    public function searchableAs()
    {
        return $this->getTable();
    }

declare (strict_types = 1);
namespace app\model;
use think\Model;
use tp5er\think\scout\Searchable;

/**
 * @mixin \think\Model
 */
class User extends Model
{
    use Searchable;
    
    /**
     * Determine if the model should be searchable.
     *
     * @return bool
     */
    public function shouldBeSearchable()
    {
        return true;
    }