harlan-zw / laravel-swiftype


README

Total Downloads Total Downloads StyleCI

Laravel Swiftype 是一个用于 elastic/app-search 的包装器,并提供了一些 Laravel 特定的辅助工具,以便轻松地将 Eloquent 模型与 Swiftype 集成。

安装

通过 Composer

composer require harlan-zw/laravel-swiftype

如果您未运行 Laravel 5.5(或更高版本),则请在 config/app.php 中添加服务提供者

Loonpwn\Swiftype\SwiftypeServiceProvider::class,

用法

在您的 .env 文件中,添加以下变量。

SWIFTYPE_DEFAULT_ENGINE=
SWIFTYPE_API_PRIVATE_KEY=
SWIFTYPE_HOST_IDENTIFIER=

Swiftype 凭据 页面获取您的密钥。

当自行托管 AppSearch 实例时,您可以使用凭据页面显示的 API 端点作为 SWIFTYPE_HOST_IDENTIFIER,例如。

SWIFTYPE_HOST_IDENTIFIER=https://:3002

API

此软件包有两个 Facade,可让您访问底层的 Swiftype 客户端。

Swiftype

Swiftype Facade 是对 https://github.com/elastic/app-search-php 中构建的客户端的直接包装。基客户端上的任何命令都可以在此 Facade 上使用。示例

  • Swiftype::listEngines($currentPage = null, $pageSize = null) - 显示所有可用的引擎

  • Swiftype::createEngine($name, $language = 'en') - 根据名称查找引擎

具有 IDE 自动完成功能

/** @var \Loonpwn\Swiftype\Clients\Api $api */
$api = app(Swiftype::class);

SwiftypeEngine

SwiftypeEngine 是在 Swiftype Facade 上方的包装,具有直接上下文默认引擎。核心 API 中的许多相同功能都可在该 Facade 中使用,无需指定引擎。

SwiftypeEngine::search($query, $options) - 在引擎中搜索文档

SwiftypeEngine::indexDocument($document) - 根据主键创建新文档或更新现有文档。此函数将使用转换器确保主键被转换仅为 id

SwiftypeEngine::indesDocuments($document) - 与上述类似,但将列表中的模型分块为每请求 100 个

SwiftypeEngine::deleteDocument($documentId) - 删除文档。

SwiftypeEngine::deleteDocuments($documentIds) - 接受文档 ID 数组并删除它们。

SwiftypeEngine::listDocuments($page = 1, $pageSize = 100) - 列出属于引擎的文档,具有分页。

SwiftypeEngine::listAllDocumentsByPages($action, $page = 1, $pageSize = 100) - 列出属于引擎的文档,将迭代所有页面并调用您的自定义操作。

SwiftypeEngine::purgeAllDocuments() - 将从 Swiftype 删除所有文档

特性

IsSwiftypeDocument 是一个可用的特性,它钩入模型的 saved 事件挂钩。在保存时发生以下操作

  • shouldSyncSwiftypeOnSave 被检查并必须通过 true 以继续
  • getSwiftypeAttributes 被调用来获取要发送到 Swiftype 的属性

您应覆盖这些函数以实现特定业务逻辑。

/**
 * Should model changes be pushed to Swiftype. Excludes deleting
 * @return bool
 */
public function shouldSyncSwiftypeOnSave()
{
    // by default all model changes are pushed to swiftype
    return true;
}

/**
 * Get the mapped attribute values for Swiftype
 * @return mixed|null
 */
public function getSwiftypeAttributes()
{
    // Document transformer is the default transformer, feel free to implement your own
    return transform($this, new DocumentTransformer());
}

作业

目前只创建了与 Eloquent 模型事件直接相关的作业。这些可以用于排队数据同步。

  • DeleteDocument($documentId) - 删除特定文档,接受文档 ID
  • IndexDocument($document) - 推送单个文档。接受映射的文档
  • SyncDocuments - 遍历 Swiftype 和本地数据库中的所有文档,以查找不匹配的文档并添加或删除它们。这使用 swiftype.sync_models 配置

测试

$ composer test

安全性

如果您发现任何安全相关的问题,请通过电子邮件harlan@harlanzw.com联系,而不是使用问题跟踪器。