studioespresso/craft-scout

Craft Scout 为添加全文搜索到您的条目提供了一个简单解决方案。Scout 将自动将搜索索引与您的条目保持同步。

资助包维护!
janhenckens

安装: 102,387

依赖项: 0

建议者: 0

安全性: 0

星标: 81

观察者: 6

分支: 55

开放问题: 13

类型:craft-plugin

5.0.1 2024-08-05 18:25 UTC

README

Craft Scout 为添加全文搜索到您的条目提供了一个简单解决方案。Scout 将自动将搜索索引与您的条目保持同步。

Scout

需求

此插件需要 Craft CMS 4.x 或更高版本以及 PHP 8.0.2 或更高版本。

安装

打开您的终端并转到您的 Craft 项目

# go to the project directory
cd /path/to/my-craft-project.dev

# tell Composer to install the plugin
composer require studioespresso/craft-scout

# tell Craft to install the plugin
php craft plugin/install scout

设置

为了定义您的索引,将 scout.php 文件复制到您的 config 文件夹。

<?php

return [
    /*
     * Scout listens to numerous Element events to keep them updated in
     * their respective indices. You can disable these and update
     * your indices manually using the commands.
     */
    'sync' => true,

    /*
     * 
     * @depcretio
     * By default Scout handles all indexing in a queued job, you can disable
     * this so the indices are updated as soon as the elements are updated
     * 
     * Disabling the `queue` option will no longer be supported in the next version of Scout
     * 
     */
    'queue' => true,

    /*
     * The connection timeout (in seconds), increase this only if necessary
     */
    'connect_timeout' => 1,

    /*
     * The batch size Scout uses when importing a large amount of elements
     */
    'batch_size' => 1000,
    
    /*
     * By default Scout will index elements related to the element being save (that are in the same index). 
     * Disabling this can improve performance on larger sites that have lots of relations.
     */
    'indexRelations' => true,
    
    /**
     * The element types to look for when indexRelations is enabled.
     * By default, all Craft elements are checked for relations.
     * Use this to avoid unnecessary queries to Elements that aren't
     * used by your indices or to check custom Elements that may be
     * related to your indices
     */
    'relatedElementTypes' => [],

    /*
     * The Algolia Application ID, this id can be found in your Algolia Account
     * https://www.algolia.com/api-keys. This id is used to update records.
     */
    'application_id' => '$ALGOLIA_APPLICATION_ID',

    /*
     * The Algolia Admin API key, this key can be found in your Algolia Account
     * https://www.algolia.com/api-keys. This key is used to update records.
     */
    'admin_api_key'  => '$ALGOLIA_ADMIN_API_KEY',

    /*
     * The Algolia search API key, this key can be found in your Algolia Account
     * https://www.algolia.com/api-keys. This search key is not used in Scout
     * but can be used through the Scout variable in your template files.
     */
    'search_api_key' => '$ALGOLIA_SEARCH_API_KEY', //optional
    
    /*
     * A collection of indices that Scout should sync to, these can be configured
     * by using the \rias\scout\ScoutIndex::create('IndexName') command. Each
     * index should define an ElementType, criteria and a transformer.
     */
    'indices'       => [],
];

示例索引配置

<?php

return [
    'indices'       => [
        \rias\scout\ScoutIndex::create('Blog')
            // Scout uses this by default, so this is optional
            ->elementType(\craft\elements\Entry::class)
            // If you don't define a siteId, the primary site is used
            ->criteria(function (\craft\elements\db\EntryQuery $query) {
                return $query->section('blog');
            })
            /*
             * The element gets passed into the transform function, you can omit this
             * and Scout will use the \rias\scout\ElementTransformer class instead
            */
            ->transformer(function (\craft\elements\Entry $entry) {
                return [
                    'title' => $entry->title,
                    'body' => $entry->body,
                ];
            })
            /*
             * You can use this to define index settings that get synced when you call
             * the ./craft scout/settings/update console command. This way you can
             * keep your index settings in source control. The IndexSettings
             * object provides autocompletion for all Algolia's settings
            */
            ->indexSettings(
                \rias\scout\IndexSettings::create()
                    ->minWordSizefor1Typo(4)
            )
    ],
];

->elementType(string $class)

此索引包含的元素类型,默认情况下 Scout 使用 craft\elements\Entry::class

Craft 的默认元素类型类包括

  • craft\elements\Asset
  • craft\elements\Entry
  • craft\elements\User

->criteria(callable $query)

此函数接受一个 ElementQuery 并应返回一个 ElementQuery

->criteria(function (ElementQuery $query) {
    return $query->section('blog');
});

->transformer(callable|string|array|TransformerAbstract $transformer)

用于定义应发送到 Algolia 的每个元素的数据的 transformer。如果您不设置此选项,则将使用默认的 transformer,它包括元素的所有直接属性值,但不包括自定义字段值。

// Can be set to a function
->transformer(function(craft\elements\Entry $entry) {
    return [
        'title' => $entry->title,
        'id' => $entry->id,
        'url' => $entry->url,
    ];
}),

// Or a string/array that defines a Transformer class configuration
->transformer('MyTransformerClassName'),

// Or a Transformer class instance
->transformer(new MyTransformerClassName()),

您的自定义 transformer 类可能看起来像这样

<?php

use craft\elements\Entry;
use League\Fractal\TransformerAbstract;

