pascalvgemert/laravel-cloud-search

一个在 Laravel 中以 Eloquent 方式使用 CloudSearch 的软件包

0.4.0 2021-03-11 20:38 UTC

README

在 Laravel 中以 Eloquent 方式使用 CloudSearch

需要 PHP 7.1、Laravel 5.5 或更高版本以及 Laravel AWS 软件包!

安装

您可以通过 composer 安装此软件包

composer require pascalvgemert/laravel-cloud-search

要安装 AWS 软件包,请按照 README.md 中的步骤操作:[AWS 服务提供商 for Laravel 5 & 6](https://github.com/aws/aws-sdk-php-laravel)

使用方法

您可以通过创建文档来代替使用模型,它们几乎与模型类的工作方式相同。

示例

use LaravelCloudSearch\Contracts\FieldType;
use LaravelCloudSearch\Document;
/**
 * Define your CloudSearch index fields here, this will help to define default values in your document result:
 *
 * @property-read int $id
 * @property-read string $title
 * @property-read string $description
 * @property-read string $country_code
 * @property-read array $images
 * @property-read int $stock
 * @property-read bool $pre_order
 */
class Product extends Document
{
    /** @var string */
    protected $domain = 'http://your-domain-url-for-cloudsearch.eu-west-1.cloudsearch.amazonaws.com';

    /** @var array */
    protected $casts = [
        'images' => FieldType::ARRAY,
        'pre_order' => FieldType::BOOL,
        'searchable' => FieldType::BOOL,
    ];
}

现在您可以像查询 Eloquent 模型一样查询此文档。

示例

/** @var \LaravelCloudSearch\DocumentCollection|\LaravelCloudSearch\Document[] **/
$products = Product::query()
    ->select('id')
    ->where('country_code', 'NL')
    ->where(function ($query) {
        $query
            ->where('stock', '>', 0)
            ->orWhere('pre_order', 1);
    })
    ->orderBy('price', 'asc')
    ->take(10)
    ->get();

额外的 CloudSearch 方法

调试

要调试构建查询,您可以使用与 Eloquent 一样的方式使用 getQuery() 方法。

另一个很棒的功能是,您可以挂钩到 cloudsearch.query 事件。该事件包含在 CloudSearch 执行查询所花费的 time、使用的 arguments 以及查询执行位置的 trace。例如,您可以挂钩 CloudSearch 查询到 [Laravel-Debugbar](https://github.com/barryvdh/laravel-debugbar)。

在 Laravel 中,您可以通过以下方式监听事件

Event::listen('cloudsearch.query', function ($timeInMilliSeconds, $arguments, $trace) {
    dump($timeInMilliSeconds, $arguments, $trace);
});

搜索

要执行模糊搜索,您可以使用 phrase(string $searchPhrase, int|float $fuzziness = null, bool $lookForAnyWord = false) 方法。

$fuzziness 是一个 0 到 1 之间的十进制百分比,默认值为 0.25。而 $lookForAnyWord 是一个布尔值,用于搜索所有或任何单词,默认是所有单词。

细分

CloudSearch 中一个非常常用的功能是使用细分(Facets)或桶(Buckets)。您可以在构建查询时轻松考虑这一点。

/** @var \LaravelCloudSearch\DocumentCollection **/
$products = Product::facet('country_code', ['size' => 10])->get();

/** @var \Illuminate\Support\Collection|\LaravelCloudSearch\Facet[] **/
$productFacets = $products->getFacets();

统计数据(stats)

对于 AWS CloudSearch 中的统计数据或 stats 也是如此。

/** @var \LaravelCloudSearch\DocumentCollection **/
$products = Product::statistics('country_code')->get();

/** @var \Illuminate\Support\Collection **/
$productStatistics = $products->getStatistics();