PHP code example of hyperf-ext / scout

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

    

hyperf-ext / scout example snippets


use Hyperf\Database\Model\Model;
use HyperfExt\Scout\Searchable;

class Post extends Model
{
    use Searchable;
}

[
    // 索引前缀
    'prefix' => env('SCOUT_PREFIX', ''),
    // 命令行操作时的协程并发数
    'concurrency' => env('SCOUT_CONCURRENCY', 100),
    // 控制批量操作文档时分块处理的数量
    'chunk' => [
        'searchable' => 500,
        'unsearchable' => 500,
    ],
    // 是否启用索引文档软删除
    'soft_delete' => true,
    // 控制索引、更新、删除等文档操作所做的更改何时对搜索可见,可能的值 true(或空字符串)、false、'wait_for'
    // 详细描述 https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-refresh.html
    'document_refresh' => true,
];



declare(strict_types=1);

namespace App\Models;

use Hyperf\Database\Model\Model;
use HyperfExt\Scout\Searchable;

class Post extends Model
{
    use Searchable;

    // 使用 `scoutSettings` 属性配置
    protected $scoutSettings = [
        'analysis' => [
            'analyzer' => [
                'es_std' => [
                    'type' => 'standard',
                    'stopwords' => '_spanish_'
                ]
            ]    
        ],
    ];

    // 或者重写 `getScoutSettings` 方法配置
    public function getScoutSettings(): ?array
    {
        return [
            'analysis' => [
                'analyzer' => [
                    'es_std' => [
                        'type' => 'standard',
                        'stopwords' => '_spanish_'
                    ]
                ]    
            ],
        ];
    }
}



declare(strict_types=1);

namespace App\Models;

use Hyperf\Database\Model\Model;
use HyperfExt\Scout\Searchable;

class Post extends Model
{
    use Searchable;
    
    // 使用 `scoutMapping` 属性配置
    protected $scoutMapping = [
       'properties' => [
           'title' => ['type' => 'text'],
       ],
    ];

    // 或者重写 `getScoutMapping` 方法配置
    public function getScoutMapping(): array
    {
        return [
            'properties' => [
                'title' => ['type' => 'text'],
            ],
        ];
    }
}



declare(strict_types=1);

namespace App\Models;

use Hyperf\Database\Model\Model;
use HyperfExt\Scout\Searchable;

class Post extends Model
{
    use Searchable;

    /**
     * 获取模型的索引名称。
     */
    public function searchableAs(): string
    {
        return 'posts_index';
    }
}



declare(strict_types=1);

namespace App\Models;

use Hyperf\Database\Model\Model;
use HyperfExt\Scout\Searchable;

class Post extends Model
{
    use Searchable;

    /**
     * 获取模型的可搜索数据。
     */
    public function toSearchableArray(): array
    {
        $array = $this->toArray();

        // 自定义数组...

        return $array;
    }
}



declare(strict_types=1);

namespace App\Models;

use Hyperf\Database\Model\Model;
use HyperfExt\Scout\Searchable;

class User extends Model
{
    use Searchable;

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

    /**
     * 获取模型键名。
     *
     * @return mixed
     */
    public function getScoutKeyName()
    {
        return 'email';
    }
}

$order = new App\Models\Order;

// ...

$order->save();

// 通过模型查询构造器添加...
App\Models\Order::where('price', '>', 100)->searchable();

// 你也可以通过模型关系增加记录...
$user->orders()->searchable();

// 你也可以通过集合增加记录...
$orders->searchable();

$order = App\Models\Order::find(1);

// 更新订单...

$order->save();

//  通过模型查询更新...
App\Models\Order::where('price', '>', 100)->searchable();

// 你也可以通过数据间的关联进行更新...
$user->orders()->searchable();

// 你也可以通过数据集合进行更新...
$orders->searchable();

$order = App\Models\Order::find(1);

$order->delete();

// 通过模型查询删除...
App\Models\Order::where('price', '>', 100)->unsearchable();

// 你可以通过数据间的关系进行删除...
$user->orders()->unsearchable();

// 你可以通过数据集合进行删除...
$orders->unsearchable();