class MyTransformerClassName extends TransformerAbstract
{
    public function transform(Entry $entry)
    {
        return [
            // ...
        ];
    }
}

->splitElementsOn(array $keys)

对于长文档,建议将元素分成多行,以保持每行数据大小在合理范围内。这可以通过使用 splitElementsOn() 完成。

请确保为这些键返回一个数组。

->splitElementsOn([
    'summary',
    'matrixFieldHandle'
])

重要 - distinctID(在索引后可用)必须设置为用于删除对象的分割元素的属性,以便在使用 splitElementsOn 时生效。

->indexSettings(IndexSettings $settings)

您可以使用此功能来定义在调用 ./craft scout/settings/update 控制台命令时同步的索引设置。这样,您可以保持索引设置在源代码控制中。IndexSettings 对象为 Algolia 的所有设置提供自动完成。

注意

请注意,设置不会自动同步,而只能在运行 ./craft scout/settings/update 控制台命令时同步。

->indexSettings(
    \rias\scout\IndexSettings::create()
        ->minWordSizefor1Typo(4)
)

副本

可以使用 IndexSettings 上的 replicas 函数创建副本。要配置副本,请将它们包含在 indices 数组中,并将它们的 replicaIndex 设置为 true,这样它们就不会包含在任何同步操作中。

可以使用 ./craft scout/settings/update 控制台命令更新副本索引的配置。

<?php

return [
    'indices' => [
        \rias\scout\ScoutIndex::create('Products')
            // ...
            ->indexSettings(
                \rias\scout\IndexSettings::create()
                    ->minWordSizefor1Typo(4)
                    ->replicas(['virtual(Products_desc)'])
            )
    ],
    [
        \rias\scout\ScoutIndex::create('Products_desc')
            ->replicaIndex(true)
            ->indexSettings(IndexSettings::create()->customRanking(['desc(price)'])),
    ],
];

Twig 变量

您可以通过以下 Twig 变量访问在您的配置文件中设置的 Algolia 设置。

{{ craft.scout.pluginName }}
{{ craft.scout.algoliaApplicationId }}
{{ craft.scout.algoliaAdminApiKey }}
{{ craft.scout.algoliaSearchApiKey }}

控制台命令

Scout 提供了两个简单的控制台命令来管理您的索引。

导入

要导入一个或所有索引,您可以在控制台中运行以下命令

./craft scout/index/import <indexName?>

不需要指定 indexName 参数,省略它时,所有映射都将被导入。

刷新/清除

清除索引就像在您的控制台中运行一个命令一样简单。

./craft scout/index/flush <indexName?>

与导入命令一样,不需要指定 indexName

在刷新时,Scout 会要求您确认是否真的想要清除索引中的所有数据。您可以通过附加一个 --force 标志来跳过确认。

刷新

先执行刷新/清除操作,然后再重新导入索引。

./craft scout/index/refresh <indexName?>

跳过元素

您可以通过从 transform 方法返回一个 空数组 来省略一个元素被索引。

ScoutIndex::create()
    ->transform(function (Entry $entry) {
        // Check if entry is valid for indexing
        $isValid = yourCustomValidation($entry);
        
        // If entry fails validation, return empty array
        if (! $isValid) {
            return [];
        }
    
        // Return normal data attributes
        return [
            'name' => $entry->title,
            ...
            'lorem' => $entry->lorem,
            'ipsum' => $entry->ipsum,
        ];
    });

事件

ShouldBeSearchableEvent

此事件允许您自定义在保存时(或者更具体地说,每次触发 SearchableBehaviour 时)检查哪些元素或元素类型。

use rias\scout\behaviors\SearchableBehavior;
use rias\scout\events\ShouldBeSearchableEvent;

Event::on(
    SearchableBehavior::class, 
    SearchableBehavior::EVENT_SHOULD_BE_SEARCHABLE, 
    function (ShouldBeSearchableEvent $event) {
        $event->shouldBeSearchable = false;
});

该事件具有以下属性

  • $element(正在保存的元素)
  • $shouldBeSearchable(元素是否应可搜索,默认为 true

此用例的一个示例是检查正在保存的元素的类型,并在它是 Matrix 块时将 shouldBeSearchable 设置为 false

AfterIndexImport

此事件在 ImportIndex 作业结束时运行,当所有项目都已处理完毕。

use rias\scout\events\AfterIndexImport;
use rias\scout\jobs\ImportIndex;

Event::on(
    ImportIndex::class,
    ImportIndex::EVENT_AFTER_INDEX_IMPORT,
    function (AfterIndexImport $event) {
        // Your code here
    });

该事件有一个属性

  • $indexName(刚刚完成导入的索引名称)

此用例的一个示例是如果您按计划运行导入,则可以记录或更新 dateLastImported。

从 1.x 升级

配置与 Scout v1 的配置方式不同。请参阅下面的设置部分,了解如何配置 Scout。

以下更改最为显著

  • 配置键 mappings 已更改为 indices,并且有新的方式来配置索引
  • 现在,criteria 是一个返回 ElementQuery 的可调用函数。每个索引应在准则中定义一个 siteId,否则将选择主站点。
  • 在设置中添加了新的 queuebatch 选项
  • 映射上的旧配置键已被替换为 rias\scout\ScoutIndex 对象上的函数。

Studio EspressoRias 提供