devnoiseconsulting/laravel-scout-postgres-tsvector

Laravel Scout 的 PostgreSQL 全文搜索驱动程序

v9.1.2 2023-04-28 15:22 UTC

README

Build Status Latest Stable Version Software License

此包使得使用原生 PostgreSQL 全文搜索功能与 Laravel Scout 非常容易。

内容

安装

您可以通过 composer 安装此包

composer require devnoiseconsulting/laravel-scout-postgres-tsvector

Laravel

如果您正在使用 Laravel < 5.5 或如果您已关闭包自动发现,您必须手动注册服务提供者

// config/app.php
'providers' => [
    ...
    ScoutEngines\Postgres\PostgresEngineServiceProvider::class,
],

配置

配置引擎

在 Laravel Scout 配置文件 config/scout.php 中指定用于访问索引文档的数据库连接

// config/scout.php
...
'pgsql' => [
    // Connection to use. See config/database.php
    'connection' => env('DB_CONNECTION', 'pgsql'),
    // You may want to update index documents directly in PostgreSQL (i.e. via triggers).
    // In this case you can set this value to false.
    'maintain_index' => true,
    // You can explicitly specify what PostgreSQL text search config to use by scout.
    // Use \dF in psql to see all available configurations in your database.
    'config' => 'english',
    // You may set the default querying method
    // Possible values: plainquery, phrasequery, tsquery
    // plainquery is used if this option is omitted.
    'search_using' => 'tsquery'
],
...

配置 PostgreSQL

确保全局(在 postgresql.conf 中)、特定数据库(ALTER DATABASE ... SET default_text_search_config TO ...)或另设 default_text_search_config 在每个会话中设置了适当的 默认文本搜索配置

要检查当前值

SHOW default_text_search_config;

准备模式

默认情况下,引擎期望解析的文档(模型数据)存储在与模型相同的表中,在类型为 tsvectorsearchable 列中。您需要在模式中创建此列和索引。您可以在 PostgreSQL 中选择 GINGiST 索引。

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->text('title');
            $table->text('content')->nullable();
            $table->integer('user_id');
            $table->timestamps();
        });

        DB::statement('ALTER TABLE posts ADD searchable tsvector NULL');
        DB::statement('CREATE INDEX posts_searchable_index ON posts USING GIN (searchable)');
        // Or alternatively
        // DB::statement('CREATE INDEX posts_searchable_index ON posts USING GIST (searchable)');
    }

    public function down()
    {
        Schema::drop('posts');
    }
}

配置可搜索数据

除了模型属性外,您还可以将其他任何数据带到索引文档中。例如,文章的标签列表。

public function toSearchableArray()
{
    return [
        'title' => $this->title,
        'content' => $this->content,
        'author' => $this->user->name,
        'tags' => $this->tags->pluck('tag')->implode(' '),
    ];
}

配置模型

您可以通过在模型中实现 searchableOptions() 来调整特定模型引擎的行为。

class Post extends Model
{
    use Searchable;

    // ...
    public function searchableOptions()
    {
        return [
            // You may wish to change the default name of the column
            // that holds parsed documents
            'column' => 'indexable',
            // You may want to store the index outside of the Model table
            // In that case let the engine know by setting this parameter to true.
            'external' => true,
            // If you don't want scout to maintain the index for you
            // You can turn it off either for a Model or globally
            'maintain_index' => true,
            // Ranking groups that will be assigned to fields
            // when document is being parsed.
            // Available groups: A, B, C and D.
            'rank' => [
                'fields' => [
                    'title' => 'A',
                    'content' => 'B',
                    'author' => 'D',
                    'tags' => 'C',
                ],
                // Ranking weights for searches.
                // [D-weight, C-weight, B-weight, A-weight].
                // Default [0.1, 0.2, 0.4, 1.0].
                'weights' => [0.1, 0.2, 0.4, 1.0],
                // Ranking function [ts_rank | ts_rank_cd]. Default ts_rank.
                'function' => 'ts_rank_cd',
                // Normalization index. Default 0.
                'normalization' => 32,
            ],
            // You can explicitly specify a PostgreSQL text search configuration for the model.
            // Use \dF in psql to see all available configurationsin your database.
            'config' => 'simple',
        ];
    }
}
...

如果您决定将模型的索引保留在模型表之外,您可以通知引擎您希望将额外的字段推送到索引表,然后可以使用 Scout Builder 中的 where() 来过滤结果集。在这种情况下,您需要在模型上实现 searchableAdditionalArray()。当然,外部表的架构应包括这些额外的列。

public function searchableAdditionalArray()
{
    return [
        'user_id' => $this->user_id,
    ];
}

您可能希望将可搜索列隐藏起来,以免影响您

protected $hidden = [
    'searchable',
];

使用

// plainto_tsquery()
$posts = App\Post::search('cat rat')
    ->usingPlainQuery()->get()

// phraseto_tsquery()
$posts = App\Post::search('cat rat')
    ->usingPhraseQuery()->get()

// to_tsquery()
$posts = App\Post::search('fat & (cat | rat)')
    ->usingTsQuery()->get()

// websearch_to_tsquery()
// uses web search syntax
$posts = App\Post::search('"sad cat" or "fat rat" -mouse')
    ->usingWebSearchQuery()->get()

// DIY using a callback
use ScoutEngines\Postgres\TsQuery\ToTsQuery;

$results = App\Post::search('fat & (cat | rat)', function ($builder, $config) {
    return new ToTsQuery($builder->query, $config);
})->get();

请参阅 官方文档 了解如何使用 Laravel Scout。

测试

composer test

安全性

如果您发现任何安全问题,请通过电子邮件 flynnmj@devnoise.com 联系我们,而不是使用问题跟踪器。

变更日志

请参阅 CHANGELOG 了解最近有哪些变化。

贡献

请参阅 CONTRIBUTING 了解详细信息。

致谢

许可证

MIT 许可证 (MIT)。有关更多信息,请参阅 许可证文件