App\Models\Order::withoutSyncingToSearch(function () {
    // 执行模型操作...
});

public function shouldBeSearchable()
{
    return $this->isPublished();
}

// 此处将遵循 "shouldBeSearchable" 结果...
App\Models\Order::where('price', '>', 100)->searchable();

$user->orders()->searchable();

$order->save();

// 此处将覆盖 "shouldBeSearchable" 结果...
$orders->searchable();

$order->searchable();

// 获取模型集合
$orders = App\Models\Order::search('Star Trek')->get();

// 获取单个模型
$order = App\Models\Order::search('Star Trek')->first();

$orders = App\Models\Order::search('Star Trek')->getRaw();

$orders = App\Models\Order::search('Star Trek')
    ->within('tv_shows_popularity_desc')
    ->get();

use HyperfExt\Scout\QueryBuilder;

$films = App\Models\Film::search()
    ->mustWhereLike('title', 'Star*')
    ->shouldWhere('category_id', 1)
    ->shouldWhere('category_id', 5)
    ->whereBetween('rating', [7, 10])
    ->mustWhereNested('tags', function (QueryBuilder $query) {
        $query->whereMatch('tags.title', 'sf');
    })
    ->notWhere('id', 2)
    ->minScore(0.5)
    ->size(5)
    ->orderBy('created_at', 'desc')
    ->get();

whereIn(string $field, array $values, array $parameters = [])
whereBetween(string $field, array $values, array $parameters = [])
whereExists(string $field)
whereRegexp(string $field, string $value, string $flags = 'ALL')
whereLike(string $field, string $value, array $parameters = [])
wherePrefix(string $field, string $value, array $parameters = [])
whereFuzzy(string $field, string $value, array $parameters = [])
whereIdsIn(array $values, array $parameters = [])
whereGeoDistance(string $field, string $distance, $location, array $parameters = [])
whereGeoBoundingBox(string $field, array $values, array $parameters = [])
whereGeoPolygon(string $field, array $points, array $parameters = [])
whereGeoShape(Closure $closure, array $parameters = ['relation' => 'INTERSECTS'])
whereMatchAll(array $parameters = [])
whereMatch(string $field, string $value, array $parameters = [])
whereMultiMatch(array $fields, string $value, array $parameters = [])
whereMatchPhrase(string $field, string $value, array $parameters = [])
whereMatchPhrasePrefix(string $field, string $value, array $parameters = [])
whereQueryString(string $value, array $parameters = [])
whereSimpleQueryString(string $value, array $parameters = [])
whereNested(string $path, Closure $callback, array $parameters = [])

use ONGR\ElasticsearchDSL\Search;

// 通过 `dsl` 方法传递闭包函数来访问 `Search` 实例
$orders = App\Models\Order::search()->dsl(function (Search $search) {
    // ...
})->get();

// 或者通过 `getSearch` 方法获取 `Search` 实例
$query = App\Models\Order::search();
$search = $query->getSearch();
$search->addQuery(...);
$orders = $query->get();

$orders = App\Models\Order::search()->raw([
    'bool' => [
        'must' => [
            'match' => [...],
            'term' => [...],
        ],
    ],
])->get();

$orders = App\Models\Order::search('Star Trek')->paginate();

$orders = App\Models\Order::search('Star Trek')->paginate(15);

'soft_delete' => true,

// 检索结果时包含已删除记录...
$orders = App\Models\Order::search('Star Trek')->withTrashed()->get();

// 检索结果时仅包含已删除记录...
$orders = App\Models\Order::search('Star Trek')->onlyTrashed()->get();
shell script
php bin/hyperf.php vendor:publish hyperf-ext/scout
shell script
php bin/hyperf.php scout:index:create "App\Models\Post"
shell script
php bin/hyperf.php scout:index:update "App\Models\Post"
shell script
php bin/hyperf.php scout:index:drop "App\Models\Post"
shell script
php bin/hyperf.php scout:mapping:update "App\Models\Post"
shell script
php bin/hyperf.php scout:import "App\Models\Post"
shell script
php bin/hyperf.php scout:flush "App\Models\Post"