james2doyle/laravel-scout-sonic

Laravel Scout 的 Sonic 驱动程序。

v3.0 2020-11-13 19:46 UTC

This package is auto-updated.

Last update: 2024-09-14 04:08:46 UTC


README

使用 Sonic 索引搜索 Eloquent 模型。

  1. 实现方式
  2. 安装
  3. 使用方法

实现方式

当实现 toSearchableArray 方法时,您需要提供一个将被转换为字符串(引擎只是用空格连接)的数组(因为 Sonic 只能索引字符串)。因此,您需要提供模型的一个 "字符串化"(索引字符串)版本。默认的 toArray 可以工作,但它可能对于合理使用来说噪声太大。

以下是我开发此引擎时使用的字符串示例

public function toSearchableArray()
{
    return array_filter([$this->display_name, $this->first_name, $this->last_name]);
}

对我来说,这为搜索构建了一个很棒的字符串,可以匹配 "名称"。在我的应用程序中,"名称" 的概念是用户显示名称或名/姓。

如果已知区域设置,您还可以在模型上创建 getSonicLocale() 方法,它返回区域设置。然后它将传递给 Sonic 的 PUSH 调用

// an ISO 639-3 locale code eg. eng for English (if set, the locale must be a valid ISO 639-3 code; if set to none, lexing will be disabled; if not set, the locale will be guessed from text)
public function getSonicLocale() {
    return 'none';
}

安装

如果您还没有安装 Laravel Scout,应将其安装到项目中,并将 Laravel\Scout\Searchable 特性应用于您想要使其可搜索的任何 Eloquent 模型。

使用 Composer 安装此包

composer require james2doyle/laravel-scout-sonic

注意:如果您使用的是 Laravel >= 5.5,则可以跳过此步骤,因为支持包自动发现。

接下来,将 ServiceProvider 添加到 config/app.php 中的包服务提供商中

/*
 * Package Service Providers...
 */
james2doyle\SonicScout\Providers\SonicScoutServiceProvider::class,

将默认配置追加到 config/scout.php

/*
|--------------------------------------------------------------------------
| Sonic Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your Sonic settings.
|
*/

'sonic' => [
    'address' => \env('SONIC_ADDRESS', 'localhost'),
    'port' => \env('SONIC_PORT', 1491),
    'password' => \env('SONIC_PASSWORD'),
    'connection_timeout' => \env('SONIC_CONNECTION_TIMEOUT', 10),
    'read_timeout' => \env('SONIC_READ_TIMEOUT',  5)
],

在您的 .env 文件中设置 SCOUT_DRIVER=sonic

此外,无需使用 php artisan scout:import 命令。

使用方法

只需在您的 Searchable 模型上调用 search() 方法即可

$users = App\User::search('bro')->get();

可以使用 where() 构建器方法应用简单的约束

$users = App\User::search('bro')->where('active', 1)->get();

注意:Sonic 不支持 "where" 的概念,因此约束是在集合级别而不是查询级别应用的!

分页

Sonic 无法支持真实分页,因为 Sonic 不返回正确的分页或总信息。它只是返回给定查询的所有结果。

已实施一个简单的分页实现,但它可能并不完美,因为它没有考虑到 "where" 过滤器。

有关更多信息,请参阅 Laravel Scout 文档