typesense/laravel-scout-typesense-driver

Laravel Scout 的 Typesense 驱动程序

v5.2.9 2024-04-07 13:33 UTC

README

此包使您能够轻松地将全文搜索支持添加到您的模型中,适用于 Laravel 7.* 到 11.*。

重要

此存储库中的 Scout 驱动程序的功能已合并到 Laravel Scout 本地 中。

因此,我们已暂时停止在此存储库中的开发,并计划在原生的 Laravel Scout 驱动程序中处理任何问题或改进。

如果有一些 Typesense 特定的功能难以在 Laravel Scout 本地实现(因为我们需要与所有其他驱动程序保持一致性),那么在这种情况下,我们计划将这些功能添加到此驱动程序中,并将其维护为某种“Scout 扩展驱动程序”。但目前还为时尚早,所以我们目前在此存储库中处于观望状态。

在此期间,我们建议切换到本地的 Laravel Scout 驱动程序,并在 Laravel Scout 存储库 中报告任何问题。

内容

安装

Typesense PHP SDK 使用 httplug 通过单个 API 与各种 PHP HTTP 库进行交互。

首先,根据您的 guzzlehttp/guzzle 版本安装正确的 httplug 适配器。例如,如果您使用的是包含 Guzzle 7 的 Laravel 8,请运行以下命令

composer require php-http/guzzle7-adapter

然后安装驱动程序

composer require typesense/laravel-scout-typesense-driver

并添加服务提供者

// config/app.php
'providers' => [
    // ...
    Typesense\LaravelTypesense\TypesenseServiceProvider::class,
],

请确保您已将 Laravel Scout 作为提供者,否则您将获得“无法解决的依赖”错误

// config/app.php
'providers' => [
    // ...
    Laravel\Scout\ScoutServiceProvider::class,
],

SCOUT_DRIVER=typesense 添加到您的 .env 文件中

然后,您应该将配置文件 scout.php 发布到您的配置目录

php artisan vendor:publish --provider="Laravel\Scout\ScoutServiceProvider"

在您的 config/scout.php 中添加

'typesense' => [
    'api_key'         => 'abcd',
    'nodes'           => [
      [
        'host'     => 'localhost',
        'port'     => '8108',
        'path'     => '',
        'protocol' => 'http',
      ],
    ],
    'nearest_node'    => [
        'host'     => 'localhost',
        'port'     => '8108',
        'path'     => '',
        'protocol' => 'http',
    ],
    'connection_timeout_seconds'   => 2,
    'healthcheck_interval_seconds' => 30,    
    'num_retries'                  => 3,
    'retry_interval_seconds'       => 1,
  ],

使用

如果您不熟悉 Laravel Scout,我们建议您首先阅读它的 文档

在安装了 scout 和 Typesense 驱动程序后,您需要将 Searchable 特性添加到您希望可搜索的模型中。另外,通过在模型上定义 toSearchableArray 方法并实现 TypesenseSearch 来定义您想要搜索的字段

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Typesense\LaravelTypesense\Interfaces\TypesenseDocument;
use Laravel\Scout\Searchable;

class Todo extends Model implements TypesenseDocument
{
    use Searchable;
    
     /**
     * Get the indexable data array for the model.
     *
     * @return array
     */
    public function toSearchableArray()
    {
        return array_merge(
            $this->toArray(), 
            [
                // Cast id to string and turn created_at into an int32 timestamp
                // in order to maintain compatibility with the Typesense index definition below
                'id' => (string) $this->id,
                'created_at' => $this->created_at->timestamp,
            ]
        );
    }

     /**
     * The Typesense schema to be created.
     *
     * @return array
     */
    public function getCollectionSchema(): array {
        return [
            'name' => $this->searchableAs(),
            'fields' => [
                [
                    'name' => 'id',
                    'type' => 'string',
                ],
                [
                    'name' => 'name',
                    'type' => 'string',
                ],
                [
                    'name' => 'created_at',
                    'type' => 'int64',
                ],
            ],
            'default_sorting_field' => 'created_at',
        ];
    }

     /**
     * The fields to be queried against. See https://typesense.org/docs/0.24.0/api/search.html.
     *
     * @return array
     */
    public function typesenseQueryBy(): array {
        return [
            'name',
        ];
    }    
}

然后,像这样与搜索服务同步数据

php artisan scout:import App\\Models\\Todo

之后,您可以使用以下方式搜索模型

Todo::search('测试')->get();

通过查询添加

searchable() 方法将查询的结果分块,并将记录添加到您的搜索索引中。示例

$todo = Todo::find(1);
$todo->searchable();

$todos = Todo::where('created_at', '<', now())->get();
$todos->searchable();

多搜索

您可以在单个 HTTP 请求中发送多个搜索请求,使用多搜索功能。

$searchRequests = [
    [
      'collection' => 'todo',
      'q' => 'todo'
    ],
    [
      'collection' => 'todo',
      'q' => 'foo'
    ]
];

Todo::search('')->searchMulti($searchRequests)->paginateRaw();

生成范围搜索密钥

您可以在其中嵌入搜索参数的范围内搜索 API 密钥。这在几种不同场景中很有用。

  1. 您可以在单个Typesense集合中索引多个用户/客户的 数据(即多租户),并创建具有嵌入的 filter_by 参数的 范围搜索键,这些参数只允许用户访问他们自己的数据子集。
  2. 您可以将任何 搜索参数(例如:exclude_fieldslimit_hits)嵌入其中,以防止用户在客户端修改它。

当您在搜索API调用中使用这些范围搜索键时,嵌入的参数将由Typesense自动应用,用户无法覆盖它们。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;
use Typesense\LaravelTypesense\Concerns\HasScopedApiKey;
use Typesense\LaravelTypesense\Interfaces\TypesenseDocument;

class Todo extends Model implements TypesenseDocument
{
    use Searchable, HasScopedApiKey;
}

使用

Todo::setScopedApiKey('xyz')->search('todo')->get();

从 devloopsnet/laravel-typesense 迁移

  • 将您的 composer.json 中的 devloopsnet/laravel-typesense 替换为 typesense/laravel-scout-typesense-driver
  • Scout驱动现在称为 typesense,而不是 typesensesearch。 这应通过设置 SCOUT_DRIVER 环境变量为 typesense,并将 config/scout.php 配置键从 typesensesearch 更改为 typesense 来体现。
  • 您应该导入 Typesense\LaravelTypesense\*,而不是 Devloops\LaravelTypesense\*
  • 模型应实现 Typesense\LaravelTypesense\Interfaces\TypesenseDocument,而不是实现 Devloops\LaravelTypesense\Interfaces\TypesenseSearch

作者

此包最初由 Abdullah Al-Faqeir 和他的公司 DevLoops 创建:[https://github.com/devloopsnet/laravel-scout-typesense-engine](https://github.com/devloopsnet/laravel-scout-typesense-engine)。此后,它已被纳入Typesense的GitHub组织。

其他主要贡献者包括

许可

